Skip to content

Commit b667026

Browse files
committed
Solution to Challenge manwar#1, Week 014
1 parent c405cef commit b667026

File tree

1 file changed

+40
-0
lines changed
  • challenge-014/rob-van-dam/perl5

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
}

0 commit comments

Comments
 (0)