I am trying to complete the first exercise of USACO.
How can you make the following code more efficient?
It seems that the current problem in the program is that its execution takes too much time.
Thank you for suggesting the first four sets of improvements! I made a few edits based on your comments.
5th edition of the code
/*
* Problem: USACO Your Ride is Here
*
* To print GO if this if -loop is true "if ( ( index[0] % 47 ) == ( index[1] % 47 ) )"
* else STAY
*
* It calculates the product of letters' indexes in the alphabets such that
* A -> 1, B -> 2, ... , Z -> 26
*
*/
class PlanetUfo {
// initial data
String[] groups = {"COMETQ", "ABSTAR"};
String[] comets = {"HVNGAT", "USACO"};
// to count the index
private void countIndex ( String group, String comet ) {
// to have two PlanetUfo.words in the array
String[] name = { group, comet };
int[] index = new int[100];
// to go though the PlanetUfo.words one by one in the block of the array
for ( int k = 0; k < name.length; k++ ) {
System.out.println("K:n arvo on " + k);
// to save each letter to an array
char[] words = name[k].toCharArray();
int sum = 1;
// to loop through each character in the word
for ( int i = 0; i < words.length; i++) {
System.out.println("Inside the loop");
// to loop through the alphabets
char[] alphabet =
{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
for ( int j = 0; j < alphabet.length ; j++ ) {
if ( alphabet[j] == words[i] ) {
sum = sum * (j + 1);
index[k] = sum;
System.out.println("Found " + alphabet[j] + " in " + name[k] + " (index = " + (j+1) + ")");
break;
}
}
}
}
if ( ( index[0] % 47 ) == ( index[1] % 47 ) )
System.out.println("GO");
else
System.out.println("STAY");
}
public static void main (String[] args) {
PlanetUfo planetufo = new PlanetUfo();
// to count the index for name1 and name2
for ( int i = 0; i < planetufo.groups.length; i++ ) {
planetufo.countIndex( planetufo.groups[i], planetufo.comets[i] );
}
System.out.close();
System.exit(0);
}
}
USACO gives me the following error although the program works in my computer
Run 1: Execution error: Your program exited with exit status `1'.
------ Data for Run 1 ------
COMETQ
HVNGAT
----------------------------
Your program printed data to stderr. Here is the data:
-------------------
Exception_in_thread_"main"_java.lang.NoClassDefFoundError:_ride
-------------------