鉴于我有以下想要留在酒店的人的组合;
如何根据上述情况选择可以选择的所有房间组合,儿童不能独自在一个房间内,所有人都必须使用? (注意:这是在PHP应用程序中)。
例如,上面的内容可以分解为;
理想情况下,这应该导致数据结构沿着;
行[
// Room combination
[
// Individual Room
[
'adults' => 3,
'children' => 6
]
],
[
[
'adults' => 2,
'children' => 5
],
[
'adults' => 1,
'children' => 0
]
]
]
我有以下代码来处理成年人,但是我无法想到如何将儿童的概念引入其中。
public function partition($left, $last = 1, $ar = [], &$partitions = [])
{
if ($left == 0) {
array_push($partitions, $ar);
}
for ($n = $last; $n <= $left; $n++) {
$b = $ar;
array_push($b, $n);
array_merge($partitions, $this->partition($left - $n, $n, $b, $partitions));
}
return $partitions;
}
答案 0 :(得分:0)
搜索排列?
function perm($pool,$result=array())
{
if(empty($pool))
{
echo implode(' ',$result).'<br>';
}else
{
foreach($pool as $key => $value)
{
$neuerpool = $pool;
$neuerresult = $result;
$neuerresult[]= $value;
unset($neuerpool[$key]);
perm($neuerpool,$neuerresult);
}
}
}
perm(array('der hund ','übersprang ','den graben ','mit einem weiten sprung '));
复制
答案 1 :(得分:0)
我有同样的问题,但我们使用scala,我在开发它时看到了他的帖子,我想我们试图将他的解决方案改为一个,然后用一些语言工具我们可以转换和组合,我做不知道他是否可以尝试在php中重现类似的东西,我不知道它是否是最有效的方式,但它的工作速度非常快:
import scala.collection.mutable.ListBuffer
object example extends App {
case class Room(cant: Int, tipo: String) {
override def toString: String = " " + cant + "" + tipo
}
val tagAdults = " adult(s) "
val emptyAdult = Room(0, tagAdults)
val tagChildren = " child(s) "
val emptyChild = Room(0, tagChildren)
def perm(x: Room): Seq[List[Room]] = (1 to x.cant).map { i =>
val result = new ListBuffer[Room]()
var total = x.cant / i
while (total > 0) {
if ((result.map(_.cant).sum + i) <= x.cant) result += Room(i, x.tipo)
total -= 1
}
if (x.cant % i > 0) result += Room(x.cant % i, x.tipo)
result.toList
}
val adults = perm(Room(3, tagAdults))
val childrens = perm(Room(5, tagChildren))
val combinators = for {
x <- adults
y <- childrens.filter(_.length <= adults.map(_.length).max)
} yield x zipAll(y, emptyAdult, emptyChild)
val cleanAdultsBeginZero = combinators.filter(_.forall(_._1.cant > 0))
cleanAdultsBeginZero.sortBy(_.length).foreach { x =>
val tag = "room(s)"
println(s"${x.length} $tag")
x.groupBy { case (room1, room2) => room1.cant + room2.cant }.foreach { case (key, rooms) =>
println(rooms.length + " " + tag + " of " + key + " people " + rooms.head)
}
println()
}
}
您可以在以下位置测试此代码: jdoodle或 scastie
预览一个scala工作表: