如何找到连续的空位?
我假设将一群人(在运行时给出)放入一个二维点数组中,随机分组在一起(找出所有可能的位置并随机选择一个)
首先,我想尝试首先是一个数组,
如果我有一个大小为 10 的点数组,如下所示,
spots[occupied,open,open,occupied,occupied,occupied,open,open,open,open]
可以放置 2 个人
,有没有特定的算法可以解决此类问题? 感谢您的帮助!
I am suppose to put a group of people (given at run-time) in to a 2 dimensional array of spot, group together in a row randomly(find out all possible positions and randomly pick one)
To start of, I wanna try in an array first
if I have an array of spots of size 10 like below
spots[occupied,open,open,occupied,occupied,occupied,open,open,open,open]
to put 2 people
Is there a particular algorithm to do this kind of problem?
Thanks for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 python 中:
这是另一种方法,它更有效一些:
最后,如果您确实选择使用 python,您可以在一行中完成:
in python:
here's another approach, its a little more efficient:
and finally, if you did choose to use python you could do it in one line:
伪代码:
final 现在有块了。
如果允许 people_num 为 1 的边缘情况,则必须在伪代码中指示的位置检查完整的块
Pseudo code:
final now has the blocks.
If you allow the edge case of people_num being 1, you have to check for a complete block at the position indicated in the pseudocode
我将使用 Mathematica 代码,但我相信您可以遵循逻辑。
首先找到
列表的随机排列
fill
(在StackOverflow上很容易找到算法):然后将函数“映射”到
spots
列表的每个元素上,并且如果该元素是open
返回randomfill
列表中的下一个值,否则返回不变的元素:I shall use Mathematica code but I believe you can follow the logic.
Starting with:
First find a random permutation of the list
fill
(it is easy to find an algorithm on StackOverflow):Then "map" a function onto each element of the
spots
list, and if the element isopen
return the next value from therandomfill
list, else return the element unchanged: