Jack Reilly
Jack Reilly

Reputation: 11

Logic for pairing up two sets of values in ArrayList with duplication

I'm baffled on the logic of programming this. I'm sure it's extremely simple.

So, I have an ArrayList<String> with values A, B, C, D, E, F, G. Indexed in that order.

I would like to randomly select a unique letter for each but have no duplication.

The output would look similar to this.

A:B
B:A
C:E
D:F
E:C
F:D

I’ve tried shuffling the ArrayList then moving the index by two, but couldn’t think of a way to prevent duplication, and also randomly selecting indexes then pairing them up but this only works with even numbers.

Upvotes: 0

Views: 95

Answers (2)

Shubham Srivastava
Shubham Srivastava

Reputation: 95

class Solution
{
    public static class Pair
    {
        public String a;
        public String b;

        public Pair(String a,String b)
        {
            this.a=a;
            this.b=b;
        }

        @Override
        public boolean equals(Object o)
        {
            if((this.a.equals(o.a))&&(this.b.equals(o.b)))
            {
                return true;
            }
            if((this.b.equals(o.a))&&(this.a.equals(o.b)))
            {
                return true;
            }
            return false;
        }

        @Override
        public String toString()
        {
            return a+":"+b;
        }
    }
    public static void main(String args[])
    {
        ArrayList<String> list=new ArrayList<String>();
        ......
        .....
        ......
        //list now contains {A,B,C,D,E,F,G}
        Set<Pair> letterset=new HashSet<Pair>();
        for(int i=0;i<list.size();i++)
        {
            for(int j=0;j<list.size();j++)
            {
                Pair pair=new Pair(list.get(i),list.get(j));
                letterset.add(pair);
            }
        }
        Iterator<Pair> iter=letterset.iterator();
        while(iter.hasNext())
        {
            System.out.println(iter.next());
        }
    }
}

Here 1. Pair: it is a class which holds two letters a and b, if two objects same set they are considered to be equal as implemented in the equals() function
2. letterset: set has been creates to remove the duplicate objects. 3. nested loop created to create pairs

I hope this is what you wanted.

Upvotes: 0

cegredev
cegredev

Reputation: 1579

This should be all you need:

ArrayList<String> list = // your list containing the values

ArrayList<String> shuffled = new ArrayList<>(list);
Collections.shuffle(shuffled);

This will give you a second ArrayList<String> that contains all the values of list in random order without duplicates.

Upvotes: 1

Related Questions