所以我发现我可以通过散列来计算,问题是对于 7 和 9 我有四个值。我已经尝试了其他几件事但没有运气。有人可以帮助理解我还能做些什么来从哈希中获取我想要的值。我意识到我可以将数字与键匹配,但我对如何获得要排列的值感到困惑。
letters = {"1" => ["1", "1", "1"],
"2" => ["a", "b", "c"],
"3" => ["d", "e", "f"],
"4" => ["g", "h", "i"],
"5" => ["j", "k", "l"],
"6" => ["m", "n", "o"],
"7" => ["p", "q", "r", "s"],
"8" => ["t", "u", "v"],
"9" => ["w", "x", "y", "z"]}
phone_number = gets.chomp.to_s
words = []
word = []
numbers = phone_number.chomp.chars
count0 = 0
while count0 < 3
count1 = 0
while count1 < 3
count2 = 0
while count2 < 3
count3 = 0
while count3 < 3
count4 = 0
while count4 < 3
count5 = 0
while count5 < 3
count6 = 0
while count6 < 3
word[0] = letters[numbers[0]][count0]
word[1] = letters[numbers[1]][count1]
word[2] = letters[numbers[2]][count2]
word[3] = letters[numbers[3]][count3]
word[4] = letters[numbers[4]][count4]
word[5] = letters[numbers[5]][count5]
word[6] = letters[numbers[6]][count6]
words << word.join
count6 += 1
end
count5 += 1
end
count4 += 1
end
count3 += 1
end
count2 += 1
end
count1 += 1
end
count0 += 1
end
puts words
编辑:
我想要一个七位数并打印出所有可能的字母组合。我是初学者,所以我想用我现在知道的东西来理解。我想尝试使用 if
语句执行此操作。
numbers = phone_number.chomp.chars
if letters.key?(numbers[0])
if letters.key?(numbers[1])
if letters.key?(numbers[2])
if letters.key?(numbers[3])
if letters.key?(numbers[4])
if letters.key?(numbers[5])
if letters.key?(numbers[6])
end
end
end
end
end
end
end
我了解如何从匹配的键中获取值,但不明白如何在处理其余值的同时保留第一个值(如果这有意义的话)。
最佳答案
product
是您正在寻找的功能,以下适用于任意数量的数字:
digits = '27'
keys = digits.chars.map{|digit|letters[digit]}
p keys.shift.product(*keys).map(&:join) #=> ["ap", "aq", "ar", "as", "bp", "bq", "br", "bs", "cp", "cq", "cr", "cs"]
关于ruby - 将电话号码转换成单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20367357/