Snippets

Cameron Presley Finding a number that fits multiple constraints

Created by Cameron Presley
// First constraint: Takes an integer and returns true if the number is evenly divisible by 2
let mustBeEven number =
    number % 2 = 0  // Note that we don't require a return statement, the last value returning statement is the return for a function

// Second constraint: Takes an integer and returns true if first digit is equal to the last digit
let firstDigitMustEqualLast number =
    let numberString = number.ToString().ToCharArray()
    let first = numberString.GetValue(0)
    let last = numberString.GetValue(numberString.Length-1)
    first = last

// This is what runs all the constraints together
// The 'rec' keyword tells the F# compiler that this is a recursive function
let rec findValidNumbers numbers constraints = 
    match constraints with
    | [] -> numbers // If the list of constraints is empty, then return numbers
    | firstConstraint::remainingConstraints ->  // Othewise, deconstruct the list so that now there is a head and a tail. 
        let validNumbers = numbers |> List.filter firstConstraint // Another way of saying: List.filter numbers firstConstraint
        findValidNumbers validNumbers remainingConstraints


// Set-up for solution
let numbers = [1000 .. 9999] // Creates a list with values from 1000 to 9999 inclusive
let constraints = [firstDigitMustEqualLast; mustBeEven;]

let result = findValidNumbers numbers constraints

printf "%A" result  // pretty prints the results

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.