fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <random>
  5. #include <numeric>
  6.  
  7. using namespace std;
  8.  
  9. void generateBingoCard(int rows = 3) {
  10. const int cols = 9;
  11. const int numsPerRow = 5;
  12. mt19937 engine(random_device{}()); // Shared random engine
  13.  
  14. // 1. Initialize Column Pools
  15. vector<vector<int>> colPool(cols);
  16. for (int j = 0; j < cols; j++) {
  17. int start = (j * 10) + 1;
  18. int end = (j == 8) ? 90 : (j + 1) * 10;
  19. for (int v = start; v <= end; v++) colPool[j].push_back(v);
  20. shuffle(colPool[j].begin(), colPool[j].end(), engine);
  21. }
  22.  
  23. vector<vector<int>> card(rows, vector<int>(cols, 0));
  24. vector<int> colCount(cols, 0);
  25. vector<int> rowCount(rows, 0);
  26.  
  27. // 2. Pass 1: Every column must have at least one number
  28. for (int j = 0; j < cols; j++) {
  29. int r = j % rows;
  30. card[r][j] = colPool[j].back();
  31. colPool[j].pop_back();
  32. colCount[j]++;
  33. rowCount[r]++;
  34. }
  35.  
  36. // 3. Pass 2: Fill remaining slots row-by-row (Unbiased)
  37. for (int i = 0; i < rows; i++) {
  38. // Create a list of column indices [0, 1, ..., 8] using a for loop
  39. vector<int> colOrder(cols);
  40. for (int k = 0; k < cols; k++) {
  41. colOrder[k] = k;
  42. }
  43.  
  44. // Shuffle the order we look at columns for THIS specific row
  45. shuffle(colOrder.begin(), colOrder.end(), engine);
  46.  
  47. for (int j : colOrder) {
  48. // Stop if the row already has 5 numbers
  49. if (rowCount[i] >= numsPerRow) break;
  50.  
  51. // Only fill if cell is empty
  52. if (card[i][j] == 0) {
  53. card[i][j] = colPool[j].back();
  54. colPool[j].pop_back();
  55. colCount[j]++;
  56. rowCount[i]++;
  57. }
  58. }
  59. }
  60.  
  61. // 4. In-place Vertical Sort (preserves 0/nil positions)
  62. for (int j = 0; j < cols; j++) {
  63. for (int pass = 0; pass < rows - 1; pass++) {
  64. for (int i = 0; i < rows - 1; i++) {
  65. if (card[i][j] > 0 && card[i+1][j] > 0 && card[i][j] > card[i+1][j]) {
  66. swap(card[i][j], card[i+1][j]);
  67. }
  68. }
  69. }
  70. }
  71.  
  72. // Output formatted like the sample
  73. for (int i = 0; i < rows; i++) {
  74. cout << "[";
  75. for (int j = 0; j < cols; j++) {
  76. printf("%2d%s", card[i][j], (j == cols - 1 ? "" : ", "));
  77. }
  78. cout << "]" << (i == rows - 1 ? "," : "") << endl;
  79. }
  80. }
  81.  
  82. int main() {
  83. generateBingoCard(3);
  84. return 0;
  85. }
Success #stdin #stdout 0.01s 5304KB
stdin
Standard input is empty
stdout
[ 1,  0, 25, 39,  0,  0, 61,  0, 83]
[ 3, 19,  0,  0, 41,  0, 64, 73,  0]
[ 0,  0, 23,  0, 45, 51, 67,  0, 87],