Created
January 30, 2024 13:50
-
-
Save rcmlz/2776406d70dacafacce8e8e96611233b to your computer and use it in GitHub Desktop.
Implementing simple BFS in Raku for an App called Calculator-The-Game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use MONKEY-SEE-NO-EVAL; | |
class Node { | |
has $.value; | |
has @.operations = []; | |
} | |
sub calculate(Int $start-value, Int $target-value, Int $max-steps, @possible-operators --> List) { | |
my @queue = [ Node.new(value => $start-value), ]; | |
while @queue.shift -> $parent { | |
for @possible-operators -> $op { | |
my $child = Node.new( value => EVAL("%s %s".sprintf($parent.value, $op)).Int, | |
operations => $parent.operations.clone.push: $op | |
); | |
return $child.operations if $child.value == $target-value; | |
@queue.push: $child if $child.operations.elems < $max-steps; | |
} | |
} | |
fail "No path found from %d to %d in %d steps using operators %s.".sprintf($start-value, $target-value, $max-steps, @possible-operators.join(" | ")); | |
} | |
use Test; | |
ok calculate(0, 2, 2, <+1 -1>) == <+1 +1>; | |
ok calculate(0, 5, 3, <+1 -1 +2>) == <+1 +2 +2>; | |
ok calculate(0, 210, 5, <~2 ~5 -5 +5>) == <~2 ~5 -5 ~5 +5>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment