Hi all,
I'm having a problem using a linear search to find a duplicate. Here's the details of my program:
I roll two dice continually and get random numbers, 1-6. If I roll two of the same numbers, i.e. a 2 and a 2, then I lose the game. Otherwise, I add the two dice together and store it into a variable called sum. I then store each sum into an array. I roll the dice again and compare the sum to the previous sum in the array for a duplicate number. If no duplicate, I roll the dice a third time and compare the current sum to the last two sums in the array. I continue this until I find a duplicate sum then I win and stop. It's a little like craps but slightly different.
My problem is that I don't know how to compare the current sum to all of the sums in the array. I can compare the current sum with a previous sum in the array, but I don't know how to traverse the whole array to search for a duplicate. Any idea of how to do this?
Here's the code:
public static void main(String[] args) { int a = 10; int[] sumArray = new int [a]; for (int i = 0; i < a; i++) { int d1 = roll(); int d2 = roll(); int sum = d1 + d2; sumArray[i] += sum; System.out.println("d1: " + d1 + " d2: " + d2); System.out.println("index is: " + sumArray[i]); if (d1 == d2) { System.out.println("You lose!"); break; } for (int j = 0; j < a-1; j++){ if (sum == sumArray[j]){ System.out.println("You win!"); break; } } } } public static int roll() { int die = (int)(Math.random() * 6) + 1; return die; } }