diff options
| author | Simon Proctor <simon.proctor@zoopla.co.uk> | 2020-06-08 10:45:23 +0100 |
|---|---|---|
| committer | Simon Proctor <simon.proctor@zoopla.co.uk> | 2020-06-08 10:45:23 +0100 |
| commit | 4a7d9c71ac7516dda01631d59845ec03933907be (patch) | |
| tree | 6c8d4623e28a5a65f26134924353d6551819d331 | |
| parent | f2c3c84295ef3b02c765dcf5b72777892c30b9da (diff) | |
| download | perlweeklychallenge-club-4a7d9c71ac7516dda01631d59845ec03933907be.tar.gz perlweeklychallenge-club-4a7d9c71ac7516dda01631d59845ec03933907be.tar.bz2 perlweeklychallenge-club-4a7d9c71ac7516dda01631d59845ec03933907be.zip | |
Shortest path
| -rw-r--r-- | challenge-064/simon-proctor/raku/ch-1.raku | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/challenge-064/simon-proctor/raku/ch-1.raku b/challenge-064/simon-proctor/raku/ch-1.raku new file mode 100644 index 0000000000..9228404924 --- /dev/null +++ b/challenge-064/simon-proctor/raku/ch-1.raku @@ -0,0 +1,42 @@ +#!/usr/bin/env raku + +use v6.d; + +#| Find the path from the top right of the grid to the +#| Bottom left that sums up to the least amount. +sub MAIN ( + UInt $width, #= Width of the grid + *@cells where { $_.all ~~ UInt && 1 < $_.elems && $_.elems %% $width }, #= Cell values + Bool :v(:$verbose) = False, #= Verbose mode +) { + my @grid = @cells.rotor($width); + say "Width: $width\nGrid:" if $verbose; + say @grid.map( { .join(" ") } ).join("\n") if $verbose; + + my @short-route = route-to( (0,0), (@grid[0].end,@grid.end) ).sort( -> @route { score-route( @grid, @route ) } )[0]; + + @short-route[0].map( -> ($x,$y) { @grid[$y][$x] } ).join(" -> " ).say if $verbose; + + say score-route( @grid, @short-route[0] ); +} + +multi sub score-route( @grid, @route ) { + [+] @route.map( -> ( $x, $y ) { @grid[$y][$x] } ); +} + +multi sub route-to ( @s, @e where { @s ~~ @e } ) { return [ [@s,], ] } + +multi sub route-to( @s, @e ) { + my @routes; + if ( @s[0] !~~ @e[0] ) { + for route-to( ( @s[0]+1, @s[1] ), @e ) -> @route { + @routes.push( @route.unshift( @s ) ); + } + } + if ( @s[1] !~~ @e[1] ) { + for route-to( ( @s[0], @s[1]+1 ), @e ) -> @route { + @routes.push( @route.unshift( @s ) ); + } + } + @routes; +} |
