C# Random is generate same value in the foreach [duplicate] - c#

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 6 years ago.
I want to get random number in per repeat of foreach loop
#foreach (var item in Model)
{
Random r = new Random();
int s = r.Next(0, 5);
<span>#(s)</span>
}
But I get same value instead of random value.

Random r = new Random();
#foreach (var item in Model)
{
int s = r.Next(0, 5);
<span>#(s)</span>
}

Related

Subtract the elements of two lists from each other with unknown element lengths in C# [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 1 year ago.
I have two lists in my program that the length of the lists is not equal. I want to subtract the members of these two lists element by element and save them in one list.
List<double> arrivals = new List<double>();
List<double> departure = new List<double>();
List<double> delays = new List<double>();
double departure_p = 0.8;
double arrival_p = 0.45;
int slot = 0;
while (slot < 1000)
{
Random a = new Random();
double arrival_t = a.NextDouble();
Random d = new Random();
double departure_t = d.NextDouble();
if (departure_t <= departure_p)
{
departure.Add(departure_t);
}
if (arrival_t <= arrival_p)
{
arrivals.Add(arrival_t);
}
slot++;
}
When I use this method I encounter the exception system.IndexOutOfRangeException.
for (int i = 0; i <= arrivals.Count; i++)
{
delays.Add(departure[i] - arrivals[i]);
}
foreach (var item in delays)
Console.WriteLine(item);
How can I do this?
If you write i <arrivals.Count in the for loop, the problem will be solved.
You can also use the Zip method in Linq.
var delay = departure.Zip(arrivals, (depart, arri) => depart - arri);
foreach (var item in delay)
{
Console.WriteLine(item);
}
Well, IndexOutOfRangeException means that index i exceeds Count of either departure or arrivals so departure[i] - arrivals[i] becomes illegal. You can amend the for loop as
for (int i = 0; i < Math.Min(arrivals.Count, depart.Count); i++)
delays.Add(departure[i] - arrivals[i]);
foreach (var item in delays)
Console.WriteLine(item);
with i < Math.Min(arrivals.Count, depart.Count) conditon we now guarantee, that i will never be beyond both departure and arrivals

C# Random Function only produces one value [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 5 years ago.
In this for loop I keep getting same value from my Random Function.
How can I get the Random Function to be actually Random?
for (int i=0; i<50; i++){
Random random = new Random();
int randomSong = random.Next(0, songList.Count - 1);
var selectedSong = songList.ElementAt(randomSong);
}
You need to define Random outside of the loop.
var rand = new Random();
for (int x = 0; x<50;x++)
{
var song = list.ElementAt(rand.Next(list.Count()));
}

how to write a certain array item multiple times [duplicate]

This question already has answers here:
filling a array with random numbers between 0-9 in c# [duplicate]
(3 answers)
Closed 5 years ago.
So I have myself an array like this one:
int masterNumber = randomNumber.Next(1, 7);
int childNumber;
int[] fieldArray = new int[] {masterNumber, childNumber = randomNumber.Next(1, 7)};
So now i'd like to write the master number to my console ONLY ONCE using Console.WriteLine(); and I'd like to write the random childNumber 99 times to the console, each childNumber with it's own value between 1 and 7. How would I do this?
Why you want to use fieldArray if you have "masterNumber" & "childNumber". But I think, you can do it in this way...
Random randomNumber = new Random();
int masterNumber = randomNumber.Next(1, 7);
int childNumber;
int[] fieldArray = new int[] { masterNumber, childNumber = randomNumber.Next(1, 7) };
Console.Write("Master Number " + masterNumber);
int i = 0;
while (i < 99)
{
Console.Write("Child Number " + childNumber);
Console.WriteLine(i);
i++;
}

Non duplicate random numbers in C# [duplicate]

This question already has answers here:
Random.Next returns always the same values [duplicate]
(4 answers)
Closed 9 years ago.
I am trying to create a range of non duplicate random numbers between 1 - 10, I planned on doing this by storing each random number I made in to an array and then checking that array every time to make sure I ain't already used the number.
My problem is that instead of creating different random numbers such as 1, 2, 3 I just keep getting the same random number over and over.
randomNumber();
Label1.Text = randomRow + "";
randomNumber();
Label2.Text = randomRow + "";
randomNumber();
Label3.Text = randomRow + "";
public int randomNumber()
{
List<int> numbers = new List<int>();
int num = 0;
Random randNum = new Random();
num = randNum.Next(1, 11);
if (numbers.Contains(num))
{
num = randNum.Next(1, 11);
}
else
{
randomRow = num;
numbers.Add(num);
}
return randomRow;
}
Problem : everytime you are creating the RandomNumber object in too close time.
When you create a Random object, it's seeded with a value from the system clock. If you create Random instances too close in time, they will all be seeded with the same random sequence.
From Here
When you create a Random object, it's seeded with a value from the
system clock. If you create Random instances too close in time, they
will all be seeded with the same random sequence.
Solution :
move Random randNum = new Random(); outside the function randomNumber().
Try This:
Random randNum = new Random();
public int randomNumber()
{
List<int> numbers = new List<int>();
int num = 0;
num = randNum.Next(1, 11);
if (numbers.Contains(num))
{
num = randNum.Next(1, 11);
}
else
{
randomRow = num;
numbers.Add(num);
}
return randomRow;
}
My best gues is that you are using this in a loop. In this case because you declare
Random randNum = new Random();
evry time this will generate tha same number. Just declare it BEFORE the loop and it should be fine.
Also you should consider a different approch because it is not a good practice. Like:
int[] array = {1,2,3,4,5,6,7,8,9,10};
Random randNum = new Random();
int rand=0;
int temp;
for(int i = 0; i<10;i++)
{
rand = randNum.next(1,10-i);
temp=array[rand];
array[rand]=array[9-i];
array[9-i]=temp;
}

filling a array with random numbers between 0-9 in c# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
filling a array with uniqe random numbers between 0-9 in c#
I have a array like "page[100]" and i want to fill it with random numbers between 0-9 in c#...
how i can do this?
i used :
IEnumerable<int> UniqueRandom(int minInclusive, int maxInclusive)
{
List<int> candidates = new List<int>();
for (int i = minInclusive; i <= maxInclusive; i++)
{
candidates.Add(i);
}
Random rnd = new Random();
while (candidates.Count > 1)
{
int index = rnd.Next(candidates.Count);
yield return candidates[index];
candidates.RemoveAt(index);
}
}
this way :
int[] page = UniqueRandom(0,9).Take(array size).ToArray();
but it just gave me 9 unique random numbers but i need more.
how i can have a array with random numbers that are not all the same?
How about
int[] page = new int[100];
Random rnd = new Random();
for (int i = 0; i < page.Length; ++i)
page[i] = rnd.Next(10);
Random r = new Random(); //add some seed
int[] randNums = new int[100]; //100 is just an example
for (int i = 0; i < randNums.Length; i++)
randNums[i] = r.Next(10);
You have an array of 100 numbers and draw from a pool of 10 different ones. How would you expect there to be no duplicates?
Don't overcomplicate the thing, just write what needs to be written. I.e.:
Create the array
Loop over the size of it
Put a random number between from [0, 9] in the array.

Categories