project-euler/059.jl
2020-12-08 00:45:39 -06:00

32 lines
826 B
Julia

function mostly_english(it)
init = Dict()
for c in it
if c < 20 || c > 127 return false end
if !isuppercase(Char(c)) c = c ^ 0x20 end
if !haskey(init, c) init[c] = 0 end
init[c] += 1
end
freqs = []
for (key, value) in init
push!(freqs, (value, key))
end
sfreqs = sort(freqs, rev=true)
most = sfreqs[1][2]
most2 = sfreqs[2][2]
most == 'e' || most == 't' || most2 == 'e' || most2 == 't'
end
open("p059_cipher.txt", "r") do f
data = read(f, String)
nums = map(x -> parse(UInt8, x), split(data, ","))
range = UInt8(97):UInt8(122)
for a in range, b in range, c in range
key = [a, b, c]
dec = map(d -> xor(d[2], key[(d[1] - 1) % 3 + 1]), enumerate(nums))
if !mostly_english(dec) continue end
println("key: ", String(key))
println("msg: ", String(dec))
end
end