geo or aritth

See if array is arithmetic [2,4,6,8] or geometric [2,4,8,16]. Return -1 if no pattern. Negative numbers may be entered as parameters, 0 will not, and no array will contain all the same elements.

by Jason Land

JavaScript

//see if array is arithmetic [2,4,6,8] or geometric [2,4,8,16]. Return -1 if no pattern. Negative numbers may be entered as parameters, 0 will not, and no array will contain all the same elements. 
function ArithGeo(AorGArray) {
    var constantSub = AorGArray[1] - AorGArray[0];
    var constantDiv = AorGArray[1] / AorGArray[0]; //5

    for (i = 0; i < AorGArray.length - 2; i++) {
        var cTest = AorGArray[i + 2] - AorGArray[i + 1];
        if (cTest == constantSub) {
            alert("Arithmetic");
            return Arithmetic;
        }
    }
    for (j = 0; j < AorGArray.length - 2; j++) {
        var kTest = AorGArray[j + 2] / AorGArray[j + 1];
        if (kTest == constantDiv) {
            alert("Geometric");
            return Geometric;
        }
    }
    alert(-1);
    return -1;

}

ArithGeo([2, 3, 4, 5, 6]);