Generate numbers based on the index in the array

Asked

Viewed 54 times

1

I need to generate random numbers within a range... so far so good, however, I need to do this for each position of the array, for example, at position 1 of my array, random numbers should be inserted in a range of 10 to 20, at position 2, random numbers in a range of 30 to 40 and so on. The initial and final position will already be filled.

-- Excerpt from the code --

    Random r = new Random();
    int v[] = new int[capacity];

    v[0] = 0;
    v[capacity - 1] = 15;

    for (int i = 1; i < v.length - 1; i++) {
        switch (i) {
        case 1:
            v[i] = 1 + r.nextInt(2);
            break;
        case 2:
            v[i] = 4 + r.nextInt(3);
            break;
        case 3:
            v[i] = 8 + r.nextInt(3);
            break;
        case 4:
            v[i] = 12 + r.nextInt(2);
            break;
        }
  • The method nextInt class Random already allows you to specify an upper limit. Adding something to gives an upper and lower limit. Take advantage and put the code you are using for the problem, so that the community can help you in the doubt you have.

  • Perfect Isac... the problem is that I get the size of the array per parameter, in the example above, I work with a 6 position, but I will have to handle 5 and 8 positions as well...

1 answer

0


Whether to create random in ranges of 20 values can do it with a for instead of manually as you are doing.

Yes, because even though I’m using a for the fill that you have is manual, because it evaluates the specific indices:

for (int i...){
    switch (i) {
        case 1:

Soon it would be equivalent, and clearer to do:

v[1] = 1 + r.nextInt(2);
v[2] = 4 + r.nextInt(3);
v[3] = 8 + r.nextInt(3);
v[4] = 12 + r.nextInt(2);

Generalizing, having a for and within a switch based on the variable of for is always a bad start.

To solve the problem you can do so:

for (int i = 1, base = 10; i < v.length - 1; i++, base += 20) {
    v[i] = base + r.nextInt(11); //11 pois o ultimo índice é exclusive
}

Notice that I added the base variable that defines the basis of the random and that goes from 20 in 20 beginning at 10.

To better understand how the random is being generated we can analyze the first case. Basis 10 + random value between 0 and 10 gives a value between 10 and 20. The same applies to other items.

Example working on Ideone

  • Isac, thank you so much! It worked! And yes, it was awful that case inside the for... thanks!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.