Saturday, August 31, 2013

Coderbyte: Second GreatLow (Ruby)

PROBLEM

Have the function SecondGreatLow(arr) take the array of numbers stored in arr and return the second lowest and second greatest numbers, respectively, separated by a space. For example: if arr contains [7, 7, 12, 98, 106] the output should be 12 98. The array will not be empty and will contain at least 2 numbers. It can get tricky if there's just two numbers!.

SOLUTION

def SecondGreatLow(arr) 
    highest = arr.max
    lowest = arr.min
    second_highest = 0
    second_lowest = 0
    
    arr.sort!.each do |number|
        second_highest = number if number < highest
        second_lowest = number if number != lowest and second_lowest == 0
    end
    
    arr.count == 2 ? "#{arr.sort[1]} #{arr.sort[0]}" : "#{second_lowest} #{second_highest}"
end

print SecondGreatLow(STDIN.gets)