#!/usr/bin/perl
use 5.016;
use warnings;
use List
::Util qw(reduce
);
sub new {
}
sub value { $_[0]->[0] }
sub next { ref $_[0]->[1] eq 'CODE' ? $_[0]->[1] = $_[0]->[1]->() : $_[0]->[1] }
sub f {
my ($n, $l, $p) = @_;
$p->value * 10 + $l->[$n],
sub {
(($n + 1) > $#{$l}) ?
f($n + 1, $l, $p)
}
);
}
sub _f {
my ($b, $n) = @_;
top($b) :
f(
0,
($b == 9 ? [2 .. 9, 1] : [1 .. 9]),
reduce{ f(0, [0 .. 9], $a) } (top($b), 2 .. $n)
)
);
}
sub g {
my ($b, $n, $f) = @_;
$f->value,
sub {
g($b, $n + 1, _f($b, $n + 1)) :
g($b, $n, $f->next)
}
);
}
sub h {
my ($n, @g) = @_;
$g[$n]->value,
sub{
h(
$g[$n]->value % 10,
@g[0 .. $n - 1],
$g[$n]->next,
@g[$n + 1 .. $#g]
)
}
);
}
my $h = h
(1, map{ g
($_, 0, _f
($_, 0)) } (0 .. 9)); my $i = $h->value;
while($i < 1001){
$i = $h->value;
$h = $h->next;
}
IyEvdXNyL2Jpbi9wZXJsCnVzZSA1LjAxNjsKdXNlIHdhcm5pbmdzOwpubyB3YXJuaW5ncyBxdyhvbmNlKTsKdXNlIExpc3Q6OlV0aWwgcXcocmVkdWNlKTsKCnBhY2thZ2UgX1N0cmVhbTsKCnN1YiBuZXcgewoJbXkgJGNsYXNzID0gc2hpZnQ7CglyZXR1cm4gYmxlc3MgWyBAXyBdLCAkY2xhc3M7Cn0KCnN1YiB2YWx1ZSB7ICRfWzBdLT5bMF0gfQpzdWIgbmV4dCB7IHJlZiAkX1swXS0+WzFdIGVxICdDT0RFJyA/ICRfWzBdLT5bMV0gPSAkX1swXS0+WzFdLT4oKSA6ICRfWzBdLT5bMV0gfQoKCnBhY2thZ2UgbWFpbjsKCnN1YiB0b3AgeyBfU3RyZWFtLT5uZXcoc2hpZnQsIHVuZGVmKSB9CgpzdWIgZiB7CglteSAoJG4sICRsLCAkcCkg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