Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate random pairs of from list of integer without duplication of the number

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{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!

>Solution :

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);
    }

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading