Skip to content

Instantly share code, notes, and snippets.

@localheinz
Created February 20, 2017 11:16
Show Gist options
  • Save localheinz/034b40e5c3eda51ec20df6f0226aa448 to your computer and use it in GitHub Desktop.
Save localheinz/034b40e5c3eda51ec20df6f0226aa448 to your computer and use it in GitHub Desktop.
Meagram Solution (PHP)
<?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