Skip to content
loading...

re: Daily Challenge #137 - Help the Bookseller VIEW POST

FULL DISCUSSION
 

F#, quick and dirty:

let bookQuantities (l : string list) (m : char list) =
    let counts = List.map (fun (s : string) -> s.[0], s.Split(' ').[1]) l
    List.map (fun c ->
        c,
        List.sumBy (fun (cat, score) ->
            if cat = c then int score else 0) counts) m

Cleaned up version:

let bookQuantities (l : string list) (m : char list) =
    let findOrZero map key = Map.tryFind key map |> Option.defaultValue 0

    let counts =
        List.fold (fun m (s : string) ->
            let (cat, count) = s.[0], s.Split(' ').[1] |> int
            Map.add cat (count + findOrZero m cat) m) Map.empty l
    List.map (fun c -> c, findOrZero counts c) m

Usage:

let l = [ "ABART 20"; "CDXEF 50"; "BKWRK 25"; "BTSQZ 89"; "DRTYM 60" ]
let m = [ 'A'; 'B'; 'C'; 'W' ]

printf "%A" (bookQuantities l m)
// [('A', 20); ('B', 114); ('C', 50); ('W', 0)]
code of conduct - report abuse