Mercury.txt
8 58 59 5 4 62 63 1 49 15 14 52 53 11 10 56 41 23 22 44 45 19 18 48 32 34 35 29 28 38 39 25 40 26 27 37 36 30 31 33 17 47 46 20 21 43 42 24 9 55 54 12 13 51 50 16 64 2 3 61 60 6 7 57
Luna.txt
37 78 29 70 21 62 13 54 5 6 38 79 30 71 22 63 14 46 47 7 39 80 31 72 23 55 15 16 48 8 40 81 32 64 24 56 57 17 49 9 41 73 33 65 25 26 58 18 50 1 42 74 34 66 67 27 59 10 51 2 43 75 35 36 68 19 60 11 52 3 44 76 77 28 69 20 61 12 53 4 45
Solutions
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class MagicSquares {
public static boolean testMagic(String pathName) throws IOException {
// Open the file
BufferedReader reader = new BufferedReader(new FileReader(pathName));
boolean isMagic = true;
int lastSum = -1;
// For each line in the file ...
String line;
while ((line = reader.readLine()) != null) {
// ... sum each row of numbers
String[] parts = line.split("\t");
int sum = 0;
for (String part : parts) {
sum += Integer.parseInt(part);
}
if (lastSum == -1) {
// If this is the first row, remember the sum
lastSum = sum;
} else if (lastSum != sum) {
// if the sums don't match, it isn't magic, so stop reading
isMagic = false;
break;
}
}
reader.close();
return isMagic;
}
public static void main(String[] args) throws IOException {
String[] fileNames = { "Mercury.txt", "Luna.txt" };
for (String fileName : fileNames) {
System.out.println(fileName + " is magic? " + testMagic(fileName));
}
}
}
No comments:
Post a Comment