...

/

Solution: Google Labs Aptitude Test (Recursion)

Solution: Google Labs Aptitude Test (Recursion)

Go over the recursive solution for the google labs aptitude test.

We'll cover the following...

Solution

# Note: depending on your computer's speed, it might take between 5 - 10 minutes
lst = ['w','d','o','t','g','l','e','c','m']
@is_checked = {0 => false, 1 => false, 2 => false, 3 => false, 4 => false, 5 => false, 6 => false, 7 => false, 8 => false, 9 => false }

def str_to_int(a, d)
	d.each do |k, v| 
		a = a.gsub(k,v)	
	end	
	a.to_i
end

def check_ans(letter_to_digits)
	a = str_to_int('wwwdot', letter_to_digits)
	b = str_to_int('google', letter_to_digits)
	c = str_to_int('dotcom', letter_to_digits)
	# puts "[DEBUG] Checking #{a} - #{b} = #{c}"
	if a - b == c
		puts "#{a} - #{b} = #{c}"
		puts letter_to_digits
	end
end

def find_out(letter_to_digits, lst, idx)
	if idx == 9
		check_ans(letter_to_digits)
		return
	end
	
	(0..9).each do |i| 
		next if i == 0 and (lst[idx] == 'w' or lst[idx] == 'd' or lst[idx] == 'g')

		unless @is_checked[i]
			@is_checked[i] = true  # the number is used
			letter_to_digits[lst[idx]] = i.to_s
			find_out(letter_to_digits, lst, idx + 1)
			@is_checked[i] = false # clear
		end
		
	end
end
puts "Processing your request, it may take upto 5 minutes."
start_time = Time.now
letter_to_digits = {}
find_out(letter_to_digits, lst, 0)
puts "Time to solve: #{Time.now - start_time} seconds"

# time: 49 seconds
Solving Google labs aptitude test using recursion

Explanation

  • Line 2–3: A list of all the unique letters used in this puzzle is created, and a hash map to keep track of the values assigned to each letter.

  • Lines 5–10: The str_to_int ...