Java Reference
In-Depth Information
**6.23
( Game: locker puzzle ) A school has 100 lockers and 100 students. All lockers are
closed on the first day of school. As the students enter, the first student, denoted
S1, opens every locker. Then the second student, S2, begins with the second
locker, denoted L2, and closes every other locker. Student S3 begins with the third
locker and changes every third locker (closes it if it was open, and opens it if it was
closed). Student S4 begins with locker L4 and changes every fourth locker. Stu-
dent S5 starts with L5 and changes every fifth locker, and so on, until student S100
changes L100.
After all the students have passed through the building and changed the lockers,
which lockers are open? Write a program to find your answer.
( Hint : Use an array of 100 Boolean elements, each of which indicates whether a
locker is open ( true ) or closed ( false ). Initially, all lockers are closed.)
**6.24
( Simulation: coupon collector's problem ) Coupon collector is a classic statistics
problem with many practical applications. The problem is to pick objects from a
set of objects repeatedly and find out how many picks are needed for all the
objects to be picked at least once. A variation of the problem is to pick cards from
a shuffled deck of 52 cards repeatedly and find out how many picks are needed
before you see one of each suit. Assume a picked card is placed back in the deck
before picking another. Write a program to simulate the number of picks needed to
get four cards from each suit and display the four cards picked (it is possible a card
may be picked twice). Here is a sample run of the program:
VideoNote
Coupon collector's problem
Queen of Spades
5 of Clubs
Queen of Hearts
4 of Diamonds
Number of picks: 12
6.25
( Algebra: solve quadratic equations ) Write a method for solving a quadratic equa-
tion using the following header:
public static int solveQuadratic( double [] eqn, double [] roots)
ax 2
The coefficients of a quadratic equation are passed to the array
eqn and the noncomplex roots are stored in roots. The method returns the number
of roots. See Programming Exercise 3.1 on how to solve a quadratic equation.
Write a program that prompts the user to enter values for a , b , and c and displays
the number of roots and all noncomplex roots.
+
bx
+
c
=
0
6.26
( Strictly identical arrays ) The arrays list1 and list2 are strictly identical if
their corresponding elements are equal. Write a method that returns true if
list1 and list2 are strictly identical, using the following header:
public static boolean equals( int [] list1, int [] list2)
Write a test program that prompts the user to enter two lists of integers and dis-
plays whether the two are strictly identical. Here are the sample runs. Note that the
first number in the input indicates the number of the elements in the list.
Enter list1:
Enter list2:
Two lists are strictly identical
5 2 5 6 1 6
5 2 5 6 1 6
 
 
Search WWH ::




Custom Search