Skip to content

Instantly share code, notes, and snippets.

@strychemi
Created January 18, 2016 08:55
Show Gist options
  • Select an option

  • Save strychemi/a03a79c6b0e9deb5ae72 to your computer and use it in GitHub Desktop.

Select an option

Save strychemi/a03a79c6b0e9deb5ae72 to your computer and use it in GitHub Desktop.
# have a phone number to letter group mapping
TELEBET = ["0", "1", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"]
# all completed mnemonics will be saved here
@mnemonic_list = []
# recursive method
# ARGUMENTS:
# number is the string of digits
# digit is the current digit being added to the mnemonic, initially set to 0
# and mnemonic is the sequence being built, initially set to empty string
def phone_mnemonics(number, digit=0, mnemonic="")
# base case: if all digits are processed,
# mnemonic is complete, and add to list
if digit == number.length
@mnemonic_list << mnemonic
else
# try all possible letters for this digit
TELEBET[number[digit].to_i].split("").each do |letter|
# recurse, sending the next call the current trial letter
# along with the next digit to be processed
phone_mnemonics(number, digit + 1, mnemonic + letter)
end
end
end
#test run
phone_mnemonics("248")
puts @mnemonic_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment