#!/usr/bin/perl

$calculations = 0;

$numcards = 52;
$handsize = 4;  #actually handsize - 1

select((select(STDIN), $|=1)[0]);
select((select(STDOUT), $|=1)[0]);

%choices;
sub choose {
  # cache this.
  my ($m, $n) = @_;
  my $s = "$m,$n";
  return $choices{$s} if (defined $choices{$s});
  if ($n == 0) {
    $choices{$s} = 1;
    return $choices{$s};
  }
  if ($n == 1) {
    $choices{$s} = $m;
    return $choices{$s};
  }
  if ($n == $m) {
    $choices{$s} = 1;
    return $choices{$s};
  }
  $choices{$s} = choose($m-1,$n-1) + choose($m-1,$n);
  ++$calculations;
  return $choices{$s};
}

print "Ready.\n";

$totalcalcs = 0;
$jobs = 0;

while (1) {
  $_ = <STDIN>;
  chomp;
  print STDOUT ("$_ read.\n" );
  @combo = split(" ");

  $look = 0;
  $base = $handsize;
  $answer = 1;
  for (1..$combo[$handsize]) {
    if ($combo[$look] == $_) {
      $look++;
      ++$calculations;
      $base--;
      ++$calculations;
    } else {
      $answer += choose($numcards-$_,$base);
    }
  }
  print STDOUT "Answer is $answer.  ";
  print STDOUT "$calculations more calculations made.  ";
  $totalcalcs += $calculations;
  $jobs++;
  print STDOUT "Average calculations is ", $totalcalcs/$jobs, "\n";
  $calculations = 0;
}
