【发布时间】:2021-08-01 16:03:43
【问题描述】:
我需要像彩票程序一样将 10 个随机数组合(不重复)流式写入 file.txt。我得到了除了非重复随机数之外的所有东西。它必须像具有 10 种组合的 2D 数组一样被视为(file.txt)。
class Matriz
{
private int[,] array;
private int nfilas, ncols;
public void Ingresar()
{
Random aleatori = new Random();
nfilas = 10;
ncols = 6;
Console.WriteLine("\n");
array = new int[nfilas, ncols];
for (int filas = 0; filas < nfilas; filas++)
{
for (int columnas = 0; columnas < ncols; columnas++)
array[filas, columnas] = aleatori.Next(0, 50);
}
}
public void Imprimir()
{
StreamWriter fitxer = new StreamWriter(@"C:\andres\lotto649.txt");
int contador = 0;
for (int f = 0; f < nfilas; f++)
{
for (int c = 0; c < ncols; c++)
fitxer.Write(array[f, c] + " ");
fitxer.WriteLine();
contador++;
}
fitxer.WriteLine($"\n\n\tHay {contador} combinaciones de la Loteria 6/49");
fitxer.Close();
}
static void Main(string[] args)
{
Matriz array_menu = new Matriz();
array_menu.Ingresar();
array_menu.Imprimir();
}
}
【问题讨论】:
-
它实际上可以工作(编译,写出),但它会在同一行中生成重复的组合。如何解决?
-
我假设您只想避免每行重复。我认为最简单的解决方案是跟踪为该行写入的数字,如果已经包含下一个随机数,则继续生成新数字,直到您得到一个尚未在列表中的数字。
-
基本思路是:列出你的 50 个号码,然后随机取一个号码并从列表中删除该号码,然后获取下一个号码,直到列表为空或你有足够的号码。
-
@jack-t-spades 是的,它只是为了避免每行重复,您建议使用 if (nums.Contains (aleatori)) 条件?像这样?
-
不相关:我建议创建一个静态 Random 对象作为类字段而不是本地对象。