How can i generate different random numbers in short time?
For example:
Number = 20;
if (Number > 0)
{
AddEffect(rand.Next(0,100);
Number--;
}
In this example, rand.Next gives me twenty times the same number. Is there any way to force a change?
I think you're trying to say:
var rand = new Random();
var Number = 20;
while (Number > 0)
{
// rand.Next(0,100); // this will give 20 different numbers btw
AddEffect(rand.Next(0,100));
Number--;
}
but otherwise, seems fine
int totalNumbers = 20;
Random rand = new Random();
for (int i = 0; i < totalNumbers; i++)
{
AddEffect(rand.Next(0, 101)); // a number between -1 and 101, min: 0, max: 100
}
Is this what you mean? This is an easy and clear way to generate some random numbers.
More info here: http://www.dotnetperls.com/for
Related
My code is supposed to generate random and non-repeating numbers, but when I print it it doesn't do it properly and sometimes it repeats itself. How can I fix?
Console.WriteLine("choose how many digits your password should be\nminimum 5 maximum 10 digits");
Console.Write("number of digits:");
int digit = int.Parse(Console.ReadLine());
int[] passwordarray = new int[digit];
Random r = new Random();
for (int i = 0; i < passwordarray.Length; i++)
{
if (digit <= 10 && digit >= 5)
{
do
{
passwordarray[i] = r.Next(0, 10);
} while (!(passwordarray.Contains(passwordarray[i])));
}
else
{
Console.WriteLine("your number of digits is less than 5 or more than 10");
}
}
I restructured your code:
Console.WriteLine("choose how many digits your password should be\nminimum 5 maximum 10 digits");
Console.Write("number of digits:");
int digit = int.Parse(Console.ReadLine());
int[] passwordarray = new int[digit];
Random r = new Random();
// check the digits first
if (digit <= 10 && digit >= 5)
{
int tempVal;
for (int i = 0; i < passwordarray.Length; i++)
{
// generate values until you have a value thats not in the array
do
{
tempVal = r.Next(0, 10);
} while (passwordarray.Contains(tempVal));
// add the value
passwordarray[i] = tempVal;
}
}
Basically you want to check first if the digits are between 5 and 10, then iterate trough your array, generate random values until you have one that isn't in the password array yet, and add this value. I just restructured your code, I didn't run it.
EDIT: obviously there are better solutions to implement this behavior, like Dmitrys answer, I restructured the code just to show you where your logic is wrong
I have a situation in which I must generate a random number, this number must be either zero or one
So, the code is something like this:
randomNumber = new Random().Next(0,1)
However, the business requirements state that there is just 10% probability that the generated number is zero and 90% probability that the generated number is 1
However can I include that probability in generating the random number please?
What I thought of is:
Generate array of integer that includes 10 zeros and 90 ones.
Generate a random index between 1 and 100
Take the value that corresponds to that index
But I don't know if this way is the correct way, plus, I think that C# should have something ready for it
You can implement it like that:
// Do not re-create Random! Create it once only
// The simplest implementation - not thread-save
private static Random s_Generator = new Random();
...
// you can easiliy update the margin if you want, say, 91.234%
const double margin = 90.0 / 100.0;
int result = s_Generator.NextDouble() <= margin ? 1 : 0;
to get true with a probability of 10%:
bool result = new Random().Next(1, 11) % 10 == 0;
to get true with a probability of 40%:
bool result = new Random().Next(1, 11) > 6;
First of all, you should save the reference to the random instance in order to get a proper random sequence of numbers:
Random randGen = new Random();
The second thing to know, is that the max of the random is exclusive, so to properly solve the issue you should do:
int eitherOneOrZero = randGen.Next(1, 11) % 10;
To generalize it to any variation of chances, you can do:
Random randGen = new Random();
var trueChance = 60;
int x = randGen.Next(0, 100) < trueChance ? 1 : 0;
Testing:
Random randGen = new Random();
var trueChance = 60;
var totalCount = 1000;
var trueCount = 0;
var falseCount = 0;
for (int i = 0; i < totalCount; i++)
{
int x = randGen.Next(0, 100) < trueChance ? 1 : 0;
if (x == 1)
{
trueCount++;
}
else
{
falseCount++;
}
}
Output:
True: 60.30 %
False: 39.70 %
Hi guy i try to generate 50 number with 5 digit depend on user total summary. For example, User give 500000 and then i need to random number with 5 digit by 50 number equal 500000
i try this but it isn't 5 digit number
int balane = 500000;
int nums = 50;
int max = balane / nums;
Random rand = new Random();
int newNum = 0;
int[] ar = new int[nums];
for (int i = 0; i < nums - 1; i++)
{
newNum = rand.Next(0, max);
ar[i] = newNum;
balane -= newNum;
max = balane / (nums - i - 1);
ar[nums - 1] = balane;
}
int check = 0;
foreach (int x in ar)
{
check += x;
}
i tried already but value inside my array have negative value i want to get only
positive value
Please help me, how to solve this and thank for advance.
I once asked a similar question on codereview.stackexchange.com. I have modified my answer to produce a five digit sequence for you.
Furthermore, this code is fast enough to be used to create tens of thousands of codes in a single request. If you look at the initial question and answer (linked to below) you will find that it checks to see whether the code has been used or not prior to inserting it. Thus, the codes are unique.
void Main()
{
Console.WriteLine(GenerateCode(CodeLength));
}
private const int CodeLength = 10;
// since Random does not make any guarantees of thread-safety, use different Random instances per thread
private static readonly ThreadLocal<Random> _random = new ThreadLocal<Random>(() => new Random());
// Define other methods and classes here
private static string GenerateCode(int numberOfCharsToGenerate)
{
char[] chars = "0123456789".ToCharArray();
var sb = new StringBuilder();
for (int i = 0; i < numberOfCharsToGenerate; i++)
{
int num = _random.Value.Next(0, chars.Length);
sb.Append(chars[num]);
}
return sb.ToString();
}
Original question and answer: https://codereview.stackexchange.com/questions/142049/creating-a-random-code-and-saving-if-it-does-not-exist/142056#142056
Perhaps try this:
var rnd = new Random();
var numbers = Enumerable.Range(0, 50).Select(x => rnd.Next(500_000)).OrderBy(x => x).ToArray();
numbers = numbers.Skip(1).Zip(numbers, (x1, x0) => x1 - x0).ToArray();
numbers = numbers.Append(500_000 - numbers.Sum()).ToArray();
Console.WriteLine(numbers.Count());
Console.WriteLine(numbers.Sum());
This outputs:
50
500000
This works by generating 50 random numbers between 0 and 499,999 inclusively. It then sorts them ascendingly and then gets the difference between each successive pair. This by definition produces a set of 49 values that almost adds up to 500,000. It's then just a matter of adding the one missing number by doing 500_000 - numbers.Sum().
i'm trying to get X number of random number (where X is a variable) between 0 and 100 and add them to a row in a DataGridView. I'm using the code below, but the problem is i need it to be impossible to have the same number twice. Is there a way make sure i get unique random numbers?
int X = 20;
Random random = new Random();
int randomrow = random.Next(0, 100);
for (int i = 0; i < X; i++)
{
int randomNumber = random.Next(0, 100);
data.Rows[randomrow][3] = randomNumber;
}
Thanks for the help!
Split your problem in two:
Create a list of X random, unique numbers. There are numerous ways to do that:
a. Create a list of all numbers 0-100 and then shuffle them. OR
b. Keep a hash set of all the numbers you already created (in addition to the list) and only add a new one if it has not been added before.
Afterwards, loop through the list and the data rows simultaneously and insert the values into the rows.
Here's the simple way to do it without creating a shuffle method for the List (though there are examples of that). Basically create a list of all possible integers, populate the list, then sort by new GUIDs.
int X = 20;
var RowNumbers = new List<int>();
for (int i = 0; i < X; i++)
RowNumbers.Add(i);
foreach (int i in RowNumbers.OrderBy(f => Guid.NewGuid()))
{
data.Rows[i][3] = i;
}
You would need to compare the numbers you have already used to the next one you get from random.Next. If you have already used it, pick another. I also like Heinzi's answer.
Here is algorithm without shuffling and previous result using:
var max = 100; // max available value
var count = 20; // number of random numbers
var random = new Random();
var rest = (double)max;
for (int i = 0; i < max; i++, rest--)
{
if (count / rest > random.NextDouble())
{
Console.WriteLine(i); // here is your random value
count--;
if (count == 0)
{
break;
}
}
}
How do you program c# to make an array of 1000 random integers between 1-100.
And then how do you get when a person enters a number e.g. 68 how can you make the program say 68 appears so and so many times or that it doesn't work at all!
I am not asking for the complete answer I just need a hint where to get started.
Here is what I know:
I have to use the random function and an if but I dont know what to put where!
int[] iArray = new int[1000];
int counter = 0;
Random random = new Random();
for(int i = 0; i < 1000; i++){
iArray[i] = random.Next(1, 101); //1 - 100, including 100
}
int number = Convert.ToInt32(Console.ReadLine());
foreach(int i in iArray){
if(i == number)count++;
}
Console.WriteLine("The number "+ number+" appears "+count+" times!");
Start with a for loop, in each iterative you call the random function and put the result in a public list. After that you make an dialog for the user to type a number. You can serach with lambda expression in the list to see how many matches you get.
Make an array of 1000 random integers between 1-100 and when a person enters a number e.g. 68 how can you make the program say 68 appears so and so many times
I think you're looking for a method like this:
private static Random rnd = new Random();
public static IEnumerable<int> getRandomNumbers(int count, int lowerbound, int upperbound, int specialNumber = int.MinValue, int specialNumberCount = int.MinValue)
{
List<int> list = new List<int>(count);
HashSet<int> specialNumPositions = new HashSet<int>();
if (specialNumberCount > 0)
{
// generate random positions for the number that must be create at least n-times
for (int i = 0; i < specialNumberCount; i++)
{
while (!specialNumPositions.Add(rnd.Next(0, count)))
;
}
}
while (list.Count < count)
{
if (specialNumPositions.Contains(list.Count))
list.Add(specialNumber);
else
list.Add(rnd.Next(lowerbound, upperbound + 1));
}
return list;
}
which you can use in this way:
// ensure that 68 is generated at least 10 times
var list = getRandomNumbers(1000, 1, 100, 68, 10);
Demo
If you instead just want to know how often a number appears in the list, you can ue Linq:
int count = list.Count(i => i == 68);