I'm trying to work through the following exercise. There is a problem with my code but I don't understand what it is... Using the JavaScript language, 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. My code:
function ArithGeo(arr) {
if (for (i = 0; i< (arr.length - 2); i++) {
arr[i+1] - arr[i] == arr[i+2] - arr[i+1];
}){
return "Arithmetic";
} else if (for (i = 0; i< (arr.length - 2); i++) {
arr[i+1] / arr[i] == arr[i+2] / arr[i+1];
}){
return "Geometric";
} else {
return -1;
}
};
When I put an array like [5,10,15], I get "Unexpected token for". Any ideas?
Modified your code. Didn't change the logic, but the way it should be written.
function ArithGeo(arr) {
var ap, gp;
for (i = 0; i< (arr.length - 2); i++)
if(!(ap = arr[i+1] - arr[i] == arr[i+2] - arr[i+1])) break;
if(ap) return "Arithmetic";
for (i = 0; i< (arr.length - 2); i++)
if(!(gp = arr[i+1] / arr[i] == arr[i+2] / arr[i+1])) break;
if(gp) return "Geometric";
return -1;
};