Chris Hill Chris Hill - 7 days ago 6
Java Question

prevent two objects in two identical lists from matching in java

I'm trying to make a program that randomly matches people in a list in order to figure out who is buying who a gift this year.

The problem I am running into is that certain people can't match up because they are married, for example, Deana and Pete can't match nor can Chris and Lindsay.

Here is what I have right now without trying to prevent these match ups.
Thank you,

String[] family = {"Jen", "Chris", "Lindsay", "Erica", "Deana", "Pete"};
ArrayList people = new ArrayList<String>();
for(int i = 0; i<family.length; i++){
people.add(family[i]);
}

int i=0;
while (i != family.length) {
int personTwo = (int) Math.floor(Math.random() * people.size());
String perTst = people.get(personTwo).toString();
if((family[i] != perTst)){

System.out.println(family[i] +" buys for " + people.get(personTwo));

people.remove(personTwo);
i++;
}


}

Answer

Just create a map of couples:

Map<String, String> couples = new HashMap<>();
couples.put("Deana", "Pete");
couples.put("Chris", "Lindsay");

Then update your if to check if they're a couple:

if(!family[i].equals(perTst)
        && !perTst.equals(couples.get(family[i]))
        && !family[i].equals(couples.get(perTst))) {
    //...
}
Comments