Well, I've been coding this program that has the objective to create random numbers, and then store them in an array (linhas[n]), but I don't want them to repeat. I started by doing a for cicle (int i = 0; i < n; i++) and inside it I wrote that an variable a (int a) was equal to a random number generated from the random function (r). Then I compared if "a" already existed in the array, using "bool b = Array.Exists(linhas, elements => elements == a);", then wrote that if "b" was true it would decrease the "i" value by one, to repeat the same i cicle, doing linhas[i] = a if "b" was false. Then it would write the elements of the array. The problem that I'm getting is that when I oppen the program and write the value of "n" the program just doesn't do nothing, just a black screen. I already checked and if I put the value of "n" = 1, the program generates just one number, number 1. But if I put "n" = 2 it just stops. If anyone understood what I said here and could help me, please just throw some tips!
The code here:
static void Main(string[] args)
{
int n;
Console.Write("Escreva o número de linhas a aparecer: ");
n = Convert.ToInt32(Console.ReadLine());
int[] linhas = new int[n];
var r = new Random();
for (int i = 0; i < n; i++)
{
int a = r.Next(1, n);
bool b = Array.Exists(linhas, elements => elements == a);
if (b == true)
{
i--;
}
else
{
linhas[i] = a;
}
}
Console.WriteLine("");
for (int i = 0; i < n; i++)
{
Console.WriteLine(linhas[i]);
}
Console.Read();
}
Aucun commentaire:
Enregistrer un commentaire