这只是我在脑海中想出的一个随机场景,如果我有这个数组:
[3,2,5,6,7,8,9,1,2]和这个字符串:
'325678912'我应该用Ruby写什么代码,它会产生一个of:
3*2*5 = 30, 6*7*8 = 336, and 9*1*2 = 18 并将其放入一个数组中:
[30,336,18]抱歉,我忘了把返回错误答案的代码放进去:
b = [3,2,5,6,7,8,9,1,2]
first = 0
third = first + 2
array = []
while first<b.length
prod=1
b[first..third].each do |x|
prod*=x.to_i
array<<prod
end
first+=2
third = first + 2
end
print array和我的另一段字符串代码:
a = '325678912'
number = a.split('')
first = 0
third = first + 2
array = []
while first<number.length
prod=1
number[first..third].each do |x|
prod*=x.to_i
array<<prod
end
first+=2
third = first + 2
end
print array对于这两段代码,我得到的答案是: 3,6,30,5,30,210,7,56,504,9,9,18,2,我想要的是: 30,336,18
有人能告诉我我的代码出了什么问题吗?
提前谢谢你!
发布于 2013-10-10 22:35:07
使用Enumerable#each_slice
[3,2,5,6,7,8,9,1,2].each_slice(3).map { |a,b,c| a*b*c }
# => [30, 336, 18]
[3,2,5,6,7,8,9,1,2].each_slice(3).map { |x| x.reduce(:*) }
# => [30, 336, 18]使用String#chars将字符串转换为单字符字符串数组。然后使用上面的代码得到结果:
'325678912'.chars
# => ["3", "2", "5", "6", "7", "8", "9", "1", "2"]
'325678912'.chars.map(&:to_i)
# => [3, 2, 5, 6, 7, 8, 9, 1, 2]
'325678912'.chars.map(&:to_i).each_slice(3).map { |a,b,c| a*b*c }
# => [30, 336, 18]发布于 2013-10-11 00:16:37
你的代码,带注释。
b = [3,2,5,6,7,8,9,1,2]
first = 0
third = first + 2
array = []
while first<b.length
prod=1
b[first..third].each do |x|
prod*=x.to_i # to_i unnecessary, already integer
array<<prod # Ah no. Too early. move this outside the block
end
#Here would be fine.
#And don't forget to reset prod to 1.
first+=2 #3 ! not 2.
third = first + 2
end
print arrayhttps://stackoverflow.com/questions/19298710
复制相似问题