1

该问题与摩尔斯电码有关:

# Build a function, `morse_encode(str)` that takes in a string (no
# numbers or punctuation) and outputs the morse code for it. See
# http://en.wikipedia.org/wiki/Morse_code. Put two spaces between
# words and one space between letters.
#
# You'll have to type in morse code: I'd use a hash to map letters to
# codes. Don't worry about numbers.
#
# I wrote a helper method `morse_encode_word(word)` that handled a
# single word.
#
# Difficulty: 2/5

describe "#morse_encode" do
  it "should do a simple letter" do
    morse_encode("q").should == "--.-"
  end

  it "should handle a small word" do
    morse_encode("cat").should == "-.-. .- -"
  end

  it "should handle a phrase" do
    morse_encode("cat in hat").should == "-.-. .- -  .. -.  .... .- -"
  end
end

我的解决方案是

MORSE_CODE = {
  "a" => ".-",
  "b" => "-...",
  "c" => "-.-.",
  "d" => "-..",
  "e" => ".",
  "f" => "..-.",
  "g" => "--.",
  "h" => "....",
  "i" => "..",
  "j" => ".---",
  "k" => "-.-",
  "l" => ".-..",
  "m" => "--",
  "n" => "-.",
  "o" => "---",
  "p" => ".--.",
  "q" => "--.-",
  "r" => ".-.",
  "s" => "...",
  "t" => "-",
  "u" => "..-",
  "v" => "...-",
  "w" => ".--",
  "x" => "-..-",
  "y" => "-.--",
  "z" => "--.."
}

def morse_encode(str)
  arrayer = str.split(" ")
  combiner = arrayer.map {|word| morse_encode_word(word) }
  combiner.join("  ")
end

def morse_encode_word(word)
    letters = word.split("")

  array = letters.map {|x| MORSE_CODE[x]}

  array.join(" ")
end

morse_encode("cat in hat")
morse_encode_word("cat in hat")

为什么 morse_encode 和 morse_encode_word 返回完全相同的输出?

我创建它的方式,我认为会有间距差异。

4

2 回答 2

6

当您将短语传递到morse_encode_word时,它会按字母将其拆分(即't i'变为['t', ' ', 'i']。接下来,将此数组映射到['-', nil, '..'](因为MORSE_CODE[' '] == nil)。

然后你用空格加入它,'-' + ' ' + '' + ' ' + '..'(因为nil.to_s == '')。所以你得到的字符串里面有两个空格,'- ..'.

于 2013-05-29T17:50:24.260 回答
2

When you do morse_encode_word you are not getting rid of spaces... So it will split your words, but keep the space.

In morse_encode you get rid of the space (because of split), but you add it back in when you do the join. So it ends up being the same as morse_encode_word.

I would guess that what you want is no extra spaces in morse_encode_word. Just do a check to make sure x is not a space before you map it in morse_encode_word.

Try to use reject:

def morse_encode_word(word)
  letters = word.split("")

  array = letters.reject{|x| x == " "}.map{|x| MORSE_CODE[x]}

  array.join(" ")
end
于 2013-05-29T18:02:36.477 回答