Lately I've been really into doing Google Codejam practice problems (aka I'm a nerd). I discovered I really need to brush up on my algorithms ):

## The Problem

The decimal numeral system is composed of ten digits, which we represent as "0123456789" (the digits in a system are written from lowest to highest). Imagine you have discovered an alien numeral system composed of some number of digits, which may or may not be the same as those used in decimal.

For example, if the alien numeral system were represented as `oF8`, then the numbers one through ten would be `F, 8, Fo, FF, F8, 8o, 8F, 88, Foo, FoF`. We would like to be able to work with numbers in arbitrary alien systems.

More generally, we want to be able to convert an arbitrary number that's written in one alien system into a second alien system. Complete problem here.

## My Solution (Ruby)

``````def hash_indexes(arr)
hash = {}

for i in 1..(arr.length - 1)
hash[arr[i]] = i
end
return hash
end

def log(base, num)
Math::log10(num)/Math::log10(base)
end

def to_decimal(source, num)
num_arr = num.split("")
hashed_source = hash_indexes(source.split(""))
dec = 0

for i in 0..(num_arr.size - 1)
hashed_no = hashed_source[num_arr[i]].to_i
dec += hashed_no * (source.size ** (num_arr.size - 1 - i))
end
return dec
end

def to_target(target, decimal)
final = ""
target_arr = target.split("")

i = log(target.size, decimal).to_i
while i >= 0
value = target.length ** i
times = (decimal/value).to_i
final << target_arr[times]
decimal %= value
i -= 1
end
return final
end

def solve(line)
arr = line.split(" ")
to_target(arr, to_decimal(arr, arr))
end

file = File.new("A-large-practice.in", "r")
output = File.open("A-large-practice.out", "w") do |f|
num_lines = file.gets.to_i
for counter in 1..num_lines
solution = solve(file.gets)
f.write("Case ##{counter}: #{solution}n")
#puts "Case ##{counter}: #{solution}"
end
end
file.close
``````

Time to solve:

• `A-small-practice.in` - 5.7ms

• `A-large-practice.in` - 15.1ms