Skip to content

Instantly share code, notes, and snippets.

@pseale
Last active December 13, 2016 01:17
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 pseale/4446f1d4e66a94dcec7aa3e4a34aead5 to your computer and use it in GitHub Desktop.
Save pseale/4446f1d4e66a94dcec7aa3e4a34aead5 to your computer and use it in GitHub Desktop.
//----------------------------------------------------
// main script
import fs = require("fs")
import _ = require("lodash")
import parse = require("./parse")
import decode = require("./decode")
const input = fs.readFileSync("./input.txt", "utf8")
const columns = parse(input)
const decoded = decode(columns)
console.log(`Part A: decoded word is ${decoded.mostFrequent}`)
console.log(`Part B: decoded word is ${decoded.leastFrequent}`)
//--------------------------------------
// parse.ts
"use strict"
import _ = require("lodash")
interface Input {
columns: string[][]
}
function getColumn(lines: string[], column: number): string[] {
return _(lines)
.map(x => x.charAt(column))
.value()
}
function parse(input: string): Input {
const numberOfColumns = 8
const lines = _(input.split("\n"))
.map(x => x.trim())
.filter(x => x !== "")
.value()
const columns = _(_.range(0, numberOfColumns))
.map(x => getColumn(lines, x))
.value()
return { columns }
}
export = parse
//--------------------------------------
//decode.ts
import _ = require("lodash")
interface Input {
columns: string[][]
}
interface ColumnResult {
mostFrequent: string,
leastFrequent: string
}
interface DecodeResult {
mostFrequent: string,
leastFrequent: string
}
function getMostAndLeastFrequentLetters(column: string[]): ColumnResult {
const groups = _(column)
.groupBy(x => x)
.value()
const letters = []
_.forOwn(groups, (value, key) => {
letters.push({
letter: key,
occurrences: value.length
})
})
const mostFrequent = _(letters)
.sortBy(x => x.occurrences)
.map(x => x.letter)
.last()
const leastFrequent = _(letters)
.sortBy(x => x.occurrences)
.map(x => x.letter)
.first()
return {
mostFrequent,
leastFrequent
}
}
function decode(input: Input): DecodeResult {
const lettersArray = _(input.columns)
.map(column => getMostAndLeastFrequentLetters(column))
.value()
const mostFrequent = _(lettersArray)
.map(x => x.mostFrequent )
.join("")
const leastFrequent = _(lettersArray)
.map(x => x.leastFrequent )
.join("")
return {
mostFrequent,
leastFrequent
}
}
export = decode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment