This question already has answers here:
Non-repetitive random number
(10 answers)
Closed 7 years ago.
I am looking to print 20 random numbers. Is it possible to do this with a for loop; and if it is, how can I do it?
Here is my current code:
int[] randomNum = new int[20];
Random RandomNumber = new Random();
for (int i = 0; i < 20; i++)
{
randomNum[i] = RandomNumber.Next(1, 80);
}
foreach (int j in randomNum)
{
Console.WriteLine("First Number:{0}", j);
Thread.Sleep(200);
}
Just loop the number generation until it generated a new number:
int[] randomNum = new int[20];
Random RandomNumber = new Random();
for (int i = 0; i < 20; i++)
{
int number;
do
{
number = RandomNumber.Next(1, 80);
} while(randomNum.Contains(number));
randomNum[i] = number;
}
foreach (int j in randomNum)
{
Console.WriteLine("First Number:{0}", j);
Thread.Sleep(200);
}
According to your last comment, I would say:
for (int i = 0; i < 20; i++)
{
int num;
do
{
num = RandomNumber.Next(1, 80);
} while (randomNum.Contains(num));
randomNum[i] = num;
}
Why you used array for this? If you want to print random numbers, you can write this.
Random RandomNumber = new Random();
for (int i = 0; i < 20; i++)
{
int randomNum = RandomNumber.Next(1, 80);
Console.WriteLine("Number:{0}", randomNum);
Thread.Sleep(200);
}
you don't need in randomNum. Just do it so:
for (int i = 0; i < 20; i++)
{
Console.WriteLine("First Number:{0}", RandomNumber.Next(1, 80));
}
If you wanna avoid dublication, do so:
List<int> intList = new List();
for (int i = 0; i < 20; i++)
{
int r = RandomNumber.Next(1, 80);
foreach(int s in intList) if(s!=r){
intList.Add(s);
Console.WriteLine("First Number:{0}", RandomNumber.Next(1, 80));
}else i--;
}
Related
When I try to generate a new random int each time to fill the array it just gives me back the same number. The seed won't change. I'm sure there is an easy answer but I have been looking at it for a few hours and just can't see it.
internal class LingoCard : ILingoCard
{
private ICardNumber[,] _cardNumber;
private int _teller;
private int _oddTeller;
private int rand;
Random rnd = new Random();
public LingoCard(bool useEvenNumbers)
{
ICardNumber[,] cardNumber = new ICardNumber[5,5];
_cardNumber = cardNumber;
if (useEvenNumbers == true)
{
UseEvenNumbers(_cardNumber);
} else {
UseOddNumbers(_cardNumber);
}
}
public void UseEvenNumbers(ICardNumber[,] cardNumber)
{
while (_teller < 70)
{
for (int g = 0; g < 1; g++)
{
rand = rnd.Next(0, 70);
CardNumber _walue = new CardNumber(rand);
if (rand % 2 == 0)
{
for (int i = 0; i < cardNumber.GetLength(0); i++)
{
for (int j = 0; j < cardNumber.GetLength(1); j++)
{
_cardNumber[i, j] = _walue;
}
_teller++;
}
}
}
}
}
The reason your random number is the same for all the card numbers is because you're generating one Random number before the two nested for loops and using it to fill in every card number
rand = rnd.Next(0, 70); // Random number generated once here
CardNumber _walue = new CardNumber(rand);
if (rand % 2 == 0)
{
for (int i = 0; i < cardNumber.GetLength(0); i++)
{
for (int j = 0; j < cardNumber.GetLength(1); j++)
{
_cardNumber[i, j] = _walue; // same random value assigned for every card number here
}
_teller++;
}
}
In order to fix it you'd need to generate the random number inside the for loop when you are assigning _cardNumber
for (int i = 0; i < cardNumber.GetLength(0); i++)
{
for (int j = 0; j < cardNumber.GetLength(1); j++)
{
rand = rnd.Next(0, 70) * 2; // Multiply by 2 so the random number is even
CardNumber _walue = new CardNumber(rand);
_cardNumber[i, j] = _walue;
}
_teller++;
}
Let me know if this helps!
I've been working on a sorting algorithm and one condition says that the elements in the array should be program generated.
This is the code I've been working on.
int f;
Console.WriteLine("Enter how many elements you want to be sorted:");
f = Convert.ToInt32(Console.ReadLine());
int[] myArray = new int[f];
int smallest, tmp;
Console.WriteLine("Unsorted List");
foreach (int a in myArray)
Console.Write(a + " ");
for (int i = 0; i < myArray.Length - 1; i++)
{
smallest = i;
for (int j = i + 1; j < myArray.Length; j++)
{
if (myArray[j] < myArray[smallest])
{
smallest = j;
}
tmp = myArray[smallest];
myArray[smallest] = myArray[i];
myArray[i] = tmp;
}
}
Console.WriteLine("\nSorted List Using Selection Sort:");
for (int i=0; i < myArray.Length; i++)
{
Console.Write(myArray[i] + " ");
The result of this program is just 0. How can I make the elements in array program generated? Is there a specific code block?
Please note we should use i < myArray.Length to Iterate the array instead of i < myArray.Length-1.
You can try the following code to add the elements in program generated array.
static void Main(string[] args)
{
int f;
Console.WriteLine("Enter how many elements you want to be sorted:");
f = Convert.ToInt32(Console.ReadLine());
int[] myArray = new int[f];
int temp = 0;
int minIndex = 0;
Console.WriteLine("Unsorted List");
for (int i = 0; i < myArray.Length; i++)
{
myArray[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < myArray.Length; i++)
{
minIndex = i;
for (int j = i; j < myArray.Length; j++)
{
if (myArray[j] < myArray[minIndex])
{
minIndex = j;
}
}
temp = myArray[minIndex];
myArray[minIndex] = myArray[i];
myArray[i] = temp;
}
Console.WriteLine("\nSorted List Using Selection Sort:");
for (int i = 0; i < myArray.Length; i++)
{
Console.Write(myArray[i] + " ");
}
Console.ReadKey();
}
Besides, I have modified the related code about Selection Sort, which makes it can produce the correct sort.
Result:
Update for generate the random array:
int f;
Console.WriteLine("Enter how many elements you want to be sorted:");
f = Convert.ToInt32(Console.ReadLine());
int[] myArray = new int[f];
Random randNum = new Random();
for (int i = 0; i < myArray.Length; i++)
{
myArray[i] = randNum.Next(1, 100);
}
Console.WriteLine("The radnom array is ");
foreach (var item in myArray)
{
Console.WriteLine(item);
}
I made a program to generate 7 random numbers for a lottery using a array. I have generated a random number between 1, 50 but every number shows in order and not on the same line. I would also like to store the auto generated numbers in a array to use. I am not sure how to fix this any help would be appreciated
static void AutoGenrateNumbers()
{
int temp;
int number = 0;
int[] lotto = new int[7];
Random rand = new Random();
for (int i = 0; i <= 50; i++)
{
number = 0;
temp = rand.Next(1, 50);
while (number <= i)
{
if (temp == number)
{
number = 0;
temp = rand.Next(1, 50);
}
else
{
number++;
}
}
temp = number;
Console.WriteLine($"the new lotto winning numbers are:{number}Bonus:{number}");
}
}
Is this what you need?
static void AutoGenrateNumbers()
{
int temp;
int[] lotto = new int[7];
Random rand = new Random();
for (int i = 0; i < 7; i++)
{
temp = rand.Next(1, 50);
lotto[i]= temp;
}
Console.Write($"the new lotto winning numbers are: ");
for (int i = 0; i < 6; i++)
{
Console.Write(lotto[i]+" ");
}
Console.Write($"Bonus:{lotto[6]}");
}
edit: if you want the numbers to be unique:
static void AutoGenrateNumbers()
{
int temp;
int[] lotto = new int[7];
Random rand = new Random();
for (int i = 0; i < 7; i++)
{
do
{
temp = rand.Next(1, 50);
}
while (lotto.Contains(temp));
lotto[i]= temp;
}
Console.Write($"the new lotto winning numbers are: ");
for (int i = 0; i < 6; i++)
{
Console.Write(lotto[i]+" ");
}
Console.Write($"Bonus:{lotto[6]}");
}
A better way to do this is just to generate all the numbers 1-50, shuffle them and then just take 7. Using Jon Skeet's Shuffle extension method found here:
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
T[] elements = source.ToArray();
for (int i = elements.Length - 1; i >= 0; i--)
{
int swapIndex = rng.Next(i + 1);
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
}
}
Now your code is very simple:
static void AutoGenrateNumbers()
{
var lotto = Enumerable.Range(0, 50).Shuffle(new Random()).Take(7);
Console.WriteLine("the new lotto winning numbers are: {0}", string.Join(",", lotto));
}
Fiddle here
Just to add to the existing answers tried to do that in one LINQ statement:
static void Main(string[] args)
{
var rand = new Random();
Enumerable
.Range(1, 7)
.Aggregate(new List<int>(), (x, y) =>
{
var num = rand.Next(1, 51);
while (x.Contains(num))
{
num = rand.Next(1, 51);
}
x.Add(num);
return x;
})
.ForEach(x => Console.Write($"{x} "));
}
The result is something like:
34 24 46 27 11 17 2
i'm code:
Random rand = new Random();
int[] arr = new int[4];
for (int i = 0; i < 4; i++)
{
for (int k = 0; k < 4; k++)
{
int rad = rand.Next(1, 5);
if (arr[k] != rad)
arr[i] = rad;
}
}
for (int i = 0; i < 4; i++)
MessageBox.Show(arr[i].ToString());
I wanna production numbers from 1 to 4 am and unequal with each other.
tnx.
Think it the other way round:
instead of:
generating a number and then check it if it is not duplicate
you make it such that:
you already have a set of non-duplicate numbers, then you take it
one-by-one - removing the possibilities of duplicates.
Something like this will do:
List<int> list = Enumerable.Range(1, 4).ToList();
List<int> rndList = new List<int>();
Random rnd = new Random();
int no = 0;
for (int i = 0; i < 4; ++i) {
no = rnd.Next(0, list.Count);
rndList.Add(list[no]);
list.Remove(list[no]);
}
The result is in your rndList.
This way, no duplicate will occur.
Create an array with unique elements and then shuffle it, like in the code below, it will shuffle an array in uniformly random order it uses Fisher-Yates shuffle algorithm:
int N = 20;
var theArray = new int[N];
for (int i = 0; i < N; i++)
theArray[i] = i;
Shuffle(theArray);
public static void Shuffle(int[] a) {
if (a == null) throw new ArgumentNullException("Array is null");
int n = a.Length;
var theRandom = new Random();
for (int i = 0; i < n; i++) {
int r = i + theRandom.Next(n-i); // between i and n-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
Explanation and template version of algorithm could be found in this post with nice answer from Jon Skeet.
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
T[] elements = source.ToArray();
// Note i > 0 to avoid final pointless iteration
for (int i = elements.Length-1; i > 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
int swapIndex = rng.Next(i + 1);
T tmp = elements[i];
elements[i] = elements[swapIndex];
elements[swapIndex] = tmp;
}
// Lazily yield (avoiding aliasing issues etc)
foreach (T element in elements)
{
yield return element;
}
}
Create a list containing the numbers you want, then shuffle them:
var rnd = new Random();
List<int> rndList = Enumerable.Range(1, 4).OrderBy(r => rnd.Next()).ToList();
If you want an array instead of a list:
var rnd = new Random();
int[] rndArray = Enumerable.Range(1, 4).OrderBy(r => rnd.Next()).ToArray();
int[] arr = new int[5];
int i = 0;
while (i < 5)
{
Random rand = new Random();
int a = rand.Next(1,6);
bool alreadyexist = false;
for (int j = 0; j < 5; j++)
{
if (a == arr[j])
{
alreadyexist = true;
}
}
if (alreadyexist == false)
{
arr[i] = a;
i++;
}
}
for (int k = 0; k < 5; k++)
{
MessageBox.Show(arr[k].ToString());
}
This question already has answers here:
Randomize a List<T>
(28 answers)
Closed 9 years ago.
I need to print numbers from 1 to 50 in random order without repeating
it .
static void Main(string[] args)
{
ArrayList r = new ArrayList();
Random ran = new Random();
for (int i = 0; i < 50; i++)
{
r.Add(ran.Next(1,51));
}
for (int i = 0; i < 50; i++)
Console.WriteLine(r[i]);
Console.ReadKey();
}
What you want here is the Fisher Yates Shuffle
Here is the algorithm as implemented by Jeff Atwood
cards = Enumerable.Range(1, 50).ToList();
for (int i = cards.Count - 1; i > 0; i--)
{
int n = ran.Next(i + 1);
int temp = cards[i];
cards[i] = cards[n];
cards[n] = temp;
}
If you don't want to repeat the numbers between 1 and 50, your best bet is to populate a list with the numbers 1 to 50 and then shuffle the contents. There's a good post on shuffling here:
Randomize a List<T>
All you need to do is this check if the number already exists in the list and if so get another one:
static void Main(string[] args)
{
ArrayList r = new ArrayList();
Random ran = new Random();
int num = 0;
for (int i = 0; i < 50; i++)
{
do { num = ran.Next(1, 51); } while (r.Contains(num));
r.Add(num);
}
for (int i = 0; i < 50; i++)
Console.WriteLine(r[i]);
Console.ReadKey();
}
Edit: This will greatly increase the effeciency, preventing long pauses waiting for a non-collision number:
static void Main(string[] args)
{
List<int> numbers = new List<int>();
Random ran = new Random();
int number = 0;
int min = 1;
int max = 51;
for (int i = 0; i < 50; i++)
{
do
{
number = ran.Next(min, max);
}
while (numbers.Contains(number));
numbers.Add(number);
if (number == min) min++;
if (number == max - 1) max--;
}
for (int i = 0; i < 50; i++)
Console.WriteLine(numbers[i]);
Console.ReadKey();
}