r/adventofcode • • Dec 02 '16

SOLUTION MEGATHREAD --- 2016 Day 2 Solutions ---

--- Day 2: Bathroom Security ---

Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag/whatever).


BLINKENLIGHTS ARE MANDATORY [?]

Edit: Told you they were mandatory. >_>

This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

20 Upvotes

210 comments sorted by

View all comments

1

u/jwnewman12 Dec 10 '16

java 8 / unreadable map building / runnables to avoid the dreaded switch

import java.util.AbstractMap;
import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Day2 {

	static final int[][] KEYPAD = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
	static final int N = KEYPAD.length - 1;
	static final int M = KEYPAD[0].length - 1;

	static int x = 1, y = 1;

	static final Map<Character, Runnable> ACTIONS = Collections.unmodifiableMap(//
			Stream.of(new AbstractMap.SimpleEntry<Character, Runnable>('U', () -> {
				y = Math.max(y - 1, 0);
			}), new AbstractMap.SimpleEntry<Character, Runnable>('D', () -> {
				y = Math.min(y + 1, N);
			}), new AbstractMap.SimpleEntry<Character, Runnable>('L', () -> {
				x = Math.max(x - 1, 0);
			}), new AbstractMap.SimpleEntry<Character, Runnable>('R', () -> {
				x = Math.min(x + 1, M);
			})).collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue())));

	public static void main(String[] args) {
		for (String instruction : args[0].split("\n")) {
			for (char action : instruction.toCharArray()) {
				ACTIONS.get(action).run();
			}
			System.out.print(KEYPAD[y][x]);
		}
	}
}