2015-09-21 48 views
0

我希望有人能指出我在这个正确的方向。从检索数据的组合,结果在一个数组

我需要使用像这样的阵列,以找出是否有下面的组合是可能的:

客户搜索2间客房和4位客人。在示例数组中,它应该是可能的。但是,如果客户搜索2间客房和5位客人,它应该返回错误。

<? 

    $array[0]=>array(
     'room_type'=>'Single A', 
     'number_of_rooms'=>1, 
     'number_of_beds'=>1, 
    ); 

    $array[1]=>array(
     'room_type'=>'Twin A', 
     'number_of_rooms'=>1, 
     'number_of_beds'=>2, 
    ); 

    $array[2]=>array(
     'room_type'=>'Twin B', 
     'number_of_rooms'=>1, 
     'number_of_beds'=>2, 
    ); 

?> 
+0

2房和4位游客搜索如何为真和2间客房和5个客人是假的,请解释一下? –

回答

0

正确的方向将是一个“贪婪的算法”。

为你的通用算法情况将是:

1. Take `$rooms` amount items with max number of beds from your array (array_walk or do some presorting by key) 
2. If total amount of `number_of_beds` greater or equals return true, else - false :) 
0

你试图让为它匹配:

1. Select the (unselected) room with most beds available 
2. If the number of beds you have altogether is greater or equal the numer requested, you are done. 
3. If the number of rooms selected is smaller than the limit, Continue at 1. 
4. Else the request has failed. 

这样凑生成用户的请求匹配,以及如果你不能满足你的需求,你可以告诉他。

另一种方法,有用的,如果你希望在同一个页面加载许多类似的请求,这将是解析客房提供算你多少1,2,... N-床房有,然后你可以指望床数和房间数量相乘的最大床数。 这将超越贪心算法,但需要一些准备工作。