C# Generating a random number in while loop [duplicate] - c#

This question already has answers here:
How do I generate a random integer in C#?
(31 answers)
Closed 5 years ago.
I've tried everything from YouTube videos to this forum.
I used to find always a solution here but now I'm stuck.
I need to generate a random number between 39 and 52.
Here's the somewhat source:
case Form1.number.WITHRANDOM:
{
int i = 0;
while (i < ammount)
{
i++;
int j = 0;
string text2 = "";
while (j < 2)
{
string value = Conversions.ToString(this.random.Next(0, text.Length));
text2 += Conversions.ToString(text[Conversions.ToInteger(value)]);
j++;
}
this.numberList.Add("173" + (The random number) + text2);
}
break;
}

You should use the Random class. Its Next method returns a random integer within a specified range (between minValue and maxValue):
public virtual int Next(int minValue, int maxValue)
So, in your case, this is the code:
Random random = new Random();
int number = random.Next(39, 52);

Related

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++;
}

C# Code only works when using the debugger? [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 7 years ago.
So here's the code I've been using. Its just a simple program to test to see if 3 randomly generated numbers are in ascending or descending order. For some reason if I'm using the debugger and stepping into every line then the code works properly. If not then it says the numbers are in order 100% or out of order 100%, which should not be the case.
Here is the code I've been using:
int num1;
int num2;
int num3;
int yes = 0;
int no = 0;
for (int i = 0; i <= 99; i++)
{
Random rnd = new Random();
num1 = rnd.Next(1, 11);
num2 = rnd.Next(1, 11);
num3 = rnd.Next(1, 11);
if ( ((num1 <= num2) && (num2 <= num3)) || ((num1 >= num2) && (num2 >= num3)) )
{
yes += 1;
}
else
{
no += 1;
}
}
Console.WriteLine("The Number are in ascending order " + yes.ToString() + " Times");
Console.WriteLine("The Number are not in ascending order " + no.ToString() + " Times");
Console.ReadLine();
I think that it might be a problem with the pseudo random and the code generating the same 3 numbers every time, but I'm still learning more about programming and other help would be greatly appreciated.
The new Random() constructor uses the current time as the seed.
Unless you wait in the debugger, all of your Random instances have the same seed.
You should use a single instance.
This has to do with how the random numbers are generated.
If you take
Random rnd = new Random();
and move it out of the loop, you should see the desired results.
More background:
The random number generator uses a seed based on the time you instantiate it. Because your code is running so quickly, the seed is the same so the numbers are the same. This is why it works when you step through.
Instantiating the Random outside of the loop will instantiate it once and use the random algorithm to generate new numbers.

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;
}

C# - Writing numbers 1 through 10 in random order [duplicate]

This question already has answers here:
Is using Random and OrderBy a good shuffle algorithm? [closed]
(13 answers)
Closed 9 years ago.
Part 1: All I am wanting to achieve is to write the numbers 1, 2, 3 ... 8, 9, 10 to the console window in random order. So all the numbers will need to be written to console window, but the order of them must be random.
Part 2: In my actual project I plan to write all of the elements in an array, to the console window in random order. I am assuming that if I can get the answer to part 1, I should easily be able to implement this with an array.
/// <summary>
/// Returns all numbers, between min and max inclusive, once in a random sequence.
/// </summary>
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 > 0)
{
int index = rnd.Next(candidates.Count);
yield return candidates[index];
candidates.RemoveAt(index);
}
}
In your program
Console.WriteLine("All numbers between 0 and 10 in random order:");
foreach (int i in UniqueRandom(0, 10)) {
Console.WriteLine(i);
}
Enumerable.Range(1, 10).OrderBy(i => Guid.NewGuid()) works nicely.
using System;
using System.Collections;
namespace ConsoleApplication
{
class Numbers
{
public ArrayList RandomNumbers(int max)
{
// Create an ArrayList object that will hold the numbers
ArrayList lstNumbers = new ArrayList();
// The Random class will be used to generate numbers
Random rndNumber = new Random();
// Generate a random number between 1 and the Max
int number = rndNumber.Next(1, max + 1);
// Add this first random number to the list
lstNumbers.Add(number);
// Set a count of numbers to 0 to start
int count = 0;
do // Repeatedly...
{
// ... generate a random number between 1 and the Max
number = rndNumber.Next(1, max + 1);
// If the newly generated number in not yet in the list...
if (!lstNumbers.Contains(number))
{
// ... add it
lstNumbers.Add(number);
}
// Increase the count
count++;
} while (count <= 10 * max); // Do that again
// Once the list is built, return it
return lstNumbers;
}
}
Main
class Program
{
static int Main()
{
Numbers nbs = new Numbers();
const int Total = 10;
ArrayList lstNumbers = nbs.RandomNumbers(Total);
for (int i = 0; i < lstNumbers.Count; i++)
Console.WriteLine("{0}", lstNumbers[i].ToString());
return 0;
}
}
}
int[] ints = new int[11];
Random rand = new Random();
Random is a class built into .NET, and allows us to create random integers really, really easily. Basically all we have to do is call a method inside our rand object to get that random number, which is nice. So, inside our loop, we just set each element to the results of that method:
for (int i = 0; i < ints.Length; i++)
{
ints[i] = rand.Next(11);
}
We are essentially filling our entire array with random numbers here, all between 0 and 10. At this point all we have to do is display the contents for the user, which can be done with a foreach loop:
foreach (int i in ints)
{
Console.WriteLine(i.ToString());
}

Categories