Random between certain numbers

-1

Hi, I wanted to know if it is possible to generate a random number between specific numbers. For example I have a board of 9 numbers (1,2,3,4,5,6,7,8,9) but the squares (2,6,8) are already occupied. Is it possible to create a random where only the remaining numbers can be output (1,3,4,5,7,9)?

Thank you.

    
asked by Agustin Val 17.11.2017 в 14:56
source

1 answer

5

One solution is to have a list with the available positions, "shuffle" it and take out elements.

class Test {
  public static void main(String args[]) {
    int[] posiciones = { 1,2,3,4,5,6,7,8,9 };

    shuffleArray(posiciones);
    for (int i = 0; i < posiciones.length; i++) {
      System.out.print(posiciones[i] + " ");
    }
  }

  // Algoritmo Fisher–Yates para barajar
  static void shuffleArray(int[] ar) {

    Random rnd = ThreadLocalRandom.current();
    for (int i = ar.length - 1; i > 0; i--) {
      int index = rnd.nextInt(i + 1);
      int a = ar[index];
      ar[index] = ar[i];
      ar[i] = a;
    }
  }
}
    
answered by 17.11.2017 / 15:22
source