Skip to content

Instantly share code, notes, and snippets.

@mtdtks
Last active June 19, 2018 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtdtks/663b4abe234d08e96efb6dd908562916 to your computer and use it in GitHub Desktop.
Save mtdtks/663b4abe234d08e96efb6dd908562916 to your computer and use it in GitHub Desktop.
ex2
<?php
interface Human
{
public function getName();
public function setName(string $name);
public function getWeight();
public function setWeight(int $weight);
public function getHeight();
public function setHeight(int $height);
}
class Person implements Human
{
private $name;
private $weight;
private $height;
public function __construct(string $name,int $weight,int $height)
{
$this->name = $name;
$this->weight = $weight;
$this->height = $height;
}
public function getName(): string
{ return $this->name; }
public function setName(string $name): void
{ $this->name = $name; }
public function getHeight(): int
{ return $this->height; }
public function setHeight(int $height): void
{ $this->height = $height; }
public function getWeight(): int
{ return $this->weight; }
public function setWeight(int $weight): void
{ $this->weight = $weight; }
}
interface Comparator
{
}
interface HumanComparator
{
public function compare (Human $fst, Human $sec): int;
}
class WeightComparator implements HumanComparator, Comparator
{
public function compare (Human $fst, Human $sec): int
{
$a = $fst->getWeight();
$b = $sec->getWeight();
$res = null;
if ($a < $b) { $res = -1; }
elseif ($a > $b) { $res = 1; }
else { $res = 0; }
return $res;
}
}
class NameComparator implements HumanComparator, Comparator
{
public function compare(Human $fst, Human $sec): int
{
$a = $fst->getName();
$b = $sec->getName();
return strcmp($a, $b);
}
}
interface Algorithm
{
public function sort(array $array, Comparator $comparator);
}
// $arrayのふたつのPersonをくらべて$target順に並べ替える
class SelectionSort implements Algorithm
{
public function sort($array, $comparator)
{
for($i = 0; $i < count($array); $i++)
{
for($n = 1; $n < count($array); $n++)
{
// 隣接要素を比較し大小が逆なら入替える
if ($comparator->compare($array[$n-1], $array[$n]) === 1) {
$temp = $array[$n];
$array[$n] = $array[$n - 1];
$array[$n - 1] = $temp;
}
}
}
return $array;
}
}
//$comparator = new NameComparator();
$comparator = new WeightComparator();
$input = array( new Person('たろう', 60, 165),
new Person('次郎', 62, 170),
new Person('三郎', 55, 155),
new Person('あつろう', 80, 180),
);
$algorithm = new SelectionSort();
$myArraySort = function (Array $input, Algorithm $algorithm, Comparator $comparator): array {
$res = $algorithm->sort($input, $comparator);
return $res;
};
$cons = $myArraySort($input, $algorithm, $comparator);
echo var_dump($cons);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment