Note that there are some explanatory texts on larger screens.

plurals
  1. POJust for fun - getting started on a tricky PHP logic problem
    text
    copied!<p>As a means of improving my skill as a PHP developer I often challenge myself with problems from the site <a href="http://programmingpraxis.com/2009/02/20/multiple-dwellings/" rel="nofollow">Programming Praxis</a>. 99% of the time I can solve the riddles myself, but I'm jammed on this one and need some guidance on how to get started. The riddle is called "Multiple Dwellings". Here is the problem:</p> <p><em>Baker, Cooper, Fletcher, Miller and Smith live on different floors of an apartment house that contains only five floors. Baker does not live on the top floor. Cooper does not live on the bottom floor. Fletcher does not live on either the top or the bottom floor. Miller lives on a higher floor than does Cooper. Smith does not live on a floor adjacent to Fletcher’s. Fletcher does not live on a floor adjacent to Cooper’s. Where does everyone live?</em></p> <p>My basic trouble is this: I do not understand how to test and evaluate different logical situations. So for example, if we want to test if Baker belongs on the first floor, how best to "fill in" the test positions for each of the 4 remaining people? My (many) attempts have all ended in frustration at the bottoms of massive If/else if/else trees.</p> <p>This isn't for homework, money, or fame - just a riddle I could use a little help getting started on!</p> <p><strong>Updated</strong> - Here is my solution! Thanks for all the input everyone, not necessarily optimized but at least now I understand it:</p> <pre><code>&lt;?php function testThisOne ($testList) { $MillerFloor = ""; $CooperFloor = ""; $SmithFloor = ""; $FletcherFloor = ""; foreach ($testList as $key =&gt; $person) if ($person == "Miller") $MillerFloor = $key; foreach ($testList as $key =&gt; $person) if ($person == "Cooper") $CooperFloor = $key; foreach ($testList as $key =&gt;$person) if ($person == "Smith") $SmithFloor = $key; foreach ($testList as $key =&gt; $person) if ($person == "Fletcher") $FletcherFloor = $key; if ($testList[4] == "Baker") return false; if ($testList[0] == "Cooper") return false; if ($testList[0] == "Fletcher" || $testList[4] == "Fletcher") return false; if ($MillerFloor &lt; $CooperFloor) return false; if (abs($SmithFloor - $FletcherFloor) == 1 || abs($CooperFloor - $FletcherFloor) == 1) return false; return true; } function puzzleSolve1() { $people = array("Baker","Cooper","Fletcher","Miller","Smith"); do { shuffle($people); } while (!testThisOne($people)); return $people; } ?&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload