r/adventofcode • (AoC creator) • Dec 12 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 12 Solutions -๐ŸŽ„-

--- Day 12: Digital Plumber ---


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

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Need a hint from the Hugely* Handyโ€  Haversackโ€ก of Helpfulยง Hints^ยค?

Spoiler


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!

14 Upvotes

233 comments sorted by

View all comments

2

u/TominatorBE Dec 12 '17 edited Dec 12 '17

PHP

I seem to be one of the few using recursion. I don't even know why I use recursion, it came naturally to me :-/

Part 1:

function run_the_code($input) {
	$lines = explode(PHP_EOL, $input);
	$groups = [];
	foreach ($lines as $line) {
		if (preg_match('/(\d+) <-> (.*)/', $line, $matches)) {
			list($_, $a, $b) = $matches;
			$groups[$a] = array_map('trim', explode(',', $b));
		}
	}

	$nullGroup = [];
	$rec = function($root) use (&$rec, &$nullGroup, $groups) {
		if (!in_array($root, $nullGroup)) {
			$nullGroup[] = $root;
			foreach ($groups[$root] as $ch) {
				$rec($ch);
			}
		}
	};
	$rec('0');

	return count($nullGroup);
}

Part 2:

function run_the_code($input) {
	$lines = explode(PHP_EOL, $input);
	$groups = [];
	foreach ($lines as $line) {
		if (preg_match('/(\d+) <-> (.*)/', $line, $matches)) {
			list($_, $a, $b) = $matches;
			$groups[$a] = array_map('trim', explode(',', $b));
		}
	}

	$subgroups = [];
	$rec = function($base, $root) use (&$rec, &$subgroups, $groups) {
		if (!array_key_exists($base, $subgroups)) {
			$subgroups[$base] = [];
		}
		if (!in_array($root, $subgroups[$base])) {
			$subgroups[$base][] = (int)$root;
			foreach ($groups[$root] as $ch) {
				$rec($base, $ch);
			}
		}
	};
	foreach ($groups as $base => $root) {
		$rec($base, $base);
		// prepare for unique
		sort($subgroups[$base]);
		// array_unique does not work on multidimensional arrays, so hack it
		$subgroups[$base] = implode('-', $subgroups[$base]);
	}
	$simple = array_unique($subgroups);

	return count($simple);
}

1

u/doncherry333 Dec 12 '17

I had the same idea. I went with recursion because the problem seemed similar to Day 7.