#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define MAX_CARDS 500
#define CYCLES 1000
typedef struct elem
{
int number;
int found;
}elem;
static int check_number(elem card[][5], int n);
static int check_bingo(elem card[][5], int row, int col);
void bingo_simulate(void)
{
elem card[MAX_CARDS][5][5];
int cycle;
long long sum;
int avg;
srand((unsigned int)time(NULL));
/* run bingo simulation for CYCLES times */
for(cycle = 0, sum = 0; cycle < CYCLES; cycle++)
{
int num_call;
int i, j, k, range, offset;
int ncards;
/* fill all the cards with random numbers */
for(i = 0; i < MAX_CARDS; i++)
{
for(j = 0, range = 15, offset = 1; j < 5; j++, offset += 15)
{
for(k = 0; k < 5; k++)
{
card[i][j][k].number = (rand() % range) + offset;
card[i][j][k].found = 0;
}
}
}
/* keep calling until bingo */
for(num_call = 0;;)
{
num_call++;
/* call for every card */
for(ncards = 1; ncards <= MAX_CARDS; ncards++)
{
int rand_num;
/* selet a random number between 1 to 75 including 1 and 75 */
rand_num = (rand() % 75) + 1;
/* check if the random number is present in card */
if(check_number(card[ncards], rand_num))
goto BINGO;
}
}
BINGO:
sum += num_call;
}
/* print average number of calls */
avg = sum/CYCLES;
printf("average number of calls = %d\n", avg);
}
/* set found if the number is found. Then check condition for bingo and return 1 if true; otherwise return 0; */
static int check_number(elem card[][5], int n)
{
int i, j;
for(i = 0; i < 5; i++)
{
for(j = 0; j < 5; j++)
{
if(card[i][j].found == 0 && card[i][j].number == n)
{
card[i][j].found = 1;
goto FOUND;
}
}
}
FOUND:
if(i == 5 && j == 5) /* not found */
return 0;
return check_bingo(card, i, j);
}
/* return 1 if bingo; otherwise return 0 */
static int check_bingo(elem card[][5], int row, int col)
{
int i, j;
/* check row */
for(i = 0; (i < 5) && (card[row][i].found == 1); i++);
if(i == 5)
return 1;
/* check column */
for(i = 0; (i < 5) && (card[i][col].found == 1); i++);
if(i == 5)
return 1;
/* check first diagonal */
if(row == col)
{
for(i = 0; (i < 5) && (card[i][i].found == 1); i++);
if(i == 5)
return 1;
}
/* check second diagonal */
if((row + col) == 4)
{
for(i = 0, j = 4; (i < 5) && (card[i][j].found == 1); i++, j--);
if(i == 5)
return 1;
}
return 0;
}