Random and arrays

4

I was working with random and array and I had 2 doubts on the subject.

1) It is possible to create 3 arrays, each one contains images, and with a random one that chooses a random image of the array and at the same time that the array from which the image is taken is also chosen at random among the 3 array waths up? I do not know if it is understood well

2) Can you make an image more likely to be chosen over another?

    
asked by Zekirak 04.07.2016 в 17:05
source

1 answer

4

1.a)

  

It is possible to create 3 array, each contains images, and with a random   Choose a random image of the array

If possible, we need to use the class Random , create an instance and generate a whole random number between 0 and the last element of our array

Image[] arregloUno = new Image[10];
Image[] arregloDos = new Image[10];
Image[] arregloTres = new Image[10];

Random rnd = new Random();


Image imagenSelecionada = arregloUno[rnd.nextInt(arregloUno.length) ];

1.b)

  

and in turn that the array from which the image is taken is also chosen at   chance among the 3 array there?

If there are two ways

1 - Create a random number to randomly choose the arrangement to use

    int arregloSeleccionado = rnd.nextInt(3); //donde solo puede devolver 0 , 1 y 2 

    if(arregloSeleccionado == 0){
        return arregloUno[rnd.nextInt(arregloUno.length) ]; //elegimos uno
    }else if(arregloSeleccionado == 1){
        return arregloDos[rnd.nextInt(arregloUno.length) ]; //elegimos dos
    }else if(arregloSeleccionado == 2){
        return arregloTres[rnd.nextInt(arregloUno.length) ]; //elegimos tres
    }

o 2 - Create an array of fixes and apply the same logic above, to choose an element through its index

    Object[] arreglos = new Object[3];
    arreglos[0] = arregloUno;
    arreglos[1] = arregloDos;
    arreglos[2] = arregloTres;

    arregloSeleccionado = arreglos[rnd.nextInt(arreglos.length) ];

    imagenSelecionada = arregloSeleccionado[rnd.nextInt(arregloSeleccionado.length) ];

2)

  

You can make an image more likely to be chosen   about another?

You can use this trick:

Let's say we have 3 images and we want them to appear with the following probability: 50, 30 and 20.

So we generate a random number from 0 to 99 (as if it were 1 to 100)

    int numeroAlatorio = rnd.nextInt(100);

And based on the probability we want, we assign

    if(numeroAlatorio < 50){ // rango 0 a 49 (1-50) 
        //mostrar imagen1
    }else if(numeroAlatorio <80){ // rango 50 a 79 (51-80)
        //mostrar imagen2
    }else {// rango 80 a 99 (81-100)
        //mostrar imagen3
    }

The advantage of doing it against 100, is that in percentages it is more common 100% than other numbers

    
answered by 04.07.2016 / 17:58
source