Skip to content

Instantly share code, notes, and snippets.

Created May 17, 2012 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/2718076 to your computer and use it in GitHub Desktop.
Save anonymous/2718076 to your computer and use it in GitHub Desktop.
An answer of Inverse Fizzbuzz.
#!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