我目前正在编写Coderbyte系列,以便更好地使用Ruby编程。也许这只是他们网站中的一个错误(我不知道),但除了Coderbyte之外,我的代码也适用于其他地方。
该方法的目的是返回任何输入数组中的第二个最小和第二个最大元素。
代码:
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)
答案 0 :(得分:2)
密切关注问题的规范是非常重要的。 Coderbyte说输出应该是由空格分隔的值,即字符串,而不是数组。请注意,他们甚至在&#34;正确的样本输出&#34;。
周围加上引号除此之外,您正在做方式过多的工作来实现这一目标。对数组进行排序后,您只需要第二个元素,空格和倒数第二个元素。提示:Ruby允许数组的正负索引。将其与.to_s
和字符串连接相结合,这应该只需几行。
如果您担心max和min的非唯一数字,可以在排序后使用.uniq
修剪数组。
答案 1 :(得分:0)
您需要检查数组何时只包含两个元素的条件。这是完整的代码:
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}"
end