in reply to Re: Brute force vs algorithm (PWC # 100)
in thread Brute force vs algorithm (PWC # 100)
("abusing" List::Util::reduce() to window two neighboring cells)
# PWC 100 use strict; use warnings; use JSON::PP; use Test::More; use List::Util qw/reduce/; while ( my $line = <DATA> ) { my ($json, $expected) = split /\s/, $line; my $aoa = decode_json($json); is( compute($aoa), $expected ); compute($aoa); } sub compute { my @aoa = @{(shift)}; my $bottom; while (@aoa) { $bottom = pop @aoa; my $i=0; reduce { # by overlapping pairs $aoa[-1][$i++] += # add to parent ... ($a < $b ? $a : $b); # ... minimum neighbors $b # right to left nb } @$bottom; } return $bottom->[0]; } done_testing; __DATA__ [[1],[2,4],[6,4,9],[5,1,7,2]] 8 [[9],[1,6],[7,8,2],[5,8,2,3]] 19
ok 1 ok 2 1..2
That's O(m) = O(n**2) with m:= #cells , n:= #rows and m = n*(n+1)/2
Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Brute force vs algorithm (PWC # 100)
by pryrt (Abbot) on Feb 15, 2021 at 19:56 UTC | |
by LanX (Saint) on Feb 15, 2021 at 20:17 UTC |