Last active
December 25, 2015 07:49
-
-
Save drincruz/6941652 to your computer and use it in GitHub Desktop.
An input String array of names and returns a two dimensional array to see who has who in secret Santa. So basically, {"user1":"user2"}, meaning "user1" needs to get "user2" a gift.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static java.util.Arrays.deepToString; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.Random; | |
import java.util.Queue; | |
class SecretSanta { | |
public String[][] go(String[] s) { | |
List<String> partnerPool = new LinkedList<String>(Arrays.asList(s)); | |
Collections.shuffle(partnerPool); | |
String[][] secretSantaList = new String[partnerPool.size()][2]; | |
for (int i=0; i<s.length; i++) { | |
String partner = partnerPool.remove(0); | |
if (s[i].equals(partner)) { | |
partnerPool.add(partner); | |
partner = partnerPool.remove(0); | |
} | |
secretSantaList[i][0] = s[i]; | |
secretSantaList[i][1] = partner; | |
} | |
return secretSantaList; | |
} | |
public static void main(String... args) { | |
String[] players = new String[] {"Fred", "Wilma", "Barney", "Pebbles", "Bam Bam"}; | |
String[][] santas = new SecretSanta().go(players); | |
System.out.println(deepToString(santas)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I randomly ran into your code and figured this algorithm has an error. As an example, it could give this set as a valid result to your input:
{"Wilma", "Fred", "Pebbles", "Barney", "Bam Bam"}
Which is invalid since Bam Bam would be gifting himself.