I am playin around with generating random numbers, and I can get them to generate, although my console.writeline(randomList[i]); seems to loop twice and then displays both results, it should only display one value per loop, and the user should have to hit any-key to get the next result. Can someone give a little insight on this? Thanks.
class Program
{
static void Main(string[] args)
{
GenerateRandomNumbers();
}
private static void GenerateRandomNumbers()
{
//Initialize an array
int[] randomList = new int[1000];
//Initialize an instance of random class
Random rnd = new Random();
// integer variable
int counter = 0;
while (counter < 1000)
{
//store random num
int random = rnd.Next(1, 1001);
if (Array.IndexOf(randomList, random) <= 0)
{
//store random number into Array
randomList[counter] = random;
counter++;
}
}
//output elements in Array
for (int i = 0; i < 1000; i++)
{
Console.WriteLine(randomList[i]);
Console.Read();
}
//output number of elements in Array
// Console.WriteLine(counter);
Console.Read();
}
The solution is to use the Console.ReadLine() in the loop instead of the Console.Read()
Related
This question already has answers here:
Random number generator with no duplicates
(12 answers)
Closed 2 years ago.
We are making our first 2D mobile game in Unity and we need some help. We coded on Java but is also our first time coding C#.
We are making a card game and we want to give to every player a random number, but (here's the important and difficult part for us) we want each random number not to repeat.
For example if we have 5 players and we want to assign a random number from 5 to 10, if number 6 is assigned to player 1 then number 6 cant be assigned to other player.
Here's where we are:
//Player class only have string name and int trabajo
public static void assignRandom(Player jug)
{
int randomnum;
bool aleatorio;
do
{
randomnum= Random.Range(1, 5);
aleatorio = comprobarAleatorio(randomnum);
}
while (aleatorio);
jug.setTrabajo(randomnum);
}
public static bool comprobarAleatorio(int numaleatorio)
{
bool exists = false;
int longitud = jugadoresList.Count;
for (int i = 0; i < 5; i++)
{
if (jugadoresList[i].getTrabajo().Equals(numaleatorio))
{
exists = true;
}
}
}
Then with the int we make a switch and show on screen what type of player you are. But clearly we are doing something wrong because the numbers repeat itselfs, even with 0 (we dont know how).
We appreciate every help. Thank you very much! (and sorry for our english)
One solution is you can generate a list that contains valid numbers and then shuffle them.
Code to shuffle a list from here:
// A Function to generate a
// random permutation of arr[]
static void randomize(int []arr, int n)
{
// Creating a object
// for Random class
Random r = new Random();
// Start from the last element and
// swap one by one. We don't need to
// run for the first element
// that's why i > 0
for (int i = n - 1; i > 0; i--)
{
// Pick a random index
// from 0 to i
int j = r.Next(0, i+1);
// Swap arr[i] with the
// element at random index
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Prints the random array
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
Check the code below :
public static void assignRandom(Player jug) //Player class only have string name and int trabajo
{
int randomnum;
private Random random = new Random(); //Declared an instance of Random
ArrayList randomNumsList = new ArrayList(); //Create arraylist to add random nums
bool aleatorio;
do
{
randomnum= random.next(1, 5); //Changed Random.ranged to random.next();
randomNumsList.add(randomnum); //add the random num to list
aleatorio = comprobarAleatorio(randomnum);
}
while (aleatorio);
if (!randomNumsList.Contains(randomnum) { //Only call setTrabajo if the randomNumsList don't have currently generated randomnum
jug.setTrabajo(randomnum);
}
}
public static bool comprobarAleatorio(int numaleatorio)
{
bool exists = false;
int longitud = jugadoresList.Count;
for (int i = 0; i < 5; i++)
{
if (jugadoresList[i].getTrabajo().Equals(numaleatorio))
{
exists = true;
}
}
return exists;
}
}
Tell me if it helps or if it does not help.
I'm very new to coding and I just can't wrap my head around Loops/Arrays/Randoms. I understand the concept but when it comes to applying it, I'm just lost.
Here I'm trying to generate 100 random numbers between 1-1000 and it has to output the maximum value. Here's my code so far:
Random rnd = new Random();
int nums = rnd.Next(0, 1001);
for (int i = 1; i <= 100; i++)
{
}
Console.WriteLine(nums);
Console.ReadLine();
It's only giving me one number. :(
I'd greatly appreciate any help!
Thanks!
You can accumulate your random generated number to the array and then by using Max function of the array you can find the maximum value
class Program
{
public static void Main(string[] args)
{
Random rnd = new Random();
int[] intArr = new int[100];
for (int i = 0; i < intArr.Length; i++)
{
int num = rnd.Next(1, 1000);
intArr[i] = num;
Console.WriteLine(num);
}
Console.WriteLine();
int maxNum = intArr.Max();
Console.WriteLine("The max num is:" + maxNum);
Console.ReadLine();
}
}
Click to watch online demo
You need to call rnd.Next() inside loop.
Random rnd = new Random();
for (int i = 1; i <= 100; i++)
{
int nums = rnd.Next(0, 1001);
Console.WriteLine(nums);
}
Console.ReadLine();
A good approach would be initializing a variable that stores your max. Then generate a random number within your iterative block and if it is greater than your max, set it as the new max.
Random r = new Random();
int max = 0; //declare our max variable
for(int i = 0; i < 100; i++)
{
int rand = r.Next(0, 1001);
if(rand > max) //if the new random value is greater than our max, set max = rand
max = rand;
}
Console.WriteLine(max); //Output the maximum value
Console.ReadLine();
If you want to output every random value and then output the max out of all the values generated, simply modify the code above by outputting rand within your loop as well.
Hope this helps!
I am not sure, are you asking like this?
Random random = new Random();
int[] nums = new int[100];
// when for loop ends, nums are full of 100 numbers
for (int i = 0; i < nums.Length; i++)
{
int newNum = random.Next(1, 1000);
// show every number
Console.WriteLine(newNum);
nums[i] = newNum;
}
// get the max number
var maxNum = nums.Max();
Console.WriteLine(maxNum);
If you want to see the code for Loops/Arrays/Randoms all working together you can use the below with the comments walking through what each line is doing (Working .NET Fiddle Example)
public static void Main()
{
// Pass in what range we want our randomly generated numbers to be in
// In your case, between 1 - 1000 and we want to create 100 of them.
//(See GenerateRandomNumbers())
var random = GenerateRandomNumbers(1, 1000, 100);
//Take our newly returned randomly created numbers and
//pass them to our GetMaxNumber method so it can find the Max number
//See (GetMaxNumber())
var result = GetMaxNumber(random);
//We now have our max number; print it to the Console.
Console.WriteLine("Max: " + result);
}
public static int GetMaxNumber(params int[] inputs)
{
//Create a variable that will store the largest number we find in our array
int max = inputs[0];
//Iterate (loop) through all of the 100 values in our array that we passed in
//Here we define "input" which will hold the value for each value in inputs as we check
//if the value of input is greater than our current value of max. If it is greater than our
//current value of max, then we need to update max to now be equal to the value of our input.
//Note: it will do this comparison 100 times beginning with the first value in the inputs array
foreach (var input in inputs)
{
if (input > max)
{
//input's value is greater than the current value of max; update max so that it is equal to the current value of input.
max = input;
}
//no more code; return to top of foreach loop and set input to the next value in inputs
}
//When we get here, it means our foreach loop has completed going through and comparing all 100 values of inputs to see which value is the largest.
//now return this value to Main()
return max;
}
public static int[] GenerateRandomNumbers(int beginRange, int endRange, int maxNumbers)
{
// Instantiate random number generator
Random rnd = new Random();
//Generate and display
int[] intArr = new int[maxNumbers];
//Generate 100 numbers with numbers between 1 and 1000
for (int i = 0; i < intArr.Length; i++)
{
int num = rnd.Next(beginRange, endRange);
intArr[i] = num;
}
return intArr;
}
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int[] mass = new int[10];
for (int i = 0; i < mass.Length; i++)
{
mass[i] = rnd.Next(0, 10);
}
Console.WriteLine("display random Massive: \n");
foreach (var i in mass)
{
Console.Write("{0} ", i);
}
Console.WriteLine("\n");
int max = mass.Max();
Console.WriteLine("max value in Massive = {0}", max);
Console.ReadLine();
}
}
my code gives me max value in massive, I need get max odd value. How to get max odd value?
You can use Linq to do this easily
mass.Where (x => x % 2 != 0).Max ();
You can do this easier using linq:
static void Main(string[] args)
{
Random rnd = new Random();
int[] mass = Enumerable.Range(0, 10).Select(i => rnd.Next(0, 10)).ToArray();
Console.WriteLine("display random Massive: ");
Console.WriteLine(string.Join(" ", mass));
Console.WriteLine();
int max = mass.Where(i => (i & 1) == 1).Max();
Console.WriteLine("max value in Massive = {0}", max);
Console.ReadLine();
}
Explanations:
I initialize the array by generating 10 random numbers, converting them to an array
I output them using string.Join
using Where with testing that the last bit is set filters for odd numbers
calling Max on only these odd numbers.
Note that you don't need to use \n as Console.WriteLine adds a new line at the end.
just change
int max = mass.Max();
to
int max = mass.Where(x=>(x%2)==1).Max();
I am asuming you're a beginner like me and don't understand linq yet
Declare a list for holding odd values
List<int> oddList = new List<int>();
Then in your foreach method
foreach (var i in mass)
{
if (i % 2 != 0) //check that number is odd
{
oddList.Add(i); //add odd randoms to list
{
}
Console. WriteLine(oddList.Max().ToString());
i m facing a problem in dice simulator in c#.The function RandomGenerator generates a pair of dice until the sum of these two becomes equal to the given number(from 2 to 12) in parameter.A count variable holds the number of times the pair of dice is rolled.The problem is that when i enter an even number it correctly returns the count.But when i enter an odd number it does nothing,not even gives an error,the dash goes on blinking and blinking.The code is given below.Can anyone help me??
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static int RandomGenerator(int n)
{
Random rand1 = new Random();
Random rand2 = new Random();
int sum = rand1.Next(1,7) + rand2.Next(1,7);
int count = 1;
{
sum = rand1.Next(1,7) + rand2.Next(1,7);
count++;
}
return count;
}
static void Main(string[] args)
{
Console.WriteLine("Hello! this program a pair of dice until total on dice is equal to your given number.\n\n");
Console.WriteLine("Enter the number :");
int num = int.Parse(Console.ReadLine());
int rolls = RandomGenerator(num);
Console.WriteLine("The number of rolls are:" + rolls);
}
}
}
The problem is that you're using two Random instances. By default they're initialized with Environment.TickCount seed, which has precision about 15 milliseconds. This means that it's pretty much guaranteed that your instances of class Random get identical seed and hence generate identical values on every call to Next. The sum of two identical numbers is always even.
A proper solution would be to use a single instance of Random for both dice.
Suggested solution from me:
public static int RandomGenerator(int n)
{
Random random = new Random();
int sum = 0;
int count = 0;
do
{
sum = random.Next(1, 7) + random.Next(1, 7);
count++;
} while (sum != n);
return count;
}
Victor Efimov is right about the Random instance and I faced a similar issue once with the random generator for generating color :)
I also suggest you to perform sanity check on the user's input to make sure the values entered are always between 2 and 12. This is to avoid being caught in do-while loop when the condition sum != n will never come true.
Aren't you missing a while or for-loop?
I think you should have something like the code below in your RandomGenerator method:
static int RandomGenerator(int n)
{
Random rand1 = new Random();
int sum = rand1.Next(1,7) + rand1.Next(1,7);
int count = 1;
//while the sum variable isn't equal to your provided number, roll the dices again
while(sum != n)
{
sum = rand1.Next(1,7) + rand1.Next(1,7);
count++;
}
return count;
}
System.Random generator = new Random(DateTime.Now.Millisecond);
int[] lotteryNumber = new int[7];
Console.WriteLine("Your lottery numbers: ");
for (int i = 0; i<7; i++)
{
lotteryNumber[i] = generator.Next(1, 37);
Console.Write("{0} ",lotteryNumber[i]);
}
Console.ReadLine();
I need to make a program that prints 7 lottery numbers, but without duplicates. The code above prints 7 random numbers in the range of (1-37), but duplicates appaer. I need a way to prevent duplicate numbers from appearing.
The simplest approach IMO would be to generate a sequence of all the possible numbers (i.e. 1-37), shuffle the collection, then take the first seven results.
Searching on Stack Overflow for "Fisher-Yates shuffle C#" will find lots of examples.
In fact, you could modify the Fisher-Yates shuffle to yield results as you took them, so you could write a method such as:
var numbers = Enumerable.Range(1, 37).Shuffle().Take(7).ToList();
You could take a dictionary but make sure that you prevent duplicate key insertion. Keys of dictionary would serve as the unique numbers you need
You could toss them into a HashSet<int>. If you Add and it returns false, generate a new number.
If you're trying to pick numbers from a range without repetitions, you need to create an array of all the possible numbers and then "shuffle" a random selection out:
int[] allPossibleNumbers = Enumerable.Range(1, 37).ToArray();
int[] lotteryNumber = new int[7];
for (int i = 0; i < 7; i++)
{
int index = r.Next(i, 37);
lotteryNumber[i] = allPossibleNumbers[index];
allPossibleNumbers[index] = allPossibleNumbers[i];
// This step not necessary, but allows you to reuse allPossibleNumbers
// rather than generating a fresh one every time.
// allPossibleNumbers[i] = lotteryNumber[i];
}
Generate a list with your 37 items.
Then in your for, select one and delete the selected
Maybe this could help, if you get the existing number just try to find new one that isn't in the array:
static void Main(string[] args)
{
System.Random generator = new Random(DateTime.Now.Millisecond); int[] lotteryNumber = new int[7];
Console.WriteLine("Your lottery numbers: ");
for (int i = 0; i < 7; i++)
{
int lNumber = 0;
do
{
lNumber = generator.Next(1, 37);
}
while (lotteryNumber.Contains(lNumber));
lotteryNumber[i] = lNumber;
Console.Write("{0} ", lotteryNumber[i]);
}
Console.ReadLine();
}
HashSet<int> set = new HashSet<int>();
System.Random generator = new Random(DateTime.Now.Millisecond);
while(set.Count < 7){
set.Add(generator.Next(1,37);
}
That should work, since a HashSet will automatically ignore duplicates. Just loop until the set reaches the number of units you need. Only potential problem is it has the POTENTIAL (unlikely) to loop for a long time, but it should eventually respond.
so I took your original code...found some logic errors and added the fix you were looking for to prevent random number duplicates.
Enjoy!
System.Random generator = new Random(DateTime.Now.Millisecond);
int[] lotteryNumber = new int[7];
int lowerBounds = 1;
int upperBounds = 8;
int maxNumberLotteryValues = 7;
if ( ( upperBounds - lowerBounds ) < (maxNumberLotteryValues))
{
Console.Write("Warning: Adjust your upper and lower bounds...there are not enough values to create a unique set of Lottery numbers! ");
}
else
{
Console.WriteLine("Your lottery numbers: ");
for (int i = 0; i < maxNumberLotteryValues; i++)
{
int nextNumber = generator.Next(lowerBounds, upperBounds);
int count = lowerBounds; //Prevent infinite loop
while ((lotteryNumber.Contains(nextNumber))
&& (count <= upperBounds))
{
nextNumber = generator.Next(lowerBounds, upperBounds);
count++; //Prevent infinite loop
}
lotteryNumber[i] = nextNumber;
Console.Write("{0} ", lotteryNumber[i]);
}
}
Console.ReadLine();
const int nBalls = 37;
const int nPicks = 6;
int[] balls = new int[nPicks];
Random rnd = new Random(DateTime.Now.Millisecond);
int remainingBalls=nBalls;
int remainingPicks=nPicks;
for (int i = 1; i <= nBalls; i++)
{
if (rnd.Next(1, remainingBalls+1) <= remainingPicks)
balls[--remainingPicks]=i;
remainingBalls--;
}
Console.WriteLine(string.Join(",",balls));
Will outperform Shuffle and HashSet methods as nPicks/nBalls gets larger.