我接受了这个问题的采访。我将展示我的PHP逻辑:
John,Alex,Jay,Thomson和May住在一栋只有五层楼的公寓楼的不同楼层。约翰不住在顶楼。亚历克斯不住在底层。杰伊不住在顶层或底层。汤姆森住在比亚历克斯更高的楼层。梅不会住在杰伊附近的楼层。杰伊并不住在亚历克斯附近的地板上。每个人住在哪里?
我是如何处理这些问题的?如果我能得到某种书籍或培训?
我最初的想法是找出“开始”的地方,因为这些种类必须先在另一种之前完成。
答案 0 :(得分:2)
这是我怎么做的。只需遍历所有可能的组合。
<?php
for ($alex = 1; $alex <= 5; $alex++) {
// note that it states alex does not live on the bottom floor,
// so you could start alex at 2 here, but then you would have
// to apply logic to the other counts too, and that will start to
// get complicated.
for ($john = 1; $john <= 5; $john++) {
for ($jay = 1; $jay <= 5; $jay++) {
for ($thomson = 1; $thomson <= 5; $thomson++) {
for ($may = 1; $may <= 5; $may++) {
// John, Alex, Jay, Thomson and May live on different floors of an apartment house that contains only five floors
if (count(array_unique(array($alex, $john, $jay, $thomson, $may))) !== 5) {
continue;
}
// John does not live on the top floor
if ($john == 5) {
continue;
}
// Alex does not live on the bottom floor
if ($alex == 1) {
continue;
}
// Jay does not live on either the top or the bottom floor
if ($jay == 1 || $jay == 5) {
continue;
}
// Thomson lives on a higher floor than does Alex
if ($thomson < $alex) {
continue;
}
// May does not live on a floor adjacent to Jay’s
if (abs($may - $jay) == 1) {
continue;
}
// Jay does not live on a floor adjacent to Alex’s
if (abs($jay - $alex) == 1) {
continue;
}
echo 'Alex: floor ' . $alex . '<br>';
echo 'John: floor ' . $john . '<br>';
echo 'Jay: floor ' . $jay . '<br>';
echo 'Thomson: floor ' . $thomson . '<br>';
echo 'May: floor ' . $may . '<br>';
}
}
}
}
}
解决方案/输出:
Alex: floor 2
John: floor 3
Jay: floor 4
Thomson: floor 5
May: floor 1