Saturday, August 31, 2013

Coderbyte: Arith Geo (Ruby)

PROBLEM

Have the function ArithGeo(arr) take the array of numbers stored in arr and return the string "Arithmetic" if the sequence follows an arithmetic pattern or return "Geometric" if it follows a geometric pattern. If the sequence doesn't follow either pattern return -1. An arithmetic sequence is one where the difference between each of the numbers is consistent, where as in a geometric sequence, each term after the first is multiplied by some constant or common ratio. Arithmetic example: [2, 4, 6, 8] and Geometric example: [2, 6, 18, 54]. Negative numbers may be entered as parameters, 0 will not be entered, and no array will contain all the same elements.

SOLUTION

def ArithGeo(arr)
    common_difference = arr[0].to_i - arr[1].to_i
    common_ratio = arr[1].to_i / arr[0].to_i
    sequence_type = ""
    
    arr.each_with_index do |number, index|
        if arr[index].to_i -  arr[index+1].to_i != common_difference
            if arr.count-1 != index
                sequence_type = "!arithmetic"
            end
        end
    end

    if sequence_type != "!arithmetic"
        return "Arithmetic"
    else
        arr.each_with_index do |number, index|  
            if arr[index].to_i * common_ratio != arr[index+1].to_i
                if arr.count-1 != index
                    sequence_type = "!geometric"
                end
            end
        end
        if sequence_type != "!geometric"
            return "Geometric"
        end
    end   
    return "-1"
end

print ArithGeo(STDIN.gets)