简体   繁体   中英

Algorithm to implement the BINGO game

For those who doesn't know a BINGO game, its played as follows

1)You get a BINGO card in which there is a NXN matrix of numbers randomly printed.Numbers are unique.The max number printed can be greater than N^2. eg if you have 5x5 matrix then the max number can be 75 as well.But the range of numbers is pre-decided say 1 to M.

2)A person speaks out numbers randomly in the range 1 to M.

3)If the number is on your card you cross the number.

4)The process of crossing numbers is repeated.When you have crossed a full row or a full column or the two diagonals,then you get your first bingo The game is still continued as the total BINGOs possible are N+N+2 for N rows,N columns and 2 diagonals.

Now I want to create an algorithm for it.The user will input random numbers and the algorithm will hear them and cross its numbers in the matrix(already provided).As soon as it gets BINGO it declares it.What is the best possible approach


I tried it as maintaining a 2-D matrix for the card

When a number is announced, i search it in O(NxN) time.When I find it ,I make it as 0.

After making it as 0, I search whether it the corresponding row & column has now all zeroes.If it was on the diagonal , I also search for the diagonal.It takes O(3N) time.

Any better approach?

You can form a map for each number that would map to a pair (row, column).

if ( myMap[number] exists ) {
  then increment rowCount[ myMap[number].row ];
  then increment columnCount[ myMap[number].column ];
}

if ( rowCount[myMap[number].row] == N ) { bingo! }
if ( columnCount[myMap[number].column] == N ) { bingo! }

myMap.erase( number );

Similarly for diagonals.

Use an array to store the numbers on the card and keep it sorted. Upon number being called, search the number using Binary Search (O(logN) time). This should be a quick approach.

Create a class Coordinate that holds x and y position in bingo card. NxN array of booleans initialized to false to keep track of what gets crossed off on bingo card.

N^2 time to iterate through bingo card and add each number to hash table using the number as the key and a new Coordinate as the value.

n time to iterate through all the numbers that will be called out, retrieve the Coordinate from the hash table, and update the status of the boolean array. In case of duplicate numbers called, you must retrieve and update boolean array until the hash table does not contain the key.

4N time to check each direction on boolean array for first bingo

N^2 + n*4N total runtime

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM