Home > Net >  Generate random pairs of from list of integer without duplication of the number
Generate random pairs of from list of integer without duplication of the number

Time:06-24

I have to list of integer like {1,3,4,5,6,7} I would like to generate an array, which contains pairs from the a and b arrays, in a random order, without duplicates. For example I would like to get the following result:

c={(1,5),(3,7),(4,6),...}

and if we found odd numbers, then it should give us any random selection for that last number

{1,3,4,5,6,7,8}

c={(1,5),(3,7),(4,6,8),...}

I have used below code to achieve this, but it's not working as expected.

int[] a={1,2,3,4,5};
    int[] b={6,7};
    List<int[]> list = new ArrayList<>();
    for (int i = 0; i < a.length;   i)
        for (int j = 0; j < b.length;   j)
            list.add(new int[] {a[i], b[j]});
    Collections.shuffle(list);

Thanks!

CodePudding user response:

I have worked on the similar problem. I hope below code will help you.

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class PairMap {

    public static void main(String[] args) {
        LinkedList<Integer> userList = new LinkedList<>(IntStream.range(1, 18).boxed().collect(Collectors.toList()));
        List<Set<Integer>> usersPairs = new ArrayList<>();
        
        Collections.shuffle(userList);
        
        while(userList.size() > 1)
        {
            Set<Integer> userSet = new TreeSet<>();
            userSet.add(userList.removeFirst());
            userSet.add(userList.removeFirst());
            usersPairs.add(userSet);
            
        }
        
        Random r = new Random();
        if(userList.size() == 1 && !usersPairs.isEmpty()) {
                usersPairs.get(r.nextInt(usersPairs.size())).add(userList.removeFirst());
        }
        System.out.println(usersPairs);
    }

}
  •  Tags:  
  • java
  • Related