|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | +--- Day 4: High-Entropy Passphrases --- |
| 5 | +
|
| 6 | +A new system policy has been put in place that requires all accounts to use a passphrase instead of simply a password. A passphrase consists of a series of words (lowercase letters) separated by spaces. |
| 7 | +
|
| 8 | +To ensure security, a valid passphrase must contain no duplicate words. |
| 9 | +
|
| 10 | +For example: |
| 11 | +
|
| 12 | + aa bb cc dd ee is valid. |
| 13 | + aa bb cc dd aa is not valid - the word aa appears more than once. |
| 14 | + aa bb cc dd aaa is valid - aa and aaa count as different words. |
| 15 | +
|
| 16 | +The system's full passphrase list is available as your puzzle input. How many passphrases are valid? |
| 17 | +
|
| 18 | +The first half of this puzzle is complete! It provides one gold star: * |
| 19 | +--- Part Two --- |
| 20 | +
|
| 21 | +For added security, yet another system policy has been put in place. Now, a valid passphrase must contain no two words that are anagrams of each other - that is, a passphrase is invalid if any word's letters can be rearranged to form any other word in the passphrase. |
| 22 | +
|
| 23 | +For example: |
| 24 | +
|
| 25 | + abcde fghij is a valid passphrase. |
| 26 | + abcde xyz ecdab is not valid - the letters from the third word can be rearranged to form the first word. |
| 27 | + a ab abc abd abf abj is a valid passphrase, because all letters need to be used when forming another word. |
| 28 | + iiii oiii ooii oooi oooo is valid. |
| 29 | + oiii ioii iioi iiio is not valid - any of these words can be rearranged to form any other word. |
| 30 | +
|
| 31 | +Under this new system policy, how many passphrases are valid? |
| 32 | +
|
| 33 | +*/ |
| 34 | + |
| 35 | +$input = <<<INPUT |
| 36 | +abcde fghij |
| 37 | +abcde xyz ecdab |
| 38 | +a ab abc abd abf abj |
| 39 | +iiii oiii ooii oooi oooo |
| 40 | +oiii ioii iioi iiio |
| 41 | +INPUT; |
| 42 | + |
| 43 | +$passphrases = explode("\n", $input); |
| 44 | +$valid = 0; |
| 45 | +foreach ($passphrases as $passphrase) { |
| 46 | + $invalid = FALSE; |
| 47 | + $words = explode(' ', $passphrase); |
| 48 | + for ($i = 0; $i < count($words); $i++) { |
| 49 | + $iword = str_split($words[$i]); |
| 50 | + sort($iword); |
| 51 | + for ($j = $i + 1; $j < count($words); $j++) { |
| 52 | + $jword = str_split($words[$j]); |
| 53 | + sort($jword); |
| 54 | + if ($iword == $jword) { |
| 55 | + $invalid = TRUE; |
| 56 | + break(2); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + if (!$invalid) { |
| 61 | + print $passphrase . "\n"; |
| 62 | + $valid++; |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +print $valid . "\n"; |
0 commit comments