我被给了一个谜题作为礼物.它由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) 我必须对列表列表进行投影,这些列表返回每个列表中每个元素的所有组合.例如:
projection([[1]; [2; 3]]) = [[1; 2]; [1; 3]].
projection([[1]; [2; 3]; [4; 5]]) = [[1; 2; 4]; [1; 2; 5]; [1; 3; 4]; [1; 3; 5]].
Run Code Online (Sandbox Code Playgroud)
我想出了一个功能:
let projection lss0 =
let rec projectionUtil lss accs =
match lss with
| [] -> accs
| ls::lss' -> projectionUtil lss' (List.fold (fun accs' l ->
accs' @ List.map (fun acc -> acc @ [l]) accs)
[] ls)
match lss0 with
| [] -> []
| ls::lss' ->
projectionUtil lss' (List.map …Run Code Online (Sandbox Code Playgroud) 我是f#的新手
我试着计算一组数字的笛卡尔积.我"借"了这个.
let xs = [1..99]
let ys = [1..99]
seq {for x in xs do for y in ys do yield x * y}
Run Code Online (Sandbox Code Playgroud)
有更好或更优雅的方式吗?
加里
可能重复:
F# - 两个列表的交叉乘积
在F#中有效地投影列表列表
我有一个函数,它接受两个整数列表,并返回一个包含所有笛卡儿积的列表.我认为我有正确的想法,但没有正确的实施.我可以得到一些指示吗?
let rec cartesian = function
| ([],[]) -> []
| (xs,[]) -> []
| ([],ys) -> []
| (x::xs,ys) -> List.map(fun y -> (x,y)::[]) cartesian (xs,ys)
Run Code Online (Sandbox Code Playgroud)