Question

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?

Was it helpful?

Solution

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;    
};

OTHER TIPS

It looks like you're trying to get the result of the for loop, but loops don't have return values. Consider defining a boolean variable (initially set to true) outside of the loop and AND it with the result of the comparison you perform inside the loop; the variable will be true at the end if each iteration of the loop ANDs true to it.

For example:

var test = true;
for(var i=0; i<5; i++) {
     test = test && ( i != 6 );
 }
 if(test) {
     alert("i was never 6");
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top