Dice Simulator int c# - c#

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

Related

C# Why get a zero number in random number

I'm trying to create an array list using random numbers. But sometimes I get a zero in results. I do not understand why.
I'm grateful if anyone can explain.
int[] number = new int[6];
Random rnd = new Random();
for (int i = 0; i < number.Length; i++)
{
int random = rnd.Next(1, 26);
if (!number.Contains(random))
{
number[i] = random;
}
}
foreach (int nr in number)
{
Console.Write("|" + nr + "|");
}
//results
|6||12||0||22||25||11|
int[] number = new int[6];
Here number array is created with default int value i.e 0
The issue with your code is in some cases this value is not getting updated due to the check
if (!number.Contains(random))
You can change your code to include a loop to guarantee your random number doesn't lie in the array.
int[] number = new int[6];
Random rnd = new Random();
for (int i = 0; i < number.Length; i++)
{
int random = rnd.Next(1, 26);
while (number.Contains(random))
{
random = rnd.Next(1, 26);
}
number[i] = random;
}
foreach (int nr in number)
{
Console.Write("|" + nr + "|");
}
Please note that current approach is quite performance hungry as for every new random value we are iterating through entire array everytime to check if it exists. You can reduce the performance by using as HashSet<int> if possible
When you declare the array in following statement it initializes with 6 integers as 0
int[] number = new int[6];
While the random number generated for each array element, check for duplication in following statement may have resulted false
if (!number.Contains(random))
That's why it was never updated to new assigned number.
You can add else condition to it and regenerate random number
Just use your debugger to step through your code and inspect your variables to see what's happening. Apart from all the suggestions here, which are bad because they can loop way too many times or even forever, you appear to want to get 6 random, unique numbers between 1 and 26.
The de facto way to do that, is to generate a list with those numbers (Enumerable.Range()), shuffle them (Fisher-Yates) and Take() the first six.
Use while loop.
int[] number = new int[6];
Random rnd = new Random();
int i = 0;
while (i < number.Length)
{
int random = rnd.Next(1, 26);
if (!number.Contains(random))
{
number[i] = random;
i++;
}
}
foreach (int nr in number)
{
Console.Write("|" + nr + "|");
}

C#: Generate 100 random numbers between 1-1000 and output the max value

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

Random function refresh [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 7 years ago.
Console.WriteLine("How many times would you like to roll?");
string count = Console.ReadLine();
int cnt = Convert.ToInt32(count);
for (int i = 1; i <= cnt; i++)
{
int rol = new int();
Random roll = new Random();
rol = roll.Next(1, 6);
Console.WriteLine("Die {0} landed on {1}.", i, rol);
}
Console.ReadLine();
I am trying to create a dice-rolling simulator in C#, but I'm encountering one problem: The random number never changes after the first roll. What is happening and how can I fix it?
As Alex pointed you need to move it out of the for loop. Also use 1,7 instead of 1,6 that way you will get results from 1 to 6.
Console.WriteLine("How many times would you like to roll?");
string count = Console.ReadLine();
int cnt = Convert.ToInt32(count);
Random roll = new Random();
for (int i = 1; i <= cnt; i++) {
int rol = new int();
rol = roll.Next(1, 7);
Console.WriteLine("Die {0} landed on {1}.", i, rol);
}
Console.ReadLine();
Random creates pseudo-random numbers one by one. This sequence of random numbers is controlled by the seed number. Two sequences of random numbers will be identical if their seeds are identical. The numbers within the sequence are random: in a sense that you can't predict the next number in the sequence.
In case of Random, where does the seed come from? It depends on which constructor was used. Random() creates a default seed. Random(Int32) uses the seed passed by the calling code.
The code in the O.P. creates a new random number generator object in every iteration of the loop. Every time, the seed is the same default. Every time, the first number in the sequence of pseudo-random numbers is the same.
So, create one Random outside of the loop and use the same Random for every iteration of the loop.
Console.WriteLine("How many times would you like to roll?");
string strCount = Console.ReadLine();
int n = Convert.ToInt32(strCount);
Random die = new Random();
for (int i = 1; i <= n; i++)
{
int roll = die.Next(1, 6);
Console.WriteLine("Die {0} landed on {1}.", i, roll);
}
Console.ReadLine();

Random double between given numbers

I'm looking for some succinct, modern C# code to generate a random double number between 1.41421 and 3.14159. where the number should be [0-9]{1}.[0-9]{5} format.
I'm thinking some solution that utilizes Enumerable.Range somehow may make this more succinct.
You can easily define a method that returns a random number between two values:
private static readonly Random random = new Random();
private static double RandomNumberBetween(double minValue, double maxValue)
{
var next = random.NextDouble();
return minValue + (next * (maxValue - minValue));
}
You can then call this method with your desired values:
RandomNumberBetween(1.41421, 3.14159)
Use something like this.
Random random = new Random()
int r = random.Next(141421, 314160); //+1 as end is excluded.
Double result = (Double)r / 100000.00;
Random r = new Random();
var number = r.Next(141421, 314160) / 100000M;
Also you can't force decimal number to match your pattern. E.g. if you have 1.5 number it will not match 1.50000 format. So, you should format result as string:
string formattedNumber = number.ToString("0.00000");
I used this. I hope this helps.
Random Rnd = new Random();
double RndNum = (double)(Rnd.Next(Convert.ToInt32(LatRandMin.Value), Convert.ToInt32(LatRandMax.Value)))/1000000;
Check out the following link for ready-made implementations that should help:
MathNet.Numerics, Random Numbers and Probability Distributions
The extensive distributions are especially of interest, built on top of the Random Number Generators (MersenneTwister, etc.) directly derived from System.Random, all providing handy extension methods (e.g. NextFullRangeInt32, NextFullRangeInt64, NextDecimal, etc.). You can, of course, just use the default SystemRandomSource, which is simply System.Random embellished with the extension methods.
Oh, and you can create your RNG instances as thread safe if you need it.
Very handy indeed!
here my solution, it's not pretty but it works well
Random rnd = new Random();
double num = Convert.ToDouble(rnd.Next(1, 15) + "." + rnd.Next(1, 100));
Console.WriteLine(num);
Console.ReadKey();
JMH BJHBJHHJJ const int SIZE = 1;
int nnOfTosses,
headCount = 0, tailCount = 0;
Random tossResult = new Random();
do
{
Console.Write("Enter integer number (>=2) coin tosses or 0 to Exit: ");
if (!int.TryParse(Console.ReadLine(), out nnOfTosses))
{
Console.Write("Invalid input");
}
else
{
//***//////////////////
// To assign a random number to each element
const int ROWS = 3;
double[] scores = new double[ROWS];
Random rn = new Random();
// Populate 2D array with random values
for (int row = 0; row < ROWS; row++)
{
scores[row] = rn.NextDouble();
}
//***//////////////////////////
for (int i = 0; i < nnOfTosses; i++)
{
double[] tossResult = new double[i];
tossResult[i]= tossResult.nextDouble();
}
Console.Write("Number of Coin Tosses = " + nnOfTosses);
Console.Write("Fraction of Heads = ");
Console.Write("Fraction of Tails = ");
Console.Write("Longest run is ");
}
} while (nnOfTosses != 0);
Console.ReadLine();

Random Number Displays 2 numbers when it should only display one

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()

Categories

Resources