Samples

Sudoku

let sudoku (puzzle : Puzzle) = cp {
        let! vars = newVars 81 [1..9]
        do! cp.zipWithM_ (fun x n -> cp { if n > 0 then do! hasValue x n }) vars puzzle
        do! cp.mapM_ allDifferent (rows vars)
        do! cp.mapM_ allDifferent (columns vars)
        do! cp.mapM_ allDifferent (boxes vars)
        return! labelling vars
    }

N-queen

let nqueen n = cp {
        let! allvars = newVars n [1..n]
        do! allDifferent allvars
        let rec diagonals vars =  
            let rec diagonals' v vrest i = cp {
                    match vrest with
                    | vr::vrs ->
                        let j = i + 1
                        do! compareBy (fun v1 v2 -> v1 <> v2 + j) v vr
                        do! compareBy (fun v1 v2 -> v1 <> v2 - j) v vr 
                        return! diagonals' v vrs j
                    | [] -> return ()
                }
            cp {
                match vars with
                | v::vs -> 
                    do! diagonals' v vs 0 
                    return! diagonals vs
                | [] -> return ()
            }
        do! diagonals allvars
        return! labelling allvars
    }

Latin squares

let latinSquares = cp {
        let! vars = newVars 9 [0..2]
        do! cp.mapM_ allDifferent (rows vars)
        do! cp.mapM_ allDifferent (columns vars)
        return! labelling vars
    }

Last edited Aug 6, 2011 at 5:59 PM by d95danb, version 2

Comments

No comments yet.