Ruby Project Euler Q22:为什么根据删除引号的时间得到不同的结果?
如果我运行这个,为什么会这样:Ruby Project Euler Q22:为什么根据删除引号的时间得到不同的结果?,ruby,Ruby,如果我运行这个,为什么会这样: get_score = proc{ |word, position| val = 0 word[1..-2].each_byte do |c| val = val + (c.ord - 64) end name_score = val*(position+1) } puts File.read("names.txt").split(',').sort.map.with_index(&get_score).inject(:+) g
get_score = proc{ |word, position|
val = 0
word[1..-2].each_byte do |c|
val = val + (c.ord - 64)
end
name_score = val*(position+1)
}
puts File.read("names.txt").split(',').sort.map.with_index(&get_score).inject(:+)
get_score = proc{ |word, position|
val = 0
word.each_byte do |c|
val = val + (c.ord - 64)
end
name_score = val*(position+1)
}
puts File.read("names.txt").gsub('"','').split(',').sort.map.with_index(&get_score).inject(:+)
我得到了答案:871193872
但如果我运行这个:
get_score = proc{ |word, position|
val = 0
word[1..-2].each_byte do |c|
val = val + (c.ord - 64)
end
name_score = val*(position+1)
}
puts File.read("names.txt").split(',').sort.map.with_index(&get_score).inject(:+)
get_score = proc{ |word, position|
val = 0
word.each_byte do |c|
val = val + (c.ord - 64)
end
name_score = val*(position+1)
}
puts File.read("names.txt").gsub('"','').split(',').sort.map.with_index(&get_score).inject(:+)
我得到这个:871190344
(不同之处在于,在第二个示例中,我使用gsub删除引号,但在第一个示例中,我一直保留引号,直到我使用word[1..-2]只遍历引号之间的字符)
在第三个版本中,它使用scan(/\w+/)搜索空白,即使文件中没有空白,但这是一个给出正确答案的版本:
names = File.open('names.txt').read.scan(/\w+/).sort
puts names.map { |name|
word_score = name.each_byte.map { |c| c - 64 }.reduce(:+)
(names.index(name) + 1) * word_score
}.reduce(:+)
编辑:
以下是示例数据:恐怕您复制并粘贴了输入文件或类似的内容,而没有保存它。我尝试了你的两个代码,它们工作得很好:
$ ruby p22.rb
87119XX82
87119XX82
现在,如果你问我将如何编写它(你没有:-),让我们保留抽象get_score
,但稍微重构一下:
indexes = Hash[("A".."Z").map.with_index(1).to_a]
get_score = proc { |word, idx| indexes.values_at(*word.chars).reduce(:+) * idx }
sorted_names = File.read("names.txt").delete('"').split(',').sort
solution = sorted_names.map.with_index(1, &get_score).reduce(0, :+)
. 实际上,潜在的回答者必须追踪样本数据以帮助您。关于第三个问题,
scan(/\w+/)
不查找“空白”,而是查找“单词字符(字母、数字、下划线)”的运行,这将从计算中删除逗号和引号,我会选择delete(“”)
或tr(“”,”)
。两者都可能比gsub(“,”)
快。