File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
challenge-014/rob-van-dam/perl5 Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ # !/usr/bin/env perl
2+
3+ use strict;
4+ use warnings;
5+ use v5.10;
6+
7+ my $M = shift @ARGV || 10;
8+
9+ # slow();
10+ fast();
11+
12+ # this works but is very slow for large $M
13+ # as its roughly O(n**2)
14+ sub slow {
15+ my @a = (0);
16+ for my $n (0..$M ) {
17+ my $r = 0;
18+ foreach my $m (0..($n -1)) {
19+ last if ! defined $a [$n ];
20+ $r = $n - $m if $a [$m ] == $a [$n ];
21+ }
22+ $a [$n + 1] = $r ;
23+ say $a [$n ];
24+ }
25+ }
26+
27+ # this is much faster for large $M
28+ # by caching the last time we say a given number
29+ # so its roughly O(n**2) but requires roughly O(2n) space
30+ sub fast {
31+ my @a = (0);
32+ my @last = ();
33+ for my $n (0..$M ) {
34+ my $m = $last [ $a [$n ] ];
35+ my $r = defined $m ? $n - $m : 0;
36+ $last [$a [$n ]] = $n ;
37+ $a [$n + 1] = $r ;
38+ say $a [$n ];
39+ }
40+ }
You can’t perform that action at this time.
0 commit comments