import java.util.Scanner; import java.io.*; /* * Lab 4 * * Author: Robin Dawes * * Date: 20081022 * * Comment: * */ public class ChipTest { static int instances; static int numOfChips; static Chip[] setOfChips; public static void main (String[] argv) throws Exception { Scanner myScanner = new Scanner(new File("Lab_4_Data.txt")); // find out how many instances instances = myScanner.nextInt(); for (int i = 0; i < instances; i++) { // read in the data for the next instance numOfChips = myScanner.nextInt(); setOfChips = new Chip[numOfChips]; System.out.println("\nInstance " + i); //System.out.print("Input : "); for (int j = 0; j < numOfChips; j++){ int nextChip = myScanner.nextInt(); //System.out.print(nextChip + " "); setOfChips[j] = new Chip(j, nextChip); } //System.out.println(); // find a good chip int indexOfGoodChip = recursiveTest(numOfChips, setOfChips); System.out.println("One good chip : " + indexOfGoodChip); // list the good chips System.out.print("The good chips are "); for (int j = 0; j < numOfChips; j++) if (setOfChips[indexOfGoodChip].checkChip(setOfChips[j])) System.out.print(j + " "); System.out.println(); } } // main static int recursiveTest(int n, Chip[] s) { /* System.out.print("Chips still in consideration : "); for (int i = 0; i < n; i++) System.out.print(s[i].getIndex() + " "); System.out.println(); */ if (n == 1) return s[0].getIndex(); else if (n == 3) { if (s[0].checkChip(s[1]) && s[1].checkChip(s[0])) return s[0].getIndex(); else return s[2].getIndex(); } else { Chip[] reducedSet = new Chip[n/2 + 1]; int reducedSetSize = 0; int numCheckable = n - (n%2); // if n is odd, we can't check the last chip // keep one out of each pair that reports both chips are good for (int i = 0; i < numCheckable; i+=2){ if (s[i].checkChip(s[i+1]) && s[i+1].checkChip(s[i])) { reducedSet[reducedSetSize] = s[i]; reducedSetSize++; } } // If the original set was odd in size, the last chip has not been // tested against any other. If the reduced set is even in size, we // add the last chip to it - if the reduced set is odd in size, we // don't need the last chip so we leave it out. if ((n%2 == 1) && (reducedSetSize%2 == 0)) { reducedSet[reducedSetSize] = s[n-1]; reducedSetSize++; } return recursiveTest(reducedSetSize, reducedSet); } } // recursiveTest } // class