jeroldhaas
4/23/2016 - 2:57 AM

top20orders.fsx

(*
 * A pizza chain wants to know which topping combinations are most popular for Build Your Own pizzas.
 * 
 * Given the sample of orders at http://files.olo.com/pizzas.json, write an application (in C#, F# or JavaScript) 
 * to output the top 20 most frequently ordered pizza configurations, listing the toppings for each along with the 
 * number of times that pizza configuration has been ordered.
 *)


// nuget FSharp.Data
// nuget Newtonsoft.Json
#load "Scripts/load-references-debug.fsx"
open System
open System.Text
open FSharp.Core
open Newtonsoft.Json
open FSharp.Data


type Orders = JsonProvider<"""[{"toppings":["cheese"]},{"toppings":["pepperoni", "cheese"]}]""">

let request = Http.RequestString("http://files.olo.com/pizzas.json")

let orders = Orders.Parse(request)

let grouped =
    orders
    |> Array.groupBy(fun o -> o.Toppings)

let sorted =
    grouped
    |> Array.map(fun (key, orders) -> (key, (Array.length orders), orders) )
    |> Array.sortByDescending(fun (_, s, _) -> s)

let displayResults() =
    sorted
    |> Array.take(20)
    |> Array.iter(fun (ts, sum, ps) ->
        let toppingsListString =
            ts
            |> Array.fold(fun s tss -> s + tss + " ") ""
        printfn "Toppings: %s |\t\t\tCount: %i" toppingsListString sum
     )

displayResults ()