Snippets

Cameron Presley F# Constraint Solver

Created by Cameron Presley last modified
// Can be ran in F# interactive of LINQPad
let mustBeFourDigits number = 
    number.ToString().Length = 4

let mustBeEven number =
    number % 2 = 0

let firstDigitMustBeEqualLast number =
    let numberString = number.ToString().ToCharArray()
    let firstDigit = numberString.GetValue(0)
    let lastDigit = numberString.GetValue(numberString.Length-1)
    firstDigit = lastDigit

let rec findValidNumbers numbers constraints = 
    match constraints with
    | [] -> numbers
    | firstConstraint::remainingConstraints ->
        let validNumbers = numbers |> List.filter firstConstraint
        findValidNumbers validNumbers remainingConstraints

let numbers = [1000 .. 9999]
let constraints = [mustBeEven; mustBeFourDigits; firstDigitMustBeEqualLast; ]

let result = findValidNumbers numbers constraints

printf "%A" result

Comments (0)