Skip to content

Instantly share code, notes, and snippets.

@srikumarks
Created October 7, 2021 16:15
Show Gist options
  • Save srikumarks/920fc8e61e06d0c5aa9162fbb9e606cd to your computer and use it in GitHub Desktop.
Save srikumarks/920fc8e61e06d0c5aa9162fbb9e606cd to your computer and use it in GitHub Desktop.
Julia port of Norvig's program for number->word translation
using DataStructures
# Ref: https://github.com/renatoathaydes/prechelt-phone-number-encoding
# This is a straight translation of Norvig's program into Julia.
# Function for function it is a straight port.
mappings = [("eE",0),("jnqJNQ",1),("rwxRWX",2),("dsyDSY",3),("ftFT",4),("amAM",5),
("civCIV",6),("bkuBKU",7),("lopLOP",8),("ghzGHZ",9)]
char2num = Dict((l,d) for (s,d) in mappings for l in s)
function word2num(w)
n = 1
for ch in w
if haskey(char2num, ch)
n = 10 * n + char2num[ch]
end
end
return n
end
function loaddict(words)
d = DefaultDict{Int,Array{String}}(()->[])
for w in words
push!(d[word2num(w)], w)
end
return d
end
nthdigit(digits, n) = parse(Int,digits[n+1])
digitsonly(num) = join(c for c in num if isdigit(c))
function printtranslations(d, num, digits, start=0, words=Array{Union{Int,String}}([]))
if start >= length(digits)
println(num, ": ", join(reverse(words),' '))
else
foundword = false
n = 1
for i in start:(length(digits)-1)
n = 10 * n + nthdigit(digits,i)
for word in d[n]
foundword = true
printtranslations(d, num, digits, i+1, vcat([word],words))
end
end
if !foundword && (length(words) == 0 || typeof(words[1]) != Int)
printtranslations(d, num, digits, start+1, vcat([nthdigit(digits,start)],words))
end
end
end
function main()
words = readlines("dictionary.txt")
numbers = readlines("input.txt")
d = loaddict(words)
for num in numbers
printtranslations(d, num, digitsonly(num))
end
end
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment