英文:
Get permutations from 2 vectors in Netlogo
问题
我有2个向量,例如
设置 xlims [0 9]
设置 ylims [0 9]
并希望得到一个列表中的排列组合:
[ [0 0] [9 0] [0 9] [9 9] ]
我一直尝试使用 foreach
但没有成功。
如何编写这段代码?
英文:
I have 2 vectors, say
set xlims [0 9]
set ylims [0 9]
and want to get the permutations in a list:
[ [0 0] [9 0] [0 9] [9 9] ]
I have been trying foreach
to no avail.
How can this be coded?
答案1
得分: 1
一个嵌套的foreach
会给你想要的结果。
to-report permute [ lst1 lst2 ]
let result []
foreach lst1 [l1 ->
foreach lst2 [l2 ->
set result lput (list l1 l2) result
]
]
report result
end
permute [0 9] [0 9]
得到 [[0 0] [0 9] [9 0] [9 9]]
,
而 permute [0 9] [0 9 1]
得到 [[0 0] [0 9] [0 1] [9 0] [9 9] [9 1]]
如果你想用超过两个列表来做这个操作,你可能需要使用递归解决方案。
英文:
A nested foreach
will give you what you want.
to-report permute [ lst1 lst2 ]
let result []
foreach lst1 [l1 ->
foreach lst2 [l2 ->
set result lput (list l1 l2) result
]
]
report result
end
permute [0 9] [0 9]
yields [[0 0] [0 9] [9 0] [9 9]]
and permute [0 9] [0 9 1]
yields [[0 0] [0 9] [0 1] [9 0] [9 9] [9 1]]
If you want to do this with more than two lists, you'll likely want a recursive solution.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论