Add my first solution for part 2
This commit is contained in:
parent
7e8ce94b5a
commit
138ee2b89a
1 changed files with 44 additions and 0 deletions
44
day_01/java/part_2.java
Normal file
44
day_01/java/part_2.java
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Scanner;
|
||||
|
||||
class Part2 {
|
||||
public static void main (String[] args) {
|
||||
Scanner f;
|
||||
try {
|
||||
f = Part2.readFile(args[0]);
|
||||
} catch (FileNotFoundException e) {
|
||||
System.out.println("File not found, stopping execution");
|
||||
return;
|
||||
}
|
||||
|
||||
ArrayList<Integer> sums = new ArrayList<Integer>();
|
||||
Integer runningSum = 0;
|
||||
while (f.hasNextLine()) {
|
||||
String l = f.nextLine();
|
||||
if (l.equals("")) {
|
||||
sums.add(runningSum);
|
||||
runningSum = 0;
|
||||
} else {
|
||||
runningSum = runningSum + Integer.parseInt(l);
|
||||
}
|
||||
}
|
||||
f.close();
|
||||
|
||||
Collections.sort(sums, Collections.reverseOrder());
|
||||
System.out.print(
|
||||
"The largest three values are: "
|
||||
+ sums.subList(0, 3).toString()
|
||||
+ " totalling: "
|
||||
);
|
||||
System.out.println(sums.get(0) + sums.get(1) + sums.get(2));
|
||||
}
|
||||
|
||||
private static Scanner readFile(String file) throws FileNotFoundException {
|
||||
File f = new File(file);
|
||||
Scanner s = new Scanner(f);
|
||||
return s;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue