Browse thread
Combinatorics in a functional way
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Fernando Alegre <fernando@c...> |
| Subject: | Re: [Caml-list] Combinatorics in a functional way |
Hi,
This is what I would do:
let get i (i0,i1,i2,i3,i4,i5,i6,i7) = match i with
| 0 -> i0 | 1 -> i1 | 2 -> i2 | 3 -> i3 | 4 -> i4 | 5 -> i5 | 6 -> i6
| 7 -> i7 | _ -> invalid_arg "get"
let set i (i0,i1,i2,i3,i4,i5,i6,i7) x = match i with
| 0 -> (x,i1,i2,i3,i4,i5,i6,i7) | 1 -> (i0,x,i2,i3,i4,i5,i6,i7)
| 2 -> (i0,i1,x,i3,i4,i5,i6,i7) | 3 -> (i0,i1,i2,x,i4,i5,i6,i7)
| 4 -> (i0,i1,i2,i3,x,i5,i6,i7) | 5 -> (i0,i1,i2,i3,i4,x,i6,i7)
| 6 -> (i0,i1,i2,i3,i4,i5,x,i7) | 7 -> (i0,i1,i2,i3,i4,i5,i6,x)
| _ -> invalid_arg "set"
let next bounds index =
let rec loop i index =
if i = 8 then index else
let x = get i index in
if x < get i bounds then set i index (x+1)
else loop (i+1) (set i index 0)
in
loop 0 index
let fold f acc bounds =
let rec next i index =
if i = 7 then index
else if index < get i bounds then set i (index+1)
else next (i+1) (set i index 0)
and loop a index =
if i = 8 then acc else loop (f a index) (next bounds index)
in
loop 0 (0,0,0,0,0,0,0)
let find_combi ((p0,p1,p2,p3,p4,p5,p6,p7) as bounds) =
fold (fun l x -> x :: l) [] bounds
Fernando
On Wed, Feb 21, 2007 at 08:36:03PM +1100, Erik de Castro Lopo wrote:
> Hi all,
>
> I'm currently working on something where I need to to generate a
> set of permutations that fit a set of rules. Currently I am doing
> something like: