day7_pt2.java (1413B)
1 import java.nio.file.Files; 2 import java.nio.file.Path; 3 import java.io.IOException; 4 import java.io.BufferedReader; 5 import java.io.StringReader; 6 import java.util.Arrays; 7 import java.util.List; 8 9 public class day7_pt2 { 10 public static void main(String[] args) throws IOException { 11 var input = Files.readString(Path.of(args[0])); 12 System.out.printf("day7, pt2 = %d\n", new BufferedReader(new StringReader(input)) 13 .lines() 14 .mapToLong(line -> { 15 var arr = line.split(":"); 16 var target = Long.parseLong(arr[0]); 17 var nums = Arrays.stream(arr[1].trim().split(" ")).map(Long::parseLong).toList(); 18 if (fn(target, nums.getFirst(), nums.subList(1, nums.size()))) { 19 return target; 20 } else { 21 return 0; 22 } 23 }) 24 .sum()); 25 } 26 27 static boolean fn(long target, long res, List<Long> rem) { 28 // short circuit dead ends 29 // I checked the puzzle input for "* 0" and it doesn't occur, so 30 // this seems to be valid... 31 if (res > target) { 32 return false; 33 } 34 if (rem.size() == 0) { 35 return res == target; 36 } else { 37 var arg = rem.getFirst(); 38 var rem2 = rem.subList(1, rem.size()); 39 return fn(target, res * arg, rem2) || fn(target, res + arg, rem2) || fn(target, cat(res, arg), rem2); 40 } 41 } 42 43 static long cat(long l1, long l2) { 44 return Long.parseLong(String.format("%d%d", l1, l2)); 45 } 46 }