reorg and add code for second edition

This commit is contained in:
Aditya Bhargava
2023-08-09 08:20:19 -05:00
parent 9306432a1b
commit 933acafaf3
89 changed files with 18 additions and 117 deletions

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"]