获取数组项的所有组合,同时保留顺序 - Ruby
给定一个字符串数组,
["the" "cat" "sat" "on" "the" "mat"]
我希望从任何起始位置按顺序获取项目的所有组合,例如
["the"]
["the" "cat"]
["the" "cat" "sat"]
...
["cat" "sat" "on" "the" "mat"]
["sat" "on" "the" "mat"]
["on" "the" "mat"]
...
["sat" "on"]
["sat" "on" "the"]
不允许原始序列之外的组合或缺少元素的组合,例如
["sat" "mat"] # missing "on"
["the" "on"] # reverse order
我还想知道此操作是否有具体名称或者是否有更简洁的描述方式。
谢谢。
Given an array of strings
["the" "cat" "sat" "on" "the" "mat"]
I'm looking to get all combinations of items in sequence, from any starting position, e.g.
["the"]
["the" "cat"]
["the" "cat" "sat"]
...
["cat" "sat" "on" "the" "mat"]
["sat" "on" "the" "mat"]
["on" "the" "mat"]
...
["sat" "on"]
["sat" "on" "the"]
Combinations out of the original sequence or with missing elements are disallowed, e.g.
["sat" "mat"] # missing "on"
["the" "on"] # reverse order
I'd also like to know if this operation has a particular name or if there's a neater way of describing it.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您喜欢单行,您可以尝试
顺便说一句,我认为它们被称为数组的“所有子序列”。
If you're into one-liners, you might try
BTW, I think those are called "all subsequences" of an array.
只需迭代每个起始位置,并迭代每个可能的结束位置:
需要 ruby 1.8.7+(或反向移植)来实现
flatten(1)
。Just iterate over each starting position and for each starting position over each possible end position:
Requires ruby 1.8.7+ (or backports) for
flatten(1)
.在这里你可以得到所有的组合
here you can get all the combinations