FileDocCategorySizeDatePackage
ArrayHunt.javaAPI DocExample1536Sun Mar 07 18:11:18 GMT 2004None

ArrayHunt

public class ArrayHunt extends Object
Array Hunt "game" (pathetic: computer plays itself).
author
Ian Darwin
version
$Id: ArrayHunt.java,v 1.3 2004/03/08 00:11:18 ian Exp $

Fields Summary
protected static final int
MAX
the maximum (and actual) number of random ints to allocate
protected static final int
NEEDLE
the value to look for
int[]
haystack
Random
r
Constructors Summary
public ArrayHunt()
Construct the hunting ground

		haystack = new int[MAX];
		r = new Random();
	
Methods Summary
public static voidmain(java.lang.String[] argv)


	     
		ArrayHunt h = new ArrayHunt();
		if (argv.length == 0)
			h.play();
		else {
			int won = 0;
			int games = Integer.parseInt(argv[0]);
			for (int i=0; i<games; i++)
				if (h.play())
					++won;
			System.out.println("Computer won " + won + 
				" out of " + games + ".");
		}
	
public booleanplay()
Play one game.

		int i;

		// Fill the array with random data (hay?)
		for (i=0; i<MAX; i++) {
			haystack[i] = (int)(r.nextFloat() * MAX);
		}

		// Precondition for binary search is that data be sorted!
		Arrays.sort(haystack);

		// Look for needle in haystack
		i = Arrays.binarySearch(haystack, NEEDLE);

		if (i >= 0) {		// Found it, we win.
			System.out.println("Value " + NEEDLE +
				" occurs at haystack[" + i + "]");
			return true;
		} else {		// Not found, we lose.
			System.out.println("Value " + NEEDLE +
				" does not occur in haystack; nearest value is " +
				haystack[-(i+2)] + " (found at " + -(i+2) + ")");
			return false;
		}