advent-of-code-2024/day-7/Main.java

100 lines
3.2 KiB
Java
Raw Normal View History

2024-12-12 06:00:15 +00:00
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Main {
static class Test {
public long result;
public List<Integer> values;
Test(long r, List<Integer> v) {
this.result = r;
this.values = v;
}
2024-12-14 06:49:27 +00:00
boolean part1() {
2024-12-12 06:00:15 +00:00
int possibleCombinations = (int) Math.pow(2, this.values.size());
for (int i = 0; i < possibleCombinations; i++) {
long newResult = this.values.get(0);
for (int j = 1; j < this.values.size(); j++) {
if ((i >> j) % 2 == 0) {
newResult += this.values.get(j);
} else {
newResult *= this.values.get(j);
}
}
if (newResult == this.result) {
return true;
}
}
return false;
}
2024-12-14 06:49:27 +00:00
boolean part2() {
int possibleCombinations = (int) Math.pow(3, this.values.size());
for (int i = 0; i < possibleCombinations; i++) {
long newResult = this.values.get(0);
for (int j = 1; j < this.values.size(); j++) {
long value = this.values.get(j);
long trin = ((long) (i / Math.pow(3, j)) % 3);
if (trin == 0) {
newResult += value;
} else if (trin == 1) {
newResult *= value;
} else {
newResult = Long.valueOf("" + newResult + value);
}
}
if (newResult == this.result) {
return true;
}
}
return false;
}
2024-12-12 06:00:15 +00:00
}
static ArrayList<Test> parseInput() {
ArrayList<Test> output = new ArrayList<Test>();
try {
File input = new File("input.txt");
Scanner reader = new Scanner(input);
while (reader.hasNextLine()) {
String data = reader.nextLine();
String[] parts = data.split(":");
long result = Long.valueOf(parts[0]);
List<Integer> values = Arrays.asList(parts[1].trim().split(" "))
.stream()
.map(s -> Integer.parseInt(s))
.collect(Collectors.toList());
output.add(new Test(result, values));
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("Ups...");
}
return output;
}
public static void main(String args[]) {
ArrayList<Test> tests = parseInput();
2024-12-14 06:49:27 +00:00
tests.removeIf(t -> !t.part1());
2024-12-12 06:00:15 +00:00
long total = tests.stream().mapToLong(t -> t.result).sum();
2024-12-14 06:49:27 +00:00
System.out.println("Part 1");
System.out.println(total);
tests = parseInput();
tests.removeIf(t -> !t.part2());
total = tests.stream().mapToLong(t -> t.result).sum();
System.out.println("Part 2");
2024-12-12 06:00:15 +00:00
System.out.println(total);
}
}