diff options
| author | James Smith <js5@sanger.ac.uk> | 2023-01-02 17:33:24 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-01-02 17:33:24 +0000 |
| commit | ea2964e208a5a23a3675bc32654973d757ca6049 (patch) | |
| tree | 7b0e2593b91b9f312c64ef9cee1f98d9b0d6a575 /challenge-198 | |
| parent | d2a769f76a4d65ce8805bd8756f2e6993301ee17 (diff) | |
| download | perlweeklychallenge-club-ea2964e208a5a23a3675bc32654973d757ca6049.tar.gz perlweeklychallenge-club-ea2964e208a5a23a3675bc32654973d757ca6049.tar.bz2 perlweeklychallenge-club-ea2964e208a5a23a3675bc32654973d757ca6049.zip | |
Create ch-1.pl
Diffstat (limited to 'challenge-198')
| -rw-r--r-- | challenge-198/james-smith/perl/ch-1.pl | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/challenge-198/james-smith/perl/ch-1.pl b/challenge-198/james-smith/perl/ch-1.pl new file mode 100644 index 0000000000..371a2c4d13 --- /dev/null +++ b/challenge-198/james-smith/perl/ch-1.pl @@ -0,0 +1,47 @@ +#!/usr/local/bin/perl + +use strict; +use warnings; +use feature qw(say); +use Test::More; +use Benchmark qw(cmpthese timethis); + +my @TESTS = ( + [ [2,5,8,1 ], 2 ], + [ [3 ], 0 ], + [ [1..9,21..25, map { 2*$_ } 5..10 ], 5 ], + [ [(1) x 10 ], 9 ], + [ [ 1..10 ], 9 ], + [ [ 2.9 , 3..10 ], 7], + [ [ 1..8,8.1 ], 7], + [ [ 1, 3..10 ], 1 ], + [ [ 1..8, 10 ], 1 ], + [ [ 1..999, 1001 ], 1 ], + [ [ 1..999, 999.1 ], 998 ], +); + +is( max_gap_sort( @{$_->[0]} ), $_->[1] ) for @TESTS; +is( max_gap_nosort( @{$_->[0]} ), $_->[1] ) for @TESTS; +done_testing(); + +cmpthese( -10, { + 'sort' => sub { max_gap_sort( @{$_->[0]} ) for @TESTS }, # 1700/s + 'nosort' => sub { max_gap_nosort( @{$_->[0]}) for @TESTS }, # 3535/s +} ); + +sub max_gap_sort { + return 0 unless $#_; + @_ = sort { $a <=> $b } @_; + my $p = shift; + @_ = sort { $b <=> $a } map { ($_-$p,$p=$_)[0] } @_; + $_[0]==$_[$_] || return $_ for 1..$#_; + 1*@_ +} + +sub max_gap_nosort { + return 0 unless $#_; + @_ = sort { $a <=> $b } @_; + my($p,$b,$c)=(shift,0,0); + $_-$p>$b ? ($b,$c)=($_-$p,1) : $_-$p==$b && $c++, $p=$_ for @_; + $c; +} |
