Skip to content

Commit

Permalink
Rewrite AoC 2024 day 19 part 1 solver to use iterables and yield to p…
Browse files Browse the repository at this point in the history
…repare for part 2
  • Loading branch information
h3x4d3c1m4l committed Dec 20, 2024
1 parent 2780eb7 commit a3990c7
Showing 1 changed file with 6 additions and 10 deletions.
16 changes: 6 additions & 10 deletions lib/solvers/advent_of_code/2024/day_19_solver.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import 'package:darq/darq.dart';
import 'package:h3x_devtools/solvers/advent_of_code/2024/aoc_2024_solver.dart';

class Day19Solver extends AdventOfCode2024Solver {
Expand All @@ -18,27 +17,24 @@ class Day19Solver extends AdventOfCode2024Solver {
List<String> nonCompositablePatterns = [...towelPatterns];
for (String pattern in towelPatterns) {
nonCompositablePatterns.remove(pattern);
if (!_isDesignPossible('', pattern, nonCompositablePatterns)) nonCompositablePatterns.add(pattern);
if (!_getPossibleDesigns([], pattern, nonCompositablePatterns).isNotEmpty) nonCompositablePatterns.add(pattern);
}

// Now we check which designs are possible.
int possibleDesigns = desiredDesigns.where((design) => _isDesignPossible('', design, nonCompositablePatterns)).length;
int possibleDesigns = desiredDesigns.where((design) => _getPossibleDesigns([], design, nonCompositablePatterns).isNotEmpty).length;

return 'Possible designs: $possibleDesigns';
}

bool _isDesignPossible(String currentPattern, String desiredPattern, List<String> towelPatterns) {
Iterable<List<String>> _getPossibleDesigns(List<String> currentPattern, String desiredPattern, List<String> towelPatterns) sync* {
for (String pattern in towelPatterns) {
String testingPattern = '$currentPattern$pattern';
String testingPattern = '${currentPattern.join()}$pattern';
if (testingPattern == desiredPattern) {
return true;
yield [...currentPattern, pattern];
} else if (testingPattern.length < desiredPattern.length && desiredPattern.startsWith(testingPattern)) {
bool isPossible = _isDesignPossible(testingPattern, desiredPattern, towelPatterns);
if (isPossible) return true;
yield* _getPossibleDesigns([...currentPattern, pattern], desiredPattern, towelPatterns);
}
}

return false;
}

}

0 comments on commit a3990c7

Please sign in to comment.