Skip to content

Instantly share code, notes, and snippets.

@manwar
Last active June 12, 2020 17:16
Show Gist options
  • Save manwar/4363116c51cb6f38e3392848578e2bfc to your computer and use it in GitHub Desktop.
Save manwar/4363116c51cb6f38e3392848578e2bfc to your computer and use it in GitHub Desktop.
Min Path Sum
#!/usr/bin/env perl6
use v6.d;
my $matrix = [[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]];
my $paths = find-path($matrix, 0, 0);
#dd $paths;
# Raku version of my Perl solutions
# https://github.com/manwar/perlweeklychallenge-club/blob/master/challenge-064/mohammad-anwar/perl/ch-1.pl
sub find-path(Array[] $matrix, Int $row, Int $col, @path? = ()) {
my $rows = $matrix.elems - 1;
my $cols = $matrix.[0].elems - 1;
# check boundary?
return @path if $row > $rows || $col > $cols;
my @final-path = @path.[];
@final-path.push: $matrix.[$row][$col];
if ($row == $rows && $col == $cols) {
dd @final-path;
}
# reached bottom right corner?
return @final-path if $row == $rows && $col == $cols;
my @current-path = ();
# go right if possible.
@current-path.push: find-path($matrix, $row, $col + 1, @final-path);
# go down if possible.
@current-path.push: find-path($matrix, $row + 1, $col, @final-path);
return @current-path;
}
@manwar
Copy link
Author

manwar commented Jun 12, 2020

I changed that line as without it was pushing too many Any in the list.

Yes, we just need those arrays.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment