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().
Related
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 %
I am assigning employees a random integer percentage of 100. This percentage is based on how many employees we have and must total to 100.
If we have 4 employees, I would perhaps want to generate a split such as 80-10-5-5.. if we had 2 employees. The more random the percentages are, the better.
I'm not sure how to accomplish this elegantly without a ton of different if statements but even then the randomness would be limited I feel.
Just assign each employee a random number in a certain range (range ist up to you). Than calculate the sum of the random numbers. Last step: devide each random number by the sum which gives you the percentage.
Example: random number 3, 9, 7
Sum = 19
Percentages: 3/19=16%, 9/19=47%, 7/19=37%
(Values are rounded.)
I have written a sample code for this:
int no_of_employees = 4;
int total_percentage = 100;
List<int> tempNumberList = new List<int>();
List<int> finalNumberList = new List<int>();
Random random = new Random();
for (int i = 0; i < no_of_employees; i++)
{
tempNumberList.Add(random.Next(total_percentage));
}
int sum = tempNumberList.Sum();
foreach(int number in tempNumberList)
{
finalNumberList.Add((number * total_percentage) / sum);
}
if(finalNumberList.Sum() != total_percentage)
{
finalNumberList[0] = finalNumberList[0] + (total_percentage - finalNumberList.Sum());
}
Please feel free to improve the logic if necessary at all.
This should work:
var random = new Random();
var percentages = new List<int>();
int remainder = 100;
for (int i = 0; i < employeesCount; i++)
{
int percentage = random.Next(remainder);
percentages.Add(percentage);
remainder -= percentage;
}
percentages[percentages.Count - 1] += remainder;
Note that
the last line solves the rounding issue in case the percentages' sum is not 100
a solution using only LINQ is also doable although less readable and probably with an impact on performance (using Aggregate for instance introduces the creation of an anonymous type)
I'm not 100% sure this solution guarantees equal probability (especially the last employee's case)
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;
}
}
}
I have created a short program that creates 3 random integers between 1-9 and stores them in an array, however, I would not like any of them to repeat, that is, I would like each to be unique. Is there an easier way to generate 3 unique integers other than having to iterate through the array and comparing each integer to each other? That just seems so tedious if I were to increase my array to beyond 3 integers.
This is my code to generate 3 random numbers. I saw other code in Java, but I thought maybe C# has a easier and more efficient way to do it.
var number = new Numbers[3];
Random r = new Random();
for ( int i = 0; i < number.Length; i++)
{
number[i] = new Numbers(r.Next(1,9));
}
Console.WriteLine("The Three Random Numbers Are:");
foreach(Numbers num in number)
{
Console.WriteLine("{0}", num.Number);
}
I would do something like this:
var range = Enumerable.Range(1, 8);
var rnd = new Random();
var listInts = range.OrderBy(i => rnd.Next()).Take(3).ToList();
You could make an array or a list of the numbers that might be generated, e.g. 0, 1, 2, 3. Then you generate a number from 0 to this list's length, e.g. 2 and pick list[2] so for the next time you only have 0, 1, 3 in your list.
It takes longer to generate it, especially for long lists but it doesn't repeat numbers.
using System;
using System.Collections.Generic;
public class Test
{
static Random random = new Random();
public static List<int> GenerateRandom(int count)
{
// generate count random values.
HashSet<int> candidates = new HashSet<int>();
// top will overflow to Int32.MinValue at the end of the loop
for (Int32 top = Int32.MaxValue - count + 1; top > 0; top++)
{
// May strike a duplicate.
if (!candidates.Add(random.Next(top))) {
candidates.Add(top);
}
}
// load them in to a list.
List<int> result = new List<int>();
result.AddRange(candidates);
// shuffle the results:
int i = result.Count;
while (i > 1)
{
i--;
int k = random.Next(i + 1);
int value = result[k];
result[k] = result[i];
result[i] = value;
}
return result;
}
public static void Main()
{
List<int> vals = GenerateRandom(10);
Console.WriteLine("Result: " + vals.Count);
vals.ForEach(Console.WriteLine);
}
}
Grate explanation and answers from here
Source http://ideone.com/Zjpzdh
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);