-5

I want to hand out the number 5 randomly between 4 variables.

e.g:

BEFORE:

int a = 0;
int b = 0;
int c = 0;
int d = 0;

AFTER:

int a = 2;
int b = 0;
int c = 1;
int d = 2;

or

int a = 0;
int b = 3;
int c = 0;
int d = 2;

or anything, but the most important is that the a+b+c+d has to equal 5 .

Thank you for your answer!

Daniel
  • 101
  • 7
  • Have you tried to google "java random number"? – Joakim Danielson Apr 07 '18 at 19:47
  • How random do the numbers have to be? You could keep track of the current sum, and chose a random number for the next variable a between current sum and 5. That will have the tendency to have 0's at the end. – geisterfurz007 Apr 07 '18 at 19:49
  • 2
    Possible duplicate of [How do I generate random integers within a specific range in Java?](https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java) – sswierczek Apr 07 '18 at 19:53

2 Answers2

3
  1. You set a to a random number between 0 and 5.
  2. You set b to a random number between 0 and 5 - a
  3. You set c to a random number between 0 and 5 - a - b
  4. You set d to 5 - a - b - c

As a result, you get 4 numbers with a sum of 5.

So as not to be boring and repeat tons of questions on Stack Overflow about finding a number in a given range, which would be a sub-task there, here's a link: How do I generate random integers within a specific range in Java?

nicael
  • 18,550
  • 13
  • 57
  • 90
  • 1
    Caution: This will not make the numbers evenly distributed as c will most likely have a smaller range of numbers to pick from than a. – geisterfurz007 Apr 07 '18 at 19:55
0

you can use this

    Random random =  new Random();

    int a = random.nextInt(5);
    int b = random.nextInt(5 - a);
    int c = random.nextInt(5 - a - b);
    int d = 5 - (a + b + c);

    System.out.print("a : " + a  +
            "\nb : " + b+
            "\nc : " + c+
            "\nd : " + d +
            "\n\nTotal : " + (a+b+c+d)); \\total will be 5
geisterfurz007
  • 5,292
  • 5
  • 33
  • 54
Mohamed SLimani
  • 351
  • 2
  • 9