Inspired by this question, I wanted to try my hand at the latest ponder this challenge, using F#
My approach is probably completely off course, but in the course of solving this problem, I'm trying to get a list of all the permutations of the digits 0-9.
I'm looking at solving it using a n-ary tree like so:
type Node =
| Branch of (int * Node list)
| Leaf of int
I'm quite pleased with myself, because I've managed to work out how to generate the tree that I want.
My problem now is that I can't work out how to traverse this tree and extract the 'path' to each leaf as an int. Thing thing that is confusing me is that I need to match on individual Nodes, but my 'outer' function needs to take a Node list.
My current attempt almost does 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 that this is tail-recursive.
(You're quite welcome to propose another solution for finding permutations, but I'm still interested in the solution to this particular problem)
EDIT: I've posted a generic permutations algorithm in F# here.