役判定

local $\ = "\n";

my $a = "m2m3m3m4m4m5m5m5m5m6m6m6m6m7";

my %hash;
foreach my $hai ( $a =~ /\w\d/g ) {

 if (exists $hash{$hai}) {
  $hash{$hai}++;
 }
 else{ 
  $hash{$hai}=1;
 }
}

# 頭候補さがし
my @heads;
while (my($k, $v) = each %hash) {
 print "$k=$v";
 if ($v >= 2) {
  push @heads, $k;
  print "if head $k";
 }
}

print "> hantei start";
foreach my $head ( @heads ) {
 print "-- head $head";
 my %s_hash = %hash;
 $s_hash{$head} -= 2;
 delete $s_hash{$head} if ($s_hash{$head} == 0);
 
 # 刻子判定
 while (my ($k, $v) = each %s_hash) {
  if ($v >= 3) {
   $s_hash{$k} -= 3;
   delete $s_hash{$k} if ($s_hash{$k} == 0);
   print "cotsu $k";
  }
 }
 
 # 順子判定
 # s_hash にキーが無くなれば成功
 my $success = 1;
 my $key_num;
 while ( ($key_num = keys %s_hash) != 0) {
  # sort
  my $first; # 一番若いのを取得 順子
  foreach my $k (sort keys %s_hash) {
   #print "$k=$s_hash{$k}";
   $first = $k;
   last;
  }
  print "first=$first";
  #my @list = keys %s_hash;
  #print "list=@list";

  my ($type, $num) = split //, $first;
  my $second = $type . ($num + 1);
  my $third  = $type . ($num + 2);
  
  if (exists $s_hash{$second} && exists $s_hash{$third}) {
   #print "+ $first $second $third";
   $s_hash{$first}  -= 1;
   $s_hash{$second} -= 1;
   $s_hash{$third}  -= 1;
   
   delete $s_hash{$first}  if $s_hash{$first}  == 0;
   delete $s_hash{$second} if $s_hash{$second} == 0;
   delete $s_hash{$third}  if $s_hash{$third}  == 0;
  }
  else{
   # faild
   $success = 0;
   last;
  }
 }
 
 if ($success == 1) {
  print "ok!";
 }
 else{
  print "faild";
 }
  
 #while (my ($k, $v) = each %s_hash) {
 # print "$k=$v";
 #}
}

--- run
m6=4
if head m6
m5=4
if head m5
m3=2
if head m3
m4=2
if head m4
m7=1
m2=1
> hantei start
-- head m6
cotsu m5
first=m2
first=m3
first=m6
faild
-- head m5
cotsu m6
first=m2
first=m3
first=m5
ok!
-- head m3
cotsu m5
cotsu m6
first=m2
faild
-- head m4
cotsu m5
cotsu m6
first=m2
faild

 
第10回 麻雀の役を判定する - 地球にやさしいアルゴリズム:ITpro
http://itpro.nikkeibp.co.jp/article/COLUMN/20070516/271225/?ST=develop&P=3
 
麻雀の作り方(あがり判定)
http://www5f.biglobe.ne.jp/~kenmo/program/majang/agari/agari.html
http://www.onionsoft.net/hsp/mahjong.txt