day3part1 works; part2 is maybe a tree-pruning algo?
This commit is contained in:
73
src/Day03.java
Normal file
73
src/Day03.java
Normal file
@@ -0,0 +1,73 @@
|
||||
package src;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Day03 {
|
||||
public static void main(String[] args) {
|
||||
part1();
|
||||
part2();
|
||||
}
|
||||
|
||||
private static void part1() {
|
||||
try (Scanner scanner = new Scanner(new FileReader("resources/inputs/03/input"))) {
|
||||
int sum = 0;
|
||||
while (scanner.hasNextLine()) {
|
||||
String raw = scanner.nextLine();
|
||||
List<String> bank = List.of(raw.split(""));
|
||||
int a = 0;
|
||||
int b = 1;
|
||||
int curr = Integer.parseInt(bank.get(a) + bank.get(b));
|
||||
for (int i = 2; i < bank.size(); i++) {
|
||||
int candidateA = Integer.parseInt(bank.get(a) + bank.get(i));
|
||||
int candidateB = Integer.parseInt(bank.get(b) + bank.get(i));
|
||||
if (candidateA > curr) {
|
||||
curr = candidateA;
|
||||
b = i;
|
||||
}
|
||||
if (candidateB > curr) {
|
||||
curr = candidateB;
|
||||
a = b;
|
||||
b = i;
|
||||
}
|
||||
}
|
||||
sum += curr;
|
||||
}
|
||||
IO.println(sum);
|
||||
} catch (Exception e) {
|
||||
IO.println(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void part2() {
|
||||
try (Scanner scanner = new Scanner(new FileReader("resources/inputs/03/testinput"))) {
|
||||
long sum = 0L;
|
||||
while (scanner.hasNextLine()) {
|
||||
String raw = scanner.nextLine();
|
||||
List<String> bank = List.of(raw.split(""));
|
||||
// first, get the initial 12 batteries
|
||||
List<String> curr = new ArrayList<>();
|
||||
curr.addAll(bank.subList(0, 12));
|
||||
for (int i = 12; i < bank.size(); i++) {
|
||||
curr.add(bank.get(i)); // add the next battery to the end of the list
|
||||
for (int j = 1; j < 10; j++) {
|
||||
// does the list contain a battery of the specified value?
|
||||
int index = curr.indexOf(String.valueOf(j));
|
||||
if (index != -1) {
|
||||
curr.remove(index); // remove it if it does
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
String result = curr.stream().reduce("", String::concat);
|
||||
IO.println(raw + " " + result);
|
||||
sum += Long.parseLong(result);
|
||||
}
|
||||
IO.println(sum);
|
||||
} catch (Exception e) {
|
||||
IO.println(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user