我目前正在通過Coderbyte系列,以更好地在Ruby編程。也許這只是他們網站上的一個錯誤(我不知道),但是除Coderbyte之外,我的代碼在其他地方都適用。Coderbyte Coderbyte CodeGo.net> 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)
輸出
- 輸入:[1,2,3,100] =>輸出:[2,3](正確)
- 輸入:[1 ,42,42,180] =>輸出:[42,42](正確)
- 輸入:[4,90] =>輸出:[90,4](正確)
問題是,我被授予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)
您的方法需要一個數組但是['STDIN.gets'](http://www.ruby-doc.org/core-2.1.2/IO.html#method- i-gets)返回一個字符串。 – Stefan
@Stefan你說得對,但是Coderbyte網站提供了測試數組的輸入示例。我繼續寫下一個解決方案,其中第一行是'arr = arr.split(/ [,] + /)。 n.to_i}如果arr.is_a?字符串「,並且似乎通過了他們的測試,無論輸入是字符串還是數組。 – pjs