Question: Given a finite number, find out all the possible strings that can be generated by using encoding found on old telephone keypad.
Example: 223 => bad, bae, aae...etc. ( since 2 = abc , 3 = def ... )
Answer: This is a simple recursion problem. We should recurse the loop for each possible character of every digit in given number and append the character to the output. As soon as output length is equal to the input length process/print it.
A small trick is to properly choose function argument, which should allow us to check the current length of the o/p and also the number of characters for current digits.
Code: Ruby code
$array = [" ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
def find_comb(input, length, index, out)
if index == length
for j in 0..($array[input[index].to_i].length-1)
out[index] = $array[input[index].to_i][j]
find_comb(input, length, index+1, out)
if ARGV.index('1') or ARGV.index('0')
p "0 and 1 are not allowed."
p "Syntax: ruby telephone.rb number"
find_comb(ARGV, ARGV.length, 0, "")
Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.