A new Khyber crystal mine has been started on Danton\'s. These are the crystals for lightsabers, and the mine owner has been mining red, blue, and green crystals. Periodically, the mine owner pauses the mining to put together all the crystals found till then, and ships them out to lightsaber factories (yes, they exist!). For reasons of superstition, be only does this when an equal number of crystals o each color has been collected from the mine (i.e., when there is \"balance\"). However, since he has no control over which color crystal is found next, be wants your help to decide when balance is reached. The program will read in a list o letters representing the color of each crystal that comes out of the mine. When a balance (greater than 0, 0, 0) has been achieved, the program will stop reading and print \"Balance achieved at\" followed by the number of red crystal that came out (which of course would be the same as the number of blue and the number of green crystals). The provided skeleton handles the input of the values and the output messages. You need to implement the method achieve Balance (Scanner sc) which returns an int when balance has been achieved. The entire input may not be read in the first call -- instead, the function is called repeatedly in order to read all the input. The first line in the test data file contains the number of test cases. After that, for each test case there will be one letter (R, G, B) per line representing the color of the crystal that just came out. For each test case, the program will display the \"balance\" number. You can assume that for the given input file, balance will be achieved exactly as many times as the number of test cases listed, and also that there will be no more lines in input after the last balance. We have provided a skeleton program that reads the number of test cases and opens the input stream. It also prints the output based on the achieve Balance () method that you need to implement.
The idea is to have counters that counts the number of red, green and blue crystals found so far and as soon as all of them matches we return the count.
import java.util.Scanner;
class JediCrystal {
public static int achiveBalance(Scanner sc) {
int rCount, gCount, bCount;
rCount = gCount = bCount = 0;
while (true) {
char crystal = sc.next().charAt(0);
if (crystal == \'R\')
++rCount;
else if (crystal == \'G\')
++gCount;
else
++bCount;
if (rCount == gCount && rCount == bCount && rCount != 0) {
return rCount;
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = sc.nextInt();
for (int i = 0; i < testCases; i++) {
System.out.println(achiveBalance(sc));
}
}
}