Random number generation with equal pairs from 1 to 8?

Like my question, I need to generate random numbers that have the same pairs between the range. I tried to generate random numbers and stored in an array, but the numbers are repeated more than two times. I have 16 random numbers that need to be generated in a range. Any idea how to make it generate only identical pairs of a random number?

+3
source share
4 answers

The following will do my job:

import java.util.*;

class Randoms {
  public static void main(String[] args) {
    List<Integer> randoms = new ArrayList<Integer>();
    Random randomizer = new Random();
    for(int i = 0; i < 8; ) {
      int r = randomizer.nextInt(8) + 1;
      if(!randoms.contains(r)) {
        randoms.add(r);
        ++i;
      }
    }
    List<Integer> clonedList = new ArrayList<Integer>();
    clonedList.addAll(randoms);
    Collections.shuffle(clonedList);

    int[][] cards = new int[8][];
    for(int i = 0; i < 8; ++i) {
      cards[i] = new int[]{ randoms.get(i), clonedList.get(i) };
    }

    for(int i = 0; i < 8; ++i) {
      System.out.println(cards[i][0] + " " + cards[i][1]);
    }
  }
}

One example of doing the above gives:

1 2
8 6
4 3
3 7
2 8
6 1
5 5
7 4

Hope this helps.

+2
source

, , ( - 16 1, 2,..., 8), , , . .

+1

, , :

public static List<Integer> shuffled8() {
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 1; i <= 8; i++) {
        list.add(i);
    }
    Collections.shuffle(list);
    return list;
}

public static void main(String[] args) {
    List<Integer> first = shuffled8();
    List<Integer> second= shuffled8();
    for (int i = 0; i < 8; i++) {
        System.out.println(first.get(i) + " " + second.get(i));
    }
}

shuffled8 1 8, . , first second. first.get(i) second.get(i), .

To summarize this, if you need triplets, you simply add List<Integer> third = shuffled8();, and then first.get(i), second.get(i), third.get(i)this is a triplet that has the necessary properties.

0
source

I did like this:

    Random random = new Random();
    List<Integer> listaCartoes = new ArrayList<Integer>();

    for(int i=0; i<8;)
    {
       int r = random.nextInt(8) + 1;
       if(!listaCartoes.contains(r)) 
       {
          listaCartoes.add(r);
          listaCartoes.add(r);
          ++i;
       }
    }

    Collections.shuffle(listaCartoes);

Hope this helps ^ _ ^

0
source

Source: https://habr.com/ru/post/1734353/


All Articles