#!/usr/bin/perl
#require 5.008;
our $VERSION = "0.00"; #Time-stamp: <2011-11-18T09:16:50Z>

use strict;
use warnings;
use utf8; # Japanese

use Encode;

our $TRIALS = 100000;
our $CHANGE = 1;

sub Perm {
  my ($n, $k) = @_;
  my $r = 1;
  for (my $i = 0; $i < $k; $i++) {
    $r *= ($n - $i);
  }
  return $r;
}

sub Comb {
  my ($n, $k) = @_;
  if ($n - $k < $k) {
    $k = $n - $k;
  }
  return Perm($n, $k) / Perm($k, $k);
}

sub make_board {
  my @c = (0 .. 21);
#  my @c = (0 .. 23);
#  my @c = (0 .. 15);
  splice(@c, 13, 1);
  splice(@c, 0, 1);

  my @d;
  while (@c) {
    my $n = int(rand(1) * scalar(@c));
    push(@d, [splice(@c, $n, 1), int(rand(2))]);
  }
  @c = splice(@d, 0, 6);

  if ($CHANGE) {
    my $n = 0;
    for (my $i = 0; $i < @c; $i++) {
      if ($c[$i][0] % 2) {
	$n++;
      }
    }
    my $simul = 0;
    for (my $i = 0; $i < @c; $i++) {
      if ($c[$i][0] == 8) {
	$simul++;
      } elsif ($c[$i][0] == 11) {
	$simul++;
      }
    }

    for (my $i = 0; $i < @c; $i++) {
      if ($n >= 2 && $n <= 4) {
	if ($c[$i][0] == 8) {
	  $c[$i][0] = 11;
	} elsif ($c[$i][0] == 11) {
	  $c[$i][0] = 8;
	}
      }
    }
  }
  return @c;
}

MAIN:
{
  my @n = (0) x 64;
  my @b = (0) x 7;

  for (my $i = 0; $i < $TRIALS; $i++) {
    my @c = make_board();
    my $c = 0;
    my $b = 0;
    my $s = 0;
    my $e = 0;
    for (my $j = 0; $j < @c; $j++) {
      if ($c[$j][1]) {
	$s++;
      }
      if ($c[$j][0] % 2) {
	$c = $c * 2 + 1;
	$b++;
	if ($c[$j][1] == 1) {
	  $e++;
	}
      } else {
	$c = $c * 2;
	if ($c[$j][1] == 0) {
	  $e++;
	}
      }
    }
    if ($b == 3) {
      if ($s == 0 || $e == 0) {
	$c = 0;
	$b = 0;
      }
      if ($s == 6 || $e == 6) {
	$c = 63;
	$b = 6;
      }
    }
	

    $n[$c]++;
    $b[$b]++;
  }

  for (my $i = 0; $i < @n; $i++) {
    printf("%02x: %g\n", $i, $n[$i] / $TRIALS);
  }

  for (my $i = 0; $i < @b; $i++) {
    printf("%01x: %g (%g)\n", $i, $b[$i] / $TRIALS, $b[$i] / $TRIALS / Comb(6,$i));
  }
}
