从NetLogo中的2个向量获取排列组合。

huangapple go评论71阅读模式
英文:

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会给你想要的结果。

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.

huangapple
  • 本文由 发表于 2020年1月6日 19:12:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611058.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定