LeetCode 2748. Number of Beautiful Pairs in F#

URL

Number of Beautiful Pairs - LeetCode

Code

https://github.com/syohex/dotnet-study/tree/master/fsharp/leetcode/problems/2748/main.fsx

open System

let countBeautifulPairs (nums: int list) : int =
    let rec gcd a b = if a % b = 0 then b else gcd b (a % b)

    let rec countBeautifulPairs' pairs acc =
        match pairs with
        | []
        | _ :: [] -> acc
        | (first, _) :: t ->
            let count = t |> List.filter (fun (_, last) -> gcd first last = 1) |> List.length
            countBeautifulPairs' t (acc + count)

    let charToInt = Char.GetNumericValue >> int

    let pairs =
        nums
        |> List.map string
        |> List.map (fun s -> Seq.head s |> charToInt, Seq.last s |> charToInt)

    countBeautifulPairs' pairs 0