Skip to content

Instantly share code, notes, and snippets.

@damuellen
Created July 11, 2018 22:48
Show Gist options
  • Save damuellen/5663c3992929a8ee58f366f114d36316 to your computer and use it in GitHub Desktop.
Save damuellen/5663c3992929a8ee58f366f114d36316 to your computer and use it in GitHub Desktop.
Base62
import Foundation
let base62Alphabet: [Character] = [
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
]
public func encode(integer: UInt64) -> String {
return encode(integer: integer, alphabet: base62Alphabet)
}
func encode(integer: UInt64, alphabet: [Character]) -> String {
let base = UInt64(alphabet.count)
if integer < base {
return String(alphabet[Int(integer)])
}
return encode(integer: integer / base, alphabet: alphabet) + String(alphabet[Int(integer % base)])
}
func readDay1(_ string: String) -> [Double] {
var buffer = ""
var values = [Double]()
func decode(_ string: String) -> Double {
let base = Double(base62Alphabet.count)
var output: UInt64 = 0
for (i, c) in string.enumerated() {
guard let index = base62Alphabet.index(of: c)
else { continue }
let place = UInt64(pow(base, Double(i)))
output += UInt64(index) * place
}
return Double(output)
}
for c in string.reversed() {
switch c {
case "-":
values.append(decode(buffer) * -1)
buffer.removeAll()
case "+":
values.append(decode(buffer))
buffer.removeAll()
default:
buffer.append(c)
}
}
return values.reversed()
}
func readDay2(_ string: String) -> [Double] {
var idx = string.endIndex
var values = [Double]()
func decode(_ substring: Substring) -> Double {
let base = UInt64(base62Alphabet.count)
var output: UInt64 = 0
for c in substring {
guard let index = base62Alphabet.index(of: c)
else { continue }
output = base * output + UInt64(index)
}
return Double(output)
}
for (c, i) in zip(string.reversed(), string.indices.reversed()) {
switch c {
case "-":
values.append(decode(string[i..<idx]) * -1)
idx = i
case "+":
values.append(decode(string[i..<idx]))
idx = i
default:
continue
}
}
return values.reversed()
}
func readDay3(_ string: String) -> [Double] {
var values = [Double]()
let base = Double(base62Alphabet.count)
var output: UInt64 = 0
var i = 0
for c in string.reversed() {
if let index = base62Alphabet.index(of: c) {
let place = UInt64(pow(base, Double(i)))
output += UInt64(index) * place
i += 1
} else {
values.append(Double(output) * (c == "-" ? -1 : 1))
output = 0
i = 0
}
}
return values.reversed()
}
let day1 = "+w-e-1h-24-2G-2S-2O-M+4v+B3+Fb+Ia+KD+KZ+Jy+Ha+CB+78+52+47+2u+1c+U-M"
let temp1 = readDay1(day1).map { $0 / 100 }
let temp2 = readDay2(day1).map { $0 / 100 }
let temp3 = readDay3(day1).map { $0 / 100 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment