diff options
| author | Simon Proctor <simon.proctor@zoopla.co.uk> | 2021-02-15 16:40:30 +0000 |
|---|---|---|
| committer | Simon Proctor <simon.proctor@zoopla.co.uk> | 2021-02-15 16:40:30 +0000 |
| commit | 430de9c4385301d4dcce072c09c724bbaf49ebf1 (patch) | |
| tree | c21a05f947a7e9835c5794f132ea6fc76e41dd36 | |
| parent | 5e70fcf6e681215a1d1716353061c3b53cfe108d (diff) | |
| download | perlweeklychallenge-club-430de9c4385301d4dcce072c09c724bbaf49ebf1.tar.gz perlweeklychallenge-club-430de9c4385301d4dcce072c09c724bbaf49ebf1.tar.bz2 perlweeklychallenge-club-430de9c4385301d4dcce072c09c724bbaf49ebf1.zip | |
Challenge 2, recursion time
| -rw-r--r-- | challenge-100/simon-proctor/raku/ch-2.raku | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/challenge-100/simon-proctor/raku/ch-2.raku b/challenge-100/simon-proctor/raku/ch-2.raku new file mode 100644 index 0000000000..7d2de18afe --- /dev/null +++ b/challenge-100/simon-proctor/raku/ch-2.raku @@ -0,0 +1,33 @@ +#!/usr/bin/env raku + +use v6; + +#! Given a series of comma seperated number lists making a triangle (1 -> 2 -> 3 digits long) +#! find the path down the triangle that adds up to the least amount +multi sub MAIN( *@input ) { + my @lines = @input.map( *.split(",") ); + die "Not a triangle" unless [==] 1, |(@lines.map( *.elems ).rotor(2=>-1).map( { @^a[1] - @^a[0] } ) ); + say smallest-route( @lines ); +} + +multi sub MAIN("test") { + use Test; + is( 8, smallest-route( [ [1], [2,4], [6,4,9], [5,1,7,2] ] ) ); + is( 7, smallest-route( [ [3], [3,1], [5,2,3], [4,3,1,3] ] ) ); +} + +multi sub smallest-route( @start ) { + return smallest-route( @start[0], @start[1..*-1], 0 ); +} + +multi sub smallest-route( @head, [], $index ) { + return @head[$index]; +} + +multi sub smallest-route( @head, @rest, $index ) { + my @opts = [ + smallest-route( @rest[0], @rest[1..*-1], $index ), + smallest-route( @rest[0], @rest[1..*-1], $index+1 ) + ]; + return @head[$index] + (@opts[0] < @opts[1] ?? @opts[0] !! @opts[1]); +} |
