Java Reference
In-Depth Information
filled it with random numbers, it isn't initially sorted. Hence, we call Arrays.sort() on the
array. Then we are in a position to call Arrays.binarySearch() , passing in the array and
the value to look for. If you run the program with a number, it runs that many games and re-
ports on how it fared overall. If you don't bother, it plays only one game:
public
public class
ArrayHunt {
/** the maximum (and actual) number of random ints to allocate */
protected
class ArrayHunt
protected final
final static
static int
int MAX
= 4000 ;
/** the value to look for */
protected
protected final
final static
static int
int NEEDLE = 1999 ;
int
int [] haystack ;
Random r ;
public
public static
void main ( String [] argv ) {
ArrayHunt h = new
static void
new ArrayHunt ();
iif ( argv . length == 0 )
h . play ();
else
else {
int
int won = 0 ;
int
int games = Integer . parseInt ( argv [ 0 ]);
for
int i = 0 ; i < games ; i ++)
iif ( h . play ())
++ won ;
System . out . println ( "Computer won " + won +
" out of " + games + "." );
for ( int
}
}
/** Construct the hunting ground */
public
public ArrayHunt () {
haystack = new
new int
int [ MAX ];
r = new
new Random ();
}
/** Play one game. */
public
public boolean
boolean play () {
int
int i ;
// Fill the array with random data (hay?)
for
for ( i = 0 ; i < MAX ; i ++) {
haystack [ i ] = ( int
int )( r . nextFloat () * MAX );
}
// Precondition for binary search is that data be sorted!
Search WWH ::




Custom Search