determine if array is arithmetic or geometric progression (from Coderbyte)
javascript
Solution
For arithmetic progression, subtract each element from previous element; their difference should be equal; for geometric, divide each element by the previous element, the ratio should stay the same. As for divide by zero when you meet 0, javascript gives you Inf (and it certainly is not a geometric progression). Because floats are inaccurate, maybe you'd want to store the min and max of these values and then see if they are close enough to each other.
function arithGeo(arr) {
var minRatio = 1/0,
maxRatio = -1/0,
minDiff = 1/0,
maxDiff = -1/0,
epsilon = 0.000001,
i,
ratio,
diff;
if (arr.length <= 2) {
return;
}
for (i = 1; i < arr.length; ++i) {
diff = arr[i] - arr[i - 1];
ratio = arr[i] / arr[i - 1];
minDiff = Math.min(diff, minDiff);
maxDiff = Math.max(diff, maxDiff);
minRatio = Math.min(ratio, minRatio);
maxRatio = Math.max(ratio, maxRatio);
}
if (Math.abs(minDiff - maxDiff) < epsilon) {
return "Arithmetic";
}
if (Math.abs(minRatio - maxRatio) < epsilon) {
return "Geometric";
}
return;
}
alert(arithGeo([3,9,15,21,27,28]));
alert(arithGeo([3,9,15,21,27]));
alert(arithGeo([4,2,1,0.5]));
Problem
Here is my functional code, as far as coderbyte is concerned. But I have a feeling it shouldn't be this complicated. Am I missing a simple trick? ``` function ArithGeo(arr) { var array_type = -1; if (arr.length <= 2) return true; var a = arr[1], r = a/arr[0], i; for (i = 2; i < arr.length; ++i) { if ((a *= r) == arr[i]){ array_type = "Geometric"; } else{ array_type = -1; break; } } if (array_type == "Geometric") return array_type; a = arr[1], d = a - arr[0], i; for (i = 2; i < arr.length; ++i) { if ((a += d) == arr[i]){ array_type = "Arithmetic"; } else { array_type = -1; break; } } return array_type; } ArithGeo([3,9,15,21,27, 28]); ```