Add PHP example based on DS extension for chapter 08 - greedy algorithms (#97)

* Add PHP example based on DS extension for chapter 08 - greedy algorithms

* Add code formatting

* Add code formatting / 2
This commit is contained in:
Yuriy Marad
2018-12-28 18:24:40 +02:00
committed by Aditya Bhargava
parent ac08df2ee7
commit 2bf2ab5062

View File

@@ -0,0 +1,36 @@
<?php
// You need to install Data Structures (DS) extension.
// More details here - http://php.net/manual/en/book.ds.php
use \Ds\Set;
$statesNeeded = new Set(["mt", "wa", "or", "id", "nv", "ut", "ca", "az"]);
$stations = [];
$stations["kone"] = new Set(["id", "nv", "ut"]);
$stations["ktwo"] = new Set(["wa", "id", "mt"]);
$stations["kthree"] = new Set(["or", "nv", "ca"]);
$stations["kfour"] = new Set(["nv", "ut"]);
$stations["kfive"] = new Set(["ca", "az"]);
$finalStations = new Set();
while (!$statesNeeded->isEmpty()) {
$bestStation = null;
$statesCovered = new Set();
foreach (array_keys($stations) as $station) {
$states = $stations[$station];
$covered = new Set($statesNeeded);
$covered = $covered->filter(function ($value) use ($states) {
return $states->contains($value);
});
if ($covered->count() > $statesCovered->count()) {
$bestStation = $station;
$statesCovered = $covered;
}
}
$statesNeeded = new Set($statesNeeded);
$statesNeeded = $statesNeeded->filter(function ($value) use ($statesCovered) {
return !$statesCovered->contains($value);
});
$finalStations->add($bestStation);
}
print_r($finalStations); // ["kone", "ktwo", "kthree", "kfive"]