Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
P5 *Codding Flashmob* 2019.06.21

Hello dear P5 Mind,

Let's start a new P5 adventure, and call it simple P5 Codding Flashmob. There are 4 basic 'principles': 1. Fast result values most 2. Codding is learning 3. Being second means being better than third 4. Production is never impacted

'Event axioms': 1. It is a Friday event 2. Problem takes ~10m - 20m 3. Problem is shared via Rocket, in agency channel 4. Your result is submitted in problem thread in rocket 5. Result that have not been submitted is not considered

'Problem 2019.06.21':
An anagram is : a word, phrase, or name formed by rearranging the letters of another, such as spar, formed from rasp. You will be provided a file, each line of it contains a single word (might contain white spaces). Find the longest anagram list that contains words forming anagram with each other. Ex: arest, aster, astre, rates, reast, resat, serta, stare, strae, tares, tarse, tears, teras, treasapanin

'Expected result': longest anagram list that contains words forming anagram with each

'Input file': a word per line

Be the first to submit your result !!! 3, 2, 1, ….. GOOOOOOO!

Regards, your colleague

<?php
$start = microtime(true);
function sortLettersInWord($word)
{
$stringParts = str_split($word);
sort($stringParts);
return implode('', $stringParts);
}
$words = file('words_alpha.txt', FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
$anagrams = [];
foreach ($words as $word) {
$anagrams[sortLettersInWord($word)][] = $word;
}
$anagrams = array_filter($anagrams, function ($wordList) { return count($wordList) > 1; });
usort($anagrams, function($a, $b) {
return count($b) - count($a);
});
$time_elapsed_secs = microtime(true) - $start;
echo sprintf("Found %d anagrams.\n", count($anagrams));
echo sprintf("Longest anagram list: %s.\n", implode(', ', reset($anagrams)));
echo sprintf("Execution time: %f seconds.\n", $time_elapsed_secs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.