如何用C#为BINGO宾果面板实现无重复随机数填充功能
实现逻辑
标准宾果卡的数字分布有固定规则,按列划分范围且所有数字不重复:
- B列(第0列):数字范围1~15
- I列(第1列):数字范围16~30
- N列(第2列):数字范围31~45,中间第3行位置固定为免费空位X
- G列(第3列):数字范围46~60
- O列(第4列):数字范围61~75
我们可以新增一个生成指定范围无重复随机数的工具方法,再按列填充到二维数组中即可。
完整可运行代码
using System; using System.Collections.Generic; using System.Linq; namespace BingoCardGen { class Program { static void Main(string[] args) { string[,] table = new string[5, 5]; // 新增宾果卡填充逻辑 for (int col = 0; col < 5; col++) { int rangeMin = col * 15 + 1; int rangeMax = (col + 1) * 15; // 生成当前列5个无重复随机数 List<int> colNums = GenerateUniqueNumbers(rangeMin, rangeMax, 5); for (int row = 0; row < 5; row++) { // 中间免费位跳过填充 if (row == 2 && col == 2) continue; // 补空格对齐输出 table[row, col] = colNums[row].ToString().PadLeft(2); } } printboard(table); Console.ReadKey(); } // 新增:生成指定范围内指定数量的无重复随机数 static List<int> GenerateUniqueNumbers(int min, int max, int count) { // 用Guid生成随机种子,避免短时间多次调用生成重复序列 Random random = new Random(Guid.NewGuid().GetHashCode()); HashSet<int> uniqueNums = new HashSet<int>(); while (uniqueNums.Count < count) { uniqueNums.Add(random.Next(min, max + 1)); } return uniqueNums.ToList(); } static void printboard(string[,] table) { int i, j; string[] headings = { "B", "I", "N", "G", "O" }; for (i = 0; i < 5; i++) { Console.Write("{0} ", headings[i]); } Console.WriteLine("\n------------------------------"); for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { if (i == 2 && j == 2) Console.Write("X "); else Console.Write("{0} ", table[i, j]); } Console.WriteLine(); } } } }
效果说明
运行后会自动生成符合规则的宾果卡,所有数字无重复,每列数字都在对应范围内,中间位置固定显示X,输出自动对齐方便查看。
内容的提问来源于stack exchange,提问作者Mc Dz
相关产品推荐
相关产品推荐

