From a3990c7c76bef8b67ce104a204164795a5b2e9eb Mon Sep 17 00:00:00 2001 From: Sander in 't Hout Date: Fri, 20 Dec 2024 01:41:33 +0100 Subject: [PATCH] Rewrite AoC 2024 day 19 part 1 solver to use iterables and yield to prepare for part 2 --- .../advent_of_code/2024/day_19_solver.dart | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/lib/solvers/advent_of_code/2024/day_19_solver.dart b/lib/solvers/advent_of_code/2024/day_19_solver.dart index d093c66..10cfd1f 100644 --- a/lib/solvers/advent_of_code/2024/day_19_solver.dart +++ b/lib/solvers/advent_of_code/2024/day_19_solver.dart @@ -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 { @@ -18,27 +17,24 @@ class Day19Solver extends AdventOfCode2024Solver { List 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 towelPatterns) { + Iterable> _getPossibleDesigns(List currentPattern, String desiredPattern, List 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; } }