diff options
| author | Luca Ferrari <fluca1978@gmail.com> | 2020-04-06 15:18:09 +0200 |
|---|---|---|
| committer | Luca Ferrari <fluca1978@gmail.com> | 2020-04-06 15:18:09 +0200 |
| commit | 191bcbdf1f87aac1f3aad9e4ea0ff66af3ee6e97 (patch) | |
| tree | fa7836364cc81b26dd9343a6c4d74f66a6bcabae | |
| parent | 03b397e6fe5364119375261f6fb15f0754d96900 (diff) | |
| download | perlweeklychallenge-club-191bcbdf1f87aac1f3aad9e4ea0ff66af3ee6e97.tar.gz perlweeklychallenge-club-191bcbdf1f87aac1f3aad9e4ea0ff66af3ee6e97.tar.bz2 perlweeklychallenge-club-191bcbdf1f87aac1f3aad9e4ea0ff66af3ee6e97.zip | |
Challenge 2 done.
| -rw-r--r-- | challenge-055/luca-ferrari/raku/ch-2.p6 | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/challenge-055/luca-ferrari/raku/ch-2.p6 b/challenge-055/luca-ferrari/raku/ch-2.p6 new file mode 100644 index 0000000000..efa456da41 --- /dev/null +++ b/challenge-055/luca-ferrari/raku/ch-2.p6 @@ -0,0 +1,52 @@ +#!env raku +# +#Wave Array +# +# Any array N of non-unique, unsorted integers can be arranged +# into a wave-like array such that n1 ≥ n2 ≤ n3 ≥ n4 ≤ n5 and so on. +# +# For example, given the array [1, 2, 3, 4], +# possible wave arrays include [2, 1, 4, 3] or [4, 1, 3, 2], +# since 2 ≥ 1 ≤ 4 ≥ 3 and 4 ≥ 1 ≤ 3 ≥ 2. This is not a complete list. +# +# Write a script to print all possible wave arrays +# for an integer array N of arbitrary length. +# Notes: +# +# When considering N of any length, +# note that the first element is always greater +# than or equal to the second, and then the ≤, ≥, ≤, … +# sequence alternates until the end of the array. + + +# Test if a single sequence is ok. +# The third argument checks if the test has to be done as >= or <=. +sub is-ok( Int:D $a, Int:D $b, Bool:D $greater ) { + return $a >= $b if ( $greater ); + return $a <= $b if ( ! $greater ); +} + + +sub MAIN( Int:D $number where { $number.chars > 1 } ){ + my @array = $number.comb; + + say "Waving { @array } of { @array.elems } elements "; + for @array.permutations -> @current { + my $ok = False; + my $test = True; # true = greater + my @result; + for 0 ..^ @current.elems - 1 -> $index { + $ok = is-ok @current[ $index ].Int, @current[ $index + 1 ].Int, $test; + $test = ! $test; + @result.push( @current[ $index ].Str ~ ( $test ?? ' ≥ ' !! ' ≤ ' ) ); + last if ! $ok; + } + + if $ok { + @result.push( @current[ *-1 ].Str ~ ( $test ?? ' ≥ ' !! ' ≤ ' ) ); + say @result; + } + + say "Found wave { @current }" if $ok; + } +} |
