-
Notifications
You must be signed in to change notification settings - Fork 319
/
ch-2.pl
executable file
·55 lines (47 loc) · 1.36 KB
/
ch-2.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env perl
#
# The Weekly Challenge - Perl & Raku
# (https://theweeklychallenge.org)
#
# Challenge 210 Task 2: Number Collision
#
# Perl solution by Matthias Muth.
#
use strict;
use warnings;
use List::Util qw( all );
sub number_collision {
my ( @list ) = @_;
while ( ( ! all { $_ > 0 } @list )
&& ! all { $_ < 0 } @list )
{
for ( 0 .. $#list - 1 ) {
if ( ( $list[$_] <=> 0 ) != ( $list[ $_ + 1 ] <=> 0 ) ) {
# Kill the left one if its value is less or equal.
my $pos =
abs( $list[$_] ) <= abs( $list[ $_ + 1 ] )
? $_
: $_ + 1 ;
# Kill both if their values are equal.
my $n =
abs( $list[$_] ) == abs( $list[ $_ + 1 ] )
? 2
: 1;
splice @list, $pos, $n, ();
last;
}
}
}
return @list;
}
use Test::More;
do {
is_deeply [ number_collision( @{$_->{INPUT}} ) ], $_->{EXPECTED},
"number_collision(" . join( ",", @{$_->{INPUT}} ) . ") == "
. ( "(" . join( ",", @{$_->{EXPECTED}} ) . ")" );
} for (
{ INPUT => [ 2,3,-1 ], EXPECTED => [ 2,3 ] },
{ INPUT => [ 3,2,-4 ], EXPECTED => [ -4 ]},
{ INPUT => [ 1,-1 ], EXPECTED => [] },
);
done_testing;