Created
February 20, 2017 11:16
-
-
Save localheinz/034b40e5c3eda51ec20df6f0226aa448 to your computer and use it in GitHub Desktop.
Meagram Solution (PHP)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
final class Meagrams | |
{ | |
/** | |
* @var string[] | |
*/ | |
private $words; | |
public function __construct(array $words) | |
{ | |
$this->words = $words; | |
} | |
/** | |
* @param string $word | |
* | |
* @return string[] | |
*/ | |
public function __invoke(string $word): array | |
{ | |
$length = \strlen($word); | |
$words = \array_filter($this->words, function ($word) use ($length) { | |
return \strlen($word) === $length; | |
}); | |
$characters = $this->characters($word); | |
return \array_values(\array_filter($words, function ($word) use ($characters) { | |
return 1 === $this->difference($characters, $this->characters($word)); | |
})); | |
} | |
private function characters(string $word): array | |
{ | |
$characters = \str_split($word); | |
\sort($characters); | |
return $characters; | |
} | |
private function difference(array $charactersOne, array $charactersTwo): int | |
{ | |
foreach ($charactersOne as $characterOne) { | |
$key = \array_search( | |
$characterOne, | |
$charactersTwo, | |
true | |
); | |
if (false !== $key) { | |
unset($charactersTwo[$key]); | |
} | |
} | |
return \count($charactersTwo); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment