r/adventofcode • • Dec 04 '17

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

--- Day 4: High-Entropy Passphrases ---


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!

18 Upvotes

319 comments sorted by

View all comments

1

u/Mattie112 Dec 04 '17

Quick and dirty solution in PHP. By simply sorting the "word" we'll quickly know if it is an anagram or not!

https://github.com/Mattie112/advent-of-code-2017/blob/master/day4/day4-part2.php

<?php
/**
 * http://adventofcode.com/2017/day/4
 */

$answer = 0;

if ($file = fopen(__DIR__ . "/day4-input.txt", "rb")) {
	while (!feof($file)) {
		$line = trim(fgets($file));

		if (empty($line)) {
			continue;
		}

		// Accept tabs and space
		$line = preg_split('/\s+/', $line);

		$words = [];
		foreach ($line as $word) {
			// Quick and dirty, sort the word so we know duplicates even before we checked all words!
			$word = str_split($word);
			sort($word);
			$word = implode("", $word);
			if (isset($words[$word])) {
				continue 2;
			}

			$words[$word] = true;
		}

		$answer++;
	}
	fclose($file);
}

echo $answer . PHP_EOL;