Created
May 17, 2012 10:45
-
-
Save anonymous/2718076 to your computer and use it in GitHub Desktop.
An answer of Inverse Fizzbuzz.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!perl | |
use strict; | |
use warnings; | |
use Test::More; | |
my %automata; | |
my $last_state = 15; | |
for (1 .. 15) { | |
my $fizzbuzz = ''; | |
$fizzbuzz .= 'fizz' if $_ % 3 == 0; | |
$fizzbuzz .= 'buzz' if $_ % 5 == 0; | |
next unless $fizzbuzz; | |
push @{$automata{INITIAL}{$fizzbuzz}}, [$_ => 0]; | |
push @{$automata{$last_state}{$fizzbuzz}}, | |
[$_ => $_ > $last_state ? $_ - $last_state | |
: ($_ + 15) - $last_state]; | |
$last_state = $_; | |
} | |
sub inv_fizzbuzz { | |
my @states = (['INITIAL' => undef]); | |
for my $fizzbuzz (@_) { | |
my @next_states; | |
for my $state (@states) { | |
my ($state_num, $state_range) = @$state; | |
for my $next_state_info (@{$automata{$state_num}{$fizzbuzz}}) { | |
my $next_state_num = $next_state_info->[0]; | |
my $next_state_range = $state_range // | |
[$next_state_num => $next_state_num]; | |
$next_state_range->[1] += $next_state_info->[1]; | |
push @next_states, [$next_state_num => $next_state_range]; | |
} | |
} | |
@states = @next_states or return []; # pruning | |
} | |
@states = sort { | |
$a->[1][1] - $a->[1][0] <=> $b->[1][1] - $b->[1][0] | |
} @states; | |
return $states[0][1]; | |
} | |
is_deeply(inv_fizzbuzz('fizz'), [3, 3]); | |
is_deeply(inv_fizzbuzz('buzz'), [5, 5]); | |
is_deeply(inv_fizzbuzz('fizz', 'buzz'), [9, 10]); | |
is_deeply(inv_fizzbuzz('buzz', 'fizz'), [5, 6]); | |
is_deeply(inv_fizzbuzz('fizz', 'fizz', 'buzz'), [6, 10]); | |
is_deeply(inv_fizzbuzz('fizz', 'fizz'), [6, 9]); | |
is_deeply(inv_fizzbuzz('fizz', 'buzz', 'fizz'), [3, 6]); | |
is_deeply(inv_fizzbuzz('fizzbuzz', 'fizz'), [15, 18]); | |
is_deeply(inv_fizzbuzz('buzz', 'fizz', 'buzz'), []); | |
done_testing; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment