给定2个数组Array1 = {a,b,c...n},Array2 = {10,20,15....x}如何生成所有可能的组合作为字符串a(i)b(j)c(k)n(p)
其中
1 <= i <= 10, 1 <= j <= 20 , 1 <= k <= 15, .... 1 <= p <= x
Run Code Online (Sandbox Code Playgroud)
如:
a1 b1 c1 .... n1
a1 b1 c1..... n2
......
......
a10 b20 c15 nx (last combination)
Run Code Online (Sandbox Code Playgroud)
所以在所有组合的总数=元素的产品 array2 =
(10 X 20 X 15 X ..X x)
类似于笛卡尔积,其中第二个数组定义第一个数组中每个元素的上限.
固定数字的示例,
Array x = [a,b,c]
Array y = [3,2,4]
Run Code Online (Sandbox Code Playgroud)
所以我们将有3*2*4 = 24种组合.结果应该是:
a1 b1 c1
a1 b1 …Run Code Online (Sandbox Code Playgroud) 我被给了一个谜题作为礼物.它由4个立方体组成,并排排列.每个立方体的面是四种颜色之一.
为了解决难题,立方体必须定向,以便所有四个立方体的顶部不同,它们的所有前沿都不同,它们的背部都是不同的,并且它们的底部都是不同的.左右两边无所谓.
我的伪代码解决方案是:
我使用F#中的伪代码实现解决了这个难题,但我对第3步的处理方式并不满意:
let problemSpace =
seq { for c1 in cube1Orientations do
for c2 in cube2Orientations do
for c3 in cube3Orientations do
for c4 in cube4Orientations do
yield [c1; c2; c3; c4] }
Run Code Online (Sandbox Code Playgroud)
上面的代码非常具体,只能得出四个方向序列的笛卡尔积.我开始考虑为n个方向序列编写它的方法.
我提出了(从现在开始的所有代码应该在F#interactive中执行得很好):
// Used to just print the contents of a list.
let print =
Seq.fold (fun s i -> s + i.ToString()) "" >> printfn "%s"
// Computes the product of two sequences - kind of; the 2nd argument is …Run Code Online (Sandbox Code Playgroud) 在 其他 语言和其他非懒惰的 JavaScript版本中还有其他问题,但我找不到懒惰的JavaScript版本.
给定一个任意数量的任意大小数组的数组:
var sets = [ [2,3,4,5], ['sweet','ugly'], ['cats','dogs','hogs'] ];
Run Code Online (Sandbox Code Playgroud)
和回调函数:
function holla( n, adj, noun ){
console.log( [n,adj,noun].join(' ') );
}
Run Code Online (Sandbox Code Playgroud)
什么是优雅的方式来迭代整个产品空间而不首先创建大量所有可能的组合?
lazyProduct( sets, holla );
// 2 sweet cats
// 2 sweet dogs
// 2 sweet hogs
// 2 ugly cats
// 2 ugly dogs
// 2 ugly hogs
// 3 sweet cats
// 3 sweet dogs
// 3 sweet hogs
// 3 ugly cats
// 3 ugly dogs
// …Run Code Online (Sandbox Code Playgroud) 这与此处的问题非常相关如何枚举F#中的枚举/类型.我定义了一个联合类型,然后我需要在静态方法中使用该类型的所有可能情况.例如:
type Interests =
| Music
| Books
| Movies
with
static member GetValue( this) = match this with
| Music -> 0
| Books -> 5
| Movies -> 0
static member GetSeqValues() = allCases|>Seq.map(GetValue)
Run Code Online (Sandbox Code Playgroud)
我如何获得allCases?
非常感谢