DEV Community

Discussion on: Daily Challenge #13 - Twice Linear

Collapse
 
yzhernand profile image
Yozen Hernandez

Here's my solution in Perl. I actually think its a bit too slow, even when using state variables to cache the results in subsequent calls. Maybe I'll look into optimizing it later.

#!/usr/bin/env perl

use v5.24;
use strict;
use warnings;
use feature qw(signatures);
no warnings "experimental::signatures";
use List::Util qw(first uniq);

sub dbl_linear ($n) {
    state @u = (1);
    state $last_n = 0;

    return $u[$n] if $u[$n];

    for my $i ( $last_n .. $n ) {
        my $val = $u[$i];
        @u = sort { $a <=> $b } uniq (@u, map {$_ * $val + 1} (2, 3));
    }

    $last_n = $n;
    return $u[$n];
}

use Test::More tests => 5;
is( dbl_linear(0), 1,  "u(0) == 1" );
is( dbl_linear(1), 3,  "u(1) == 3" );
is( dbl_linear(6), 13, "u(6) == 13" );
is( dbl_linear(100), 447, "u(100) == 447" );
is( dbl_linear(1000), 8488, "u(1000) == 8488" );

I'll write an explainer for it when I get a few minutes later.