Java Reference
In-Depth Information
(a)
(b)
(c)
F IGURE 6.15
Each ball takes a random path and falls into a slot.
Balls are dropped from the opening of the board. Every time a ball hits a nail, it
has a 50% chance of falling to the left or to the right. The piles of balls are accu-
mulated in the slots at the bottom of the board.
Write a program that simulates the bean machine. Your program should prompt
the user to enter the number of the balls and the number of the slots in the
machine. Simulate the falling of each ball by printing its path. For example, the
path for the ball in Figure 6.15b is LLRRLLR and the path for the ball in Figure
6.15c is RLRRLRR. Display the final buildup of the balls in the slots in a his-
togram. Here is a sample run of the program:
5
Enter the number of balls to drop:
Enter the number of slots in the bean machine:
7
LRLRLRR
RRLLLRR
LLRLLRR
RRLLLLL
LRLRRLR
O
O
OOO
( Hint : Create an array named slots . Each element in slots stores the number
of balls in a slot. Each ball falls into a slot via a path. The number of Rs in a
path is the position of the slot where the ball falls. For example, for the path
LRLRLRR, the ball falls into slots[4] , and for the path is RRLLLLL, the
ball falls into slots[2] .)
***6.22
( Game: Eight Queens ) The classic Eight Queens puzzle is to place eight queens
on a chessboard such that no two queens can attack each other (i.e., no two
queens are on the same row, same column, or same diagonal). There are many
possible solutions. Write a program that displays one such solution. A sample
output is shown below:
|Q| | | | | | | |
| | | | |Q| | | |
| | | | | | | |Q|
| | | | | |Q| | |
| | |Q| | | | | |
| | | | | | |Q| |
| |Q| | | | | | |
| | | |Q| | | | |
 
Search WWH ::




Custom Search