IT練習ノート

IT関連で調べたこと(実際は嵌ったこと)を書いています。

FizzBuzz

今更ながら、PerlFizzBuzzを考えてみた。
http://ja.wikipedia.org/wiki/Fizz_Buzz
FizzBuzzの判定の定義を外出しにしてみた。

use strict;
use Data::Dumper;
use List::Util;

my $upper_num = 30;
my $criteria = +{
 3 =>  'fizz',
 5 =>  'buzz',
 15 => 'fizzbuzz',
};
my @criteria_keys = sort { $b <=> $a }keys %$criteria;

sub saySmt {
  my ($num) = @_;
  my $key = List::Util::first { $num % $_ == 0 } @criteria_keys;
  return $key ? $criteria->{$key} : "";
}

my @in = (1..$upper_num);
my %ret = map { $_ => saySmt($_) } @in;

print Dumper(\%ret);

$VAR1 = {
          '11' => '',
          '21' => 'fizz',
          '7' => '',
          '26' => '',
          '17' => '',
          '2' => '',
          '22' => '',
          '1' => '',
          '18' => 'fizz',
          '30' => 'fizzbuzz',
          '23' => '',
          '16' => '',
          '13' => '',
          '29' => '',
          '27' => 'fizz',
          '25' => 'buzz',
          '6' => 'fizz',
          '28' => '',
          '3' => 'fizz',
          '9' => 'fizz',
          '12' => 'fizz',
          '20' => 'buzz',
          '14' => '',
          '15' => 'fizzbuzz',
          '8' => '',
          '4' => '',
          '24' => 'fizz',
          '19' => '',
          '10' => 'buzz',
          '5' => 'buzz'
        };