Skip to content

Instantly share code, notes, and snippets.

@localheinz
Created February 20, 2017 11:52
Show Gist options
  • Save localheinz/4e36817da519d0542cd45da0584caf33 to your computer and use it in GitHub Desktop.
Save localheinz/4e36817da519d0542cd45da0584caf33 to your computer and use it in GitHub Desktop.
Dominoes Length of Longest Chain Solution (PHP)
<?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;
}
}
<?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