Skip to content

Instantly share code, notes, and snippets.

@jeffesp
Created August 8, 2013 17:29
Show Gist options
  • Save jeffesp/6186753 to your computer and use it in GitHub Desktop.
Save jeffesp/6186753 to your computer and use it in GitHub Desktop.
Efficiency of Morse code
open System.IO
type MorseCodePoint = Dit | Dah
type MorseEncodedWord = { word: string; total: int; efficiency: float }
let codePointLength point =
match point with
| Dit -> 1
| Dah -> 3
let alphabet =
Map.empty.
Add('a', [ Dit; Dah ]).
Add('b', [ Dah; Dit; Dit; Dit;]).
Add('c', [ Dah; Dit; Dah; Dit;]).
Add('d', [ Dah; Dit; Dit;]).
Add('e', [ Dit;]).
Add('f', [ Dit; Dit; Dah; Dit;]).
Add('g', [ Dah; Dah; Dit;]).
Add('h', [ Dit; Dit; Dit; Dit;]).
Add('i', [ Dit; Dit;]).
Add('j', [ Dit; Dah; Dah; Dah;]).
Add('k', [ Dah; Dit; Dah;]).
Add('l', [ Dit; Dah; Dit; Dit;]).
Add('m', [ Dah; Dah;]).
Add('n', [ Dah; Dit;]).
Add('o', [ Dah; Dah; Dah;]).
Add('p', [ Dit; Dah; Dah; Dit;]).
Add('q', [ Dah; Dah; Dit; Dah;]).
Add('r', [ Dit; Dah; Dit;]).
Add('s', [ Dit; Dit; Dit;]).
Add('t', [ Dah;]).
Add('u', [ Dit; Dit; Dah;]).
Add('v', [ Dit; Dit; Dit; Dah;]).
Add('w', [ Dit; Dah; Dah;]).
Add('x', [ Dah; Dit; Dit; Dah;]).
Add('y', [ Dah; Dit; Dah; Dah;]).
Add('z', [ Dah; Dah; Dit; Dit;])
let morseCharacterLength char =
match alphabet.TryFind(char) with
| Some value -> value |> List.sumBy codePointLength
| None -> 0
let computeWordEfficiency (word:string) =
let len = word.Length
let chars = word.ToLowerInvariant().ToCharArray() |> Array.toList
let total = chars |> List.map morseCharacterLength |> List.append([ len - 1]) |> List.sum
{ word = word; total = total; efficiency = float total / float len }
let readLines (input:TextReader) =
let readNext _ = input.ReadLine()
let inputNotDone = (<>) null
Seq.initInfinite readNext |> Seq.takeWhile inputNotDone
let source = new StreamReader(@"C:\Downloads\linuxwords.txt")
let data = readLines source |> Seq.map computeWordEfficiency
data |> Seq.maxBy (fun (item:MorseEncodedWord) -> item.efficiency) |> printfn "%A"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment