Gift drawing code

In response to Martin Wolf’s blog posting about a little bit of gift drawing code I’ve hacked up a little piece of code in about 30 minutes to see if I could do better in Java 5.

There is bound to be something wrong with it. (Let’s see what we can find. :))

package net.leenarts.sinterklaas;</code>


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class test {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {

		// Do nothing with input.

		BufferedReader sin = new BufferedReader(
				new InputStreamReader(System.in));

		List<List<String>> names = new ArrayList<List<String>>();
		Map<String, List<String>> related = new HashMap<String, List<String>>();

		System.out.println("Please enter names of people for the draw."
				+ "\nPeople"
				+ "\nentered on one line seperated by whitespace are"
				+ "\nmarked as related. Confirm entry by pressing the"
				+ "\nreturn key. Entering an empty line finishes the"
				+ "\nentry procedure.");
		for (String line = sin.readLine(); line != null && line.length() > 0; line = sin
				.readLine()) {
			// Cut input up to individuals, related to each other.
			List<String> relatives = Arrays.asList(line.split("\\s{1,}"));

			// prevent doubles
			for (String relative : relatives) {
				if (names.contains(relative)) {
					System.out.println("The name \"" + relative
							+ "\" has already been entered,"
							+ " please try again.");
					continue;
				}
			}

			// Store as relatives
			for (String relative : relatives) {
				related.put(relative, relatives);
			}

			// And store the names
			names.add(relatives);
		}

		Collections.sort(names, new Comparator<List<String>>() {
			public int compare(List<String> o1, List<String> o2) {
				if (o1.size() < o2.size()) {
					return 1;
				} else if (o1.size() > o2.size()) {
					return -1;
				}

				return 0;
			}
		});

		// Now to perform the draw
		List<String> receivers = new ArrayList<String>();
		for (List<String> nameList : names) {
			receivers.addAll(nameList);
		}
		List<String> namesList = new ArrayList<String>();
		namesList.addAll(receivers);

		Map<String, String> result = new TreeMap<String, String>();

		for (String name : namesList) {
			List<String> candidateReceivers = new ArrayList<String>(receivers);

			// People are only allowed to draw
			// someone unrelated and not themselves.
			candidateReceivers.removeAll(related.get(name));

			Collections.shuffle(candidateReceivers);

			result.put(name, candidateReceivers.get(0));
			receivers.remove(candidateReceivers.get(0));
		}

		System.out.println("Here are your results:");
		System.out.println(result);

	}

}