Pass random values to Matrix

0

I have a matrix with 30 fixed values, I wanted to know how to generate these same 30 values, however random, if possible with value limit between (2400, 400).

How the array is currently:

private int[][] coordenadas = {
                { 2380, 29 },{ 2600, 59  },{ 1380, 89 },{ 780, 109},
                { 580, 139 },{ 880, 239  },{ 790, 259 },{ 760, 50 },
                { 790, 150 },{ 1980, 209 },{ 560, 45 },{ 510, 70 },
                { 930, 159 },{ 590, 80   },{ 530, 60 },{ 940, 59 },
                { 990, 30  },{ 920, 200  },{ 900, 259 },{ 660, 50 },
                { 540, 90  },{ 810, 220  },{ 900, 259 },{ 660, 50 },
                { 820, 128 },{ 490, 170  },{ 700, 30 },{ 920, 300 },
                { 856, 328 },{ 456, 320  }
        };
    
asked by anonymous 20.10.2015 / 13:49

2 answers

2

To generate the random numbers one can use the Math or Random libs. I prefer, for various aspects, to use Random.

the nextInt (int Threshold) method generates an integer between 0 and less than or equal to the Threshold. To use something like [min, max] it is necessary to add the min to the final number.

Random rand = new Random();
int m[][] = new int[30][2]; 
for(int i = 0; i < m.length; i++) { 
    m[i][0] = rand.nextInt(2400);
    m[i][1] = rand.nextInt(400);
}

// Exibindo o que foi criado
for(int i = 0; i < m.length; i++) { 
    System.out.printf(" {%d, %d} ", m[i][0], m[i][1]);  
}

Follow Ideone

    
20.10.2015 / 15:24
1

You can use the Math.random function, it generates random numbers between [0,1]

int m[][] = new int[30][2]; 
for(int i = 0; i < m.length; i++) { 
   m[i][0] = (int) Math.random()*2400; //numeros de 0 a 2400
   m[i][1] = (int) Math.random()*400; //numeros de 0 a 400
}
    
21.10.2015 / 10:51