diff --git a/src/main/java/com/adventofcode/flashk/day19/LinenLayout2.java b/src/main/java/com/adventofcode/flashk/day19/LinenLayout2.java index 8af13d8..3067cb1 100644 --- a/src/main/java/com/adventofcode/flashk/day19/LinenLayout2.java +++ b/src/main/java/com/adventofcode/flashk/day19/LinenLayout2.java @@ -12,7 +12,7 @@ public class LinenLayout2 { private List patterns; private List designs; - private Map memo = new HashMap<>(); + private Map memo = new HashMap<>(); public LinenLayout2(List inputs) { patterns = Arrays.stream(inputs.getFirst().replace(StringUtils.SPACE, StringUtils.EMPTY).split(",")) @@ -23,29 +23,41 @@ public LinenLayout2(List inputs) { designs = inputs; } - public int solveB() { - int result = 0; + public long solveB() { + long result = 0; for(String design : designs) { result += count(design, StringUtils.EMPTY); + memo.clear(); } return result; } - private int count(String design, String pattern){ + private long count(String design, String pattern){ if(design.equals(pattern)) { - return 1; + return 1L; } if(!design.startsWith(pattern)) { return 0; } - int count = 0; + long count = 0; String rightSide = design.replaceFirst(pattern, StringUtils.EMPTY); for(String newPattern : patterns) { - count += count(rightSide, newPattern); + + MemoState newState = new MemoState(rightSide, newPattern); + + long partialCount; + if(memo.containsKey(newState)) { + partialCount = memo.get(newState); + } else { + partialCount = count(rightSide, newPattern); + memo.put(new MemoState(rightSide, newPattern), partialCount); + } + + count += partialCount; } return count; diff --git a/src/main/java/com/adventofcode/flashk/day19/MemoState.java b/src/main/java/com/adventofcode/flashk/day19/MemoState.java new file mode 100644 index 0000000..e29bfe6 --- /dev/null +++ b/src/main/java/com/adventofcode/flashk/day19/MemoState.java @@ -0,0 +1,4 @@ +package com.adventofcode.flashk.day19; + +public record MemoState(String design, String pattern) { +} diff --git a/src/test/java/com/adventofcode/flashk/day19/Day19Test.java b/src/test/java/com/adventofcode/flashk/day19/Day19Test.java index 90fbbae..a820844 100644 --- a/src/test/java/com/adventofcode/flashk/day19/Day19Test.java +++ b/src/test/java/com/adventofcode/flashk/day19/Day19Test.java @@ -79,8 +79,7 @@ public void testSolvePart2Input() { // Read input file List inputs = Input.readStringLines(INPUT_FOLDER, TestFilename.INPUT_FILE); LinenLayout2 linenLayout = new LinenLayout2(inputs); - System.out.println("Solution: "+linenLayout.solveB()); - assertEquals(0L,0L); + assertEquals(619970556776002L,linenLayout.solveB()); }