Task1
We reorder notes according to the permutation array:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;
sub reorder_notes{
my ($composer,$notes,$perm) = @{$_[0]};
my @reordered;
$reordered[$perm->[$_]-1] = $notes->[$_] foreach 0..$#$perm;
uc($composer) . ' => ' . join ' ',@reordered
}
is reorder_notes(['Bach',['C','D','E','F#','G','A','B'],
[7,1,6,2,5,3,4]]),
'BACH => D F# A B G E C','Example 1';
is reorder_notes(['Beethoven',
['C','D','F#','G','Ab'],
[1, 3, 5, 2, 4]]),
'BEETHOVEN => C G D Ab F#','Example 2';
is reorder_notes(['Brahms',
['C','Db','Eb','F','G','Ab','Bb','C','D'],
[9,3,7,1,8,5,2,6,4]]),
'BRAHMS => F Bb Db D Ab C Eb G C','Example 3';
is reorder_notes(['Bruckner',
['G','F#','Bb','C','D','Eb','F'],
[4,7,2,6,1,5,3]]),
'BRUCKNER => D Bb F G Eb C F#','Example 4';
is reorder_notes(['Berg',
['C#'],
[1]]),'BERG => C#','Example 5';
done_testing();
Task2
We find the length of longest zig-zag subarray:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;
sub zig_zag_subarray{
my ($arr) = @_;
return 1 if @{$arr} == 1;
return 2 if @{$arr} == 2 && $arr->[0] != $arr->[1];
my ($max,$from,$to) = (1,0,0);
while($to++ < $#$arr){
$from = $to, next if $arr->[$to-1] == $arr->[$to];
$from = $to-1, next if $to - $from > 1
&& ($arr->[$to] <=> $arr->[$to-1])
== ($arr->[$to-1] <=> $arr->[$to-2]);
my $curr = 1 + $to - $from;
$max = $curr if $curr > $max
}
$max
}
is zig_zag_subarray([9,4,2,10,7,8,8,1,9]),5,'Example 1';
is zig_zag_subarray([1,7,4,9,2,5]),6,'Example 2';
is zig_zag_subarray([1..5]),2,'Example 3';
is zig_zag_subarray([4,4,4]),1,'Example 4';
is zig_zag_subarray([10,20,15,12,18]),3,'Example 5';
done_testing();
No comments:
Post a Comment