Created
February 20, 2017 11:52
-
-
Save localheinz/4e36817da519d0542cd45da0584caf33 to your computer and use it in GitHub Desktop.
Dominoes Length of Longest Chain Solution (PHP)
This file contains 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 Dominoes | |
{ | |
public function maxLength(string $string): int | |
{ | |
/** @var Tile[] $tiles */ | |
$tiles = \array_map(function ($tile) { | |
return Tile::fromString($tile); | |
}, \explode(',', $string)); | |
$count = \count($tiles); | |
if ($count < 2) { | |
return $count; | |
} | |
$maxLength = 1; | |
$currentLength = 1; | |
$tile = \array_shift($tiles); | |
foreach ($tiles as $nextTile) { | |
if ($tile->right() === $nextTile->left()) { | |
++$currentLength; | |
$maxLength = \max( | |
$maxLength, | |
$currentLength | |
); | |
} else { | |
$currentLength = 1; | |
} | |
$tile = $nextTile; | |
} | |
return $maxLength; | |
} | |
} |
This file contains 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); | |
namespace Localheinz\Toptal; | |
final class Tile | |
{ | |
/** | |
* @var string | |
*/ | |
private $left; | |
/** | |
* @var string | |
*/ | |
private $right; | |
public function __construct(string $left, string $right) | |
{ | |
$this->left = $left; | |
$this->right = $right; | |
} | |
public function left(): string | |
{ | |
return $this->left; | |
} | |
public function right(): string | |
{ | |
return $this->right; | |
} | |
public static function fromString(string $tile): self | |
{ | |
$sides = \explode('-', $tile); | |
return new self( | |
$sides[0], | |
$sides[1] | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment