Random double between given numbers - c#

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

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

Generate 10 digit random number in c# with random.Next [duplicate]

I'm using C# and I need to generate a random 10 digit number. So far, I've only had luck finding examples indicating min maximum value. How would i go about generating a random number that is 10 digits, which can begin with 0, (initially, I was hoping for random.Next(1000000000,9999999999) but I doubt this is what I want).
My code looks like this right now:
[WebMethod]
public string GenerateNumber()
{
Random random = new Random();
return random.Next(?);
}
**Update ended up doing like so,
[WebMethod]
public string GenerateNumber()
{
Random random = new Random();
string r = "";
int i;
for (i = 1; i < 11; i++)
{
r += random.Next(0, 9).ToString();
}
return r;
}
Use this to create random digits with any specified length
public string RandomDigits(int length)
{
var random = new Random();
string s = string.Empty;
for (int i = 0; i < length; i++)
s = String.Concat(s, random.Next(10).ToString());
return s;
}
try (though not absolutely exact)
Random R = new Random();
return ((long)R.Next (0, 100000 ) * (long)R.Next (0, 100000 )).ToString ().PadLeft (10, '0');
To get the any digit number without any loop, use Random.Next with the appropriate limits [100...00, 9999...99].
private static readonly Random _rdm = new Random();
private string PinGenerator(int digits)
{
if (digits <= 1) return "";
var _min = (int)Math.Pow(10, digits - 1);
var _max = (int)Math.Pow(10, digits) - 1;
return _rdm.Next(_min, _max).ToString();
}
This function calculated the lower and the upper bounds of the nth digits number.
To generate the 10 digit number use it like this:
PinGenerator(10)
If you want ten digits but you allow beginning with a 0 then it sounds like you want to generate a string, not a long integer.
Generate a 10-character string in which each character is randomly selected from '0'..'9'.
private void button1_Click(object sender, EventArgs e)
{
Random rand = new Random();
long randnum2 = (long)(rand.NextDouble() * 9000000000) + 1000000000;
MessageBox.Show(randnum2.ToString());
}
I came up with this method because I dont want to use the Random method :
public static string generate_Digits(int length)
{
var rndDigits = new System.Text.StringBuilder().Insert(0, "0123456789", length).ToString().ToCharArray();
return string.Join("", rndDigits.OrderBy(o => Guid.NewGuid()).Take(length));
}
hope this helps.
// ten digits
public string CreateRandomNumber
{
get
{
//returns 10 digit random number (Ticks returns 16 digit unique number, substring it to 10)
return DateTime.UtcNow.Ticks.ToString().Substring(8);
}
}
(1000000000,9999999999) is not random - you're mandating that it cannot begin with a 1, so you've already cut your target base by 10%.
Random is a double, so if you want a integer, multiply it by 1,000,000,000, then drop the figures after the decimal place.
private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden
public long LongBetween(long maxValue, long minValue)
{
return (long)Math.Round(random.NextDouble() * (maxValue - minValue - 1)) + minValue;
}
I tried to write a fast one:
private int GetNDigitsRandomNumber(int digits)
{
var min = 1;
for (int i = 0; i < digits-1; i++)
{
min *= 10;
}
var max = min * 10;
return _rnd.Next(min, max);
}
Here is a simple solution using format string:
string r = $"{random.Next(100000):00000}{random.Next(100000):00000}";
Random 10 digit number (with possible leading zeros) is produced as union of two random 5 digit numbers. Format string "00000" means leading zeros will be appended if number is shorter than 5 digits (e.g. 1 will be formatted as "00001").
For more about the "0" custom format specifier please see the documentation.
Random random = new Random();
string randomNumber = string.Join(string.Empty, Enumerable.Range(0, 10).Select(number => random.Next(0, 9).ToString()));
To generate a random 10 digit number in C#
Random RndNum = new Random();
int RnNum = RndNum.Next(1000000000,9999999999);

How to make c# Random Numbers repeat

I'm trying to generate random arrays to test my homework assignments.
The Problem is that the numbers generated are always unique , and I need some repeating numbers from time to time.
Here is the code I came up with:
static int[] RandomIntArray()
{
Random rnd = new Random();
Console.Write("Enter array Length: ");
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = rnd.Next(short.MinValue, short.MaxValue);
}
return arr;
}
You can seed a random number generator, so it will always produce the same random sequence:
Random rnd = new Random(1/* Any seed value you want in here */);
If you want to force some repeating numbers, you could so something like this:
static int[] RandomIntArray()
{
Random rnd = new Random();
Console.Write("Enter array Length: ");
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
for (int i = 0; i < arr.Length; i++)
{
if(i > 0 && rnd.Next(10) == 1) // a 1 in 10 chance of a dupe
{
arr[i] = arr[i-1];
}
else
arr[i] = rnd.Next(short.MinValue, short.MaxValue);
}
return arr;
}
If you want numbers to repeat once in a while, make the range smaller. They'll be more likely to result in duplicates.
arr[i] = rnd.Next(0, 10);
How often you want repeated numbers will dictate what approach you use. You could always round the random numbers you get to the nearest 10, 100, whatever until the "bins" are big enough that the "bins" show up as often as you want. This is similar to making the range smaller as suggested by #DLeh, but it allows you to spread the generated numbers over a larger range.
If you initialized random with same seed, you will get same sequence of numbers all the time
Random rnd1 = new Random(5);
Random rnd2 = new Random(5);
for(var i=0;i<10; i++){
Console.WriteLine(rnd1.Next() + ", " + rnd2.Next());
}

Avoiding random duplicates

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.

Categories

Resources