-1

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

enter image description here

Please help me, how to solve this and thank for advance.

user3001046
  • 235
  • 1
  • 10
  • 28
  • Possible duplicate of [Random number generator only generating one random number](https://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number) – Lucifer Jun 15 '18 at 13:04
  • If you just need 50 random 5-digit numbers, then use [Random.Next()](https://msdn.microsoft.com/en-us/library/2dx6wyd4(v=vs.110).aspx) like this: `newNum = rand.Next(10000, 100000);` which will give you any number between 10,000 and 99,999. – levelonehuman Jun 15 '18 at 13:05
  • A five digit number is any number between 0 and 99999. Which means, `Random.Next(100000)`. `00010` is justg as random as `12345` by the way. – Panagiotis Kanavos Jun 15 '18 at 13:05
  • If you want to generate 5 digits on the other hand, call `Random.Next(10)` 5 times. No need to try and convert the number back to digits when you can get the digits directly – Panagiotis Kanavos Jun 15 '18 at 13:08
  • @PanagiotisKanavos The number 00010 isn't a "proper " 5-digit number, it's the number 10 padded with zeroes. 10,000 is the smallest 5-digit number and 99,999 is the largest. – levelonehuman Jun 15 '18 at 13:10
  • @levelonehuman it is. It's just as 5 digit as 99999 and just as random. 0 is a digit just like 9. When you ask for 5 random digits, the sequence `00000` has the same probability to appear as *any* other sequence. Removing 10000 entries from the 100K will result in *less* random numbers. – Panagiotis Kanavos Jun 15 '18 at 13:23
  • This is crazy. To only way to have 50 five digit numbers total 500000 is if all numbers are 10000. – paparazzo Jun 15 '18 at 13:45
  • Unfortunately I'm having a very hard time understanding the question due to the poor English. But I think you want to generate 50 random 5-digit numbers that add up to 500000. Is that right? If that's right then the first digit will have to be permitted to be zero because 50 * 10000 is already 500000. Do I understand correctly? – Wyck Jun 15 '18 at 13:51
  • yes i already tried randome.next(0, max) but in the end result of array it is not five digit. Look like number of loop dose not match – user3001046 Jun 16 '18 at 03:33

2 Answers2

3

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

user1477388
  • 20,790
  • 32
  • 144
  • 264
  • Why not `_random.Value.Next(10)` ? Just to avoid formatting? – Panagiotis Kanavos Jun 15 '18 at 13:25
  • I like to avoid hardcoded values whenever possible. The performance difference is negligible. If a coder wants to suddenly make the sequence alphanumeric rather than simply numeric as it is now, they may not realize they must also update the `.Next(x)` line as the code will still compile. – user1477388 Jun 15 '18 at 14:36
0

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

Enigmativity
  • 113,464
  • 11
  • 89
  • 172