Inspired by this question , I wanted to try my hand at the latest to ponder this problem using F #
My approach is probably completely disabled, but in the process of solving this problem, I try to get a list of all permutations of digits 0-9.
I look at his solution using n-ary tree:
type Node = | Branch of (int * Node list) | Leaf of int
I am very pleased with myself because I managed to figure out how to generate the tree I want.
Now my problem is that I cannot decide how to go through this tree and extract the "path" to each sheet as an int. The thing that confuses me is that I need to map individual nodes, but my βexternalβ function must accept a Node list.
My current attempt is almost the right thing, except that it returns me the sum of all the paths ...
let test = Branch(3, [Branch(2, [Leaf(1)]);Branch(1, [Leaf(2)])]) let rec visitor lst acc = let inner n = match n with | Leaf(h) -> acc * 10 + h | Branch(h, t) -> visitor t (acc * 10 + h) List.map inner lst |> List.sum visitor [test] 0 //-> gives 633 (which is 321 + 312)
And I'm not even sure if this is tail-recursive.
(You can suggest another solution for finding permutations, but I'm still interested in solving this particular problem)
EDIT: I published a general permutation algorithm in F # here .
algorithm f #
Benjol Nov 12 '08 at 10:42
source share