Skip to content

Instantly share code, notes, and snippets.

@Sehnsucht-Fr
Last active November 7, 2015 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sehnsucht-Fr/1d22339d9326a0910ccb to your computer and use it in GitHub Desktop.
Save Sehnsucht-Fr/1d22339d9326a0910ccb to your computer and use it in GitHub Desktop.
Linq Challenge #2 (F#)
open System
open System.Text.RegularExpressions
// utility function
let dump name obj = obj.Dump (name : string)
let peek name obj = dump name obj; obj
let split (sep : string) (str : string) = str.Split ([|sep|], StringSplitOptions.RemoveEmptyEntries)
let matches pat str = Regex.Matches (str, pat) |> Seq.cast<Match>
let g_val (index : int) (m : Match) = m.Groups.[index].Value
"10,5,0,8,10,1,4,0,10,1"
|> split ","
|> Array.map int
|> Array.sort
|> fun arr -> arr.[3..]
|> Array.sum
|> dump "Motor Sport Scores"
seq {
for r in 1 .. 8 do
for c in 'a' .. 'h' do
if r <> 6 && c <> 'c' && abs (r - 6) = abs (int c - int 'c')
then yield sprintf "%c%d" c r
}
|> dump "Bishop Moves"
"0,6,12,18,24,30,36,42,48,53,58,63,68,72,77,80,84,87,90,92,95,96,98,99,99,100,99,99,98,96,95,92,90,87,84,80,77,72,68,63,58,53,48,42,36,30,24,18,12,6,0,-6,-12,-18,-24,-30,-36,-42,-48,-53,-58,-63,-68,-72,-77,-80,-84,-87,-90,-92,-95,-96,-98,-99,-99,-100,-99,-99,-98,-96,-95,-92,-90,-87,-84,-80,-77,-72,-68,-63,-58,-53,-48,-42,-36,-30,-24,-18,-12,-6"
|> split ","
|> Seq.chunkBySize 5
|> Seq.map (Array.item 4)
|> dump "Sampling"
"Yes,Yes,No,Yes,No,Yes,No,No,No,Yes,Yes,Yes,Yes,No,Yes,No,No,Yes,Yes"
|> split ","
|> Seq.sumBy (function "Yes" -> 1 | "No" -> -1)
|> dump "Vote Winning Margin"
"Yes,Yes,No,Yes,No,Yes,No,No,No,Yes,Yes,Yes,Yes,No,Yes,No,No,Yes,Yes"
|> split ","
|> Array.countBy id
|> fun [|_, count1; _, count2|] -> abs (count1 - count2)
|> dump "Vote Winning Margin (alternate)"
"Dog,Cat,Rabbit,Dog,Dog,Lizard,Cat,Cat,Dog,Rabbit,Guinea Pig,Dog"
|> split ","
|> Seq.countBy (function "Dog" | "Cat" as pet -> pet | other -> "Other")
|> Seq.map ((<||) <| sprintf "%s:%d")
|> String.concat ", "
|> dump "Counting Pets"
"A5B10CD3"
|> matches "([A-Z])(\d*)"
|> Seq.fold (fun str m -> str + String.replicate (let v2 = g_val 2 m in if v2 = "" then 1 else int v2) (g_val 1 m)) ""
|> dump "Run Length Decoding"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment