#!/usr/bin/perl -w
###########################################
# base-rate -- the base rate fallacy
# Mike Schilli, 2015 (m@perlmeister.com)
###########################################
use strict;
use Data::Dumper;
use Algorithm::Numerical::Shuffle
  qw( shuffle );

my $nof_patients  = 1000;
my $nof_infects   = 8;
my $tested_pos    = 0;
my $tested_corr   = 0;

my @patients = ( 0 ) x $nof_patients;

infect( \@patients, $nof_infects );

while( $tested_pos != 100000 ) {

  my $patient = 
    $patients[ rand $nof_patients ];
  my $result = examine( $patient );

  next if !$result;

  $tested_pos++;
  
    # diagnosis correct?
  $tested_corr++ if $patient;
}

printf "Test score: %3.2f%%\n", 
  $tested_corr / $tested_pos * 100.0;

###########################################
sub examine {
###########################################
  my( $patient ) = @_;

  my $rand = int rand 100;

  if( $patient ) {
      # 90% detection rate
    return $rand < 90 ? 1 : 0;
  } else {
      # 7% false positive
    return $rand < 7 ? 1 : 0;
  }
}

###########################################
sub infect {
###########################################
  my( $patients, $howmany ) = @_;

  my @rand_indices = 
    shuffle ( 0 .. $#$patients );

  while( $howmany-- ) {
    $patients[ shift @rand_indices ] = 1;
  }
}
