Generate numbers based on the index in the array

1

I need to generate random numbers within a range ... so long, however, I need to do this for each position of the array, for example, in 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 30 to 40 and so on. The starting position and the final position will already be filled.

- Code snippet -

    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;
        }
    
asked by anonymous 23.09.2017 / 20:24

1 answer

0

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

Yes, because even though you are using for , the padding you have is manual, as it evaluates the specific indexes:

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 for is always a bad beginning.

To solve the problem you can do this:

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 base of the random and that goes from 20 to 20 with beginning in 10 .

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

Example working on Ideone

    
23.09.2017 / 22:15