如何将嵌套数组转换为一组 one-element 数组
How to convert nested arrays to a group of one-element arrays
抱歉标题不是很清楚。
最好的转换方式是什么
[a, [b, c], [d, e, f], g]
(或其他类似的嵌套数组组)到
[a, b, d, g], [a, b, e, g], [a, b, f, g], [a, c, d, g], ..., [a, c, f, g]
?
我已经在 python 中完成了,但是这个过程可以应用于所有编程语言,因为只有两个循环:
arr = ["a", ["b", "c"], ["d", "e", "f"], "g"]
first = arr[1] # b, c
second = arr[2] # d, e, f
for j in first:
for k in second:
print(list((arr[0], j, k, arr[-1])))
新解
这是一个用 Smalltalk 编写的非递归解决方案。接收者是[a, [b, c], [d, e, f], g]
等子序列的集合。为了简单起见,下面的代码假设接收方数组中的所有条目都是数组,因此正确的接收方应该是 [[a], [b, c], [d, e, f], [g]]
,在 Smalltalk 中写成 #((a) (b c) (d e f) (g))
.
1. selections
2. | selections indexes index |
3. selections := OrderedCollection new.
4. indexes := Array new: self size withAll: 1.
5. [| group |
6. group := (1 to: self size) collect: [:i | (self at: i) at: (indexes at: i)].
7. selections add: group.
8. index := (1 to: self size)
findLast: [:i | (indexes at: i) < (self at: i) size]
ifAbsent: nil.
9. index notNil]
10. whileTrue: [
11. indexes at: index put: (indexes at: index) + 1.
12. index + 1 to: self size do: [:i | indexes at: i put: 1]].
13. ^selections
评论
- 方法名称
- 临时申报
- 初始化输出
- 首先选择每个子组的第一个元素
- 做..而
- 从当前索引处的每个子组中收集一个元素
- 保留刚刚创建的组
- 找到最后一个可以递增的索引
- 如果有none就停止(这会跳到13)
- 如果有一个这样的索引...
- 增加索引
- 将以下所有索引重置为 1(这将恢复为 6)
- 回答结果
既然你现在学习了Smalltalk,我建议你看一下递归的解决方案:
.
或迭代一个:
Generating all combinations from collections in Smalltalk
你现在知道它叫做笛卡尔积,所以你应该可以在 SO 上找到其他答案。
抱歉标题不是很清楚。
最好的转换方式是什么
[a, [b, c], [d, e, f], g]
(或其他类似的嵌套数组组)到
[a, b, d, g], [a, b, e, g], [a, b, f, g], [a, c, d, g], ..., [a, c, f, g]
?
我已经在 python 中完成了,但是这个过程可以应用于所有编程语言,因为只有两个循环:
arr = ["a", ["b", "c"], ["d", "e", "f"], "g"]
first = arr[1] # b, c
second = arr[2] # d, e, f
for j in first:
for k in second:
print(list((arr[0], j, k, arr[-1])))
新解
这是一个用 Smalltalk 编写的非递归解决方案。接收者是[a, [b, c], [d, e, f], g]
等子序列的集合。为了简单起见,下面的代码假设接收方数组中的所有条目都是数组,因此正确的接收方应该是 [[a], [b, c], [d, e, f], [g]]
,在 Smalltalk 中写成 #((a) (b c) (d e f) (g))
.
1. selections
2. | selections indexes index |
3. selections := OrderedCollection new.
4. indexes := Array new: self size withAll: 1.
5. [| group |
6. group := (1 to: self size) collect: [:i | (self at: i) at: (indexes at: i)].
7. selections add: group.
8. index := (1 to: self size)
findLast: [:i | (indexes at: i) < (self at: i) size]
ifAbsent: nil.
9. index notNil]
10. whileTrue: [
11. indexes at: index put: (indexes at: index) + 1.
12. index + 1 to: self size do: [:i | indexes at: i put: 1]].
13. ^selections
评论
- 方法名称
- 临时申报
- 初始化输出
- 首先选择每个子组的第一个元素
- 做..而
- 从当前索引处的每个子组中收集一个元素
- 保留刚刚创建的组
- 找到最后一个可以递增的索引
- 如果有none就停止(这会跳到13)
- 如果有一个这样的索引...
- 增加索引
- 将以下所有索引重置为 1(这将恢复为 6)
- 回答结果
既然你现在学习了Smalltalk,我建议你看一下递归的解决方案:
.
或迭代一个:
Generating all combinations from collections in Smalltalk
你现在知道它叫做笛卡尔积,所以你应该可以在 SO 上找到其他答案。