我目前正在研究代码字节系列,以便更好地掌握Ruby编程。也许这只是他们站点中的一个bug (我不知道),但是我的代码在其他地方都适用于我,除了代码字节。
该方法的目的是返回任何输入数组中的第二最小和第二大元素。
代码:
def SecondGreatLow(arr)
arr=arr.sort!
output=[]
j=1
i=(arr.length-1)
secSmall=''
secLarge=''
while output.length < 1
unless arr.length <= 2
#Get second largest here
while (j<arr.length)
unless arr[j]==arr[j-1]
unless secSmall != ''
secSmall=arr[j]
output.push(secSmall)
end
end
j+=1
end
#get second smallest here
while i>0
unless arr[i-1] == arr[i]
unless secLarge != ''
secLarge=arr[i-1]
output.push(secLarge)
end
end
i-=1
end
end
end
# code goes here
return output
end
# keep this function call here
# to see how to enter arguments in Ruby scroll down
SecondGreatLow(STDIN.gets)输出
问题是,我得到了0分,这告诉我,我的输出是不正确的每一个测试。然而,当我实际投入任何输入时,它就给出了我所期望的输出。有人能帮忙解决问题吗?谢谢!
多亏了@pjs下面的回答,更新了,我意识到这可以用几行代码来完成:
def SecondGreatLow(arr)
arr=arr.sort!.uniq
return "#{arr[1]} #{arr[-2]}"
end
# keep this function call here
# to see how to enter arguments in Ruby scroll down
SecondGreatLow(STDIN.gets) 发布于 2014-06-24 14:59:33
密切注意问题的规范是很重要的。Coder字节说,输出应该是由空格分隔的值,即字符串,而不是数组。请注意,他们甚至在“正确的样本输出”周围加上引号。
撇开规范不说,您正在做way太多的工作来实现这一点。一旦数组被排序,您所需要的就是第二个元素、一个空格和第二个到最后一个元素。提示: Ruby允许数组的正索引和负索引。将它与.to_s和string连接结合起来,这应该只需要几行。
如果您担心最大值和最小值的非唯一数字,则可以在排序后使用.uniq对数组进行调整。
发布于 2014-11-07 18:43:28
您需要检查数组何时只包含两个元素的条件。以下是完整的代码:
def SecondGreatLow(arr)
arr.uniq!
arr.sort!
if arr.length == 2
sec_lowest = arr[1]
sec_greatest = arr[0]
else
sec_lowest = arr[1]
sec_greatest = arr[-2]
end
return "#{sec_lowest} #{sec_greatest}"
endhttps://stackoverflow.com/questions/24389355
复制相似问题