boofighter
boofighter

Reputation: 171

While loop with if statements doesn't work

I'm solving some coderbyte.com challenges and I run into some problems. This is the task:

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.

function ArithGeo(arr) { 
      var x = 0;
      var s = 0;
      var allObjects = [];
      for(var i=0; i<arr.length;i++) {
        while(x<arr.length-1) {
          var diff = arr[x+1]-arr[x];
          allObjects.push(diff);
          x++;
        }
        
       while(s<allObjects.length) {
          console.log(allObjects.length);
         
          if(allObjects[s]===allObjects[s+1]) {
            console.log('entered if');
            return "Arithmetic";
            s++;
            
          }
          else if(allObjects[s+1]%allObjects[s]===0) {
            return "Geometric";
            s++;
          }
          else {
            return "-1";
            s++;
          }
         }
        
        
       
      }
             
    }
       
    // keep this function call here 
    // to see how to enter arguments in JavaScript scroll down
    ArithGeo([1,2,3,100]);    

It enters into first if statement only once, and it should enter 3 times, for every element in allObjects array. Can you tell me why this is?

Upvotes: 2

Views: 2610

Answers (1)

Matyas
Matyas

Reputation: 13702

The problem is that return breaks function execution, and nothing else is executed afterwards.

var f = function () {
    these();
    things = will + be * 3;
    executed();
    return 4;
    while(anything) {
        after++;
        a = "return statement";
        won = 't';
    }
};
f();

Wild guess: maybe continue will help you out (jumps to the next iteration)

Upvotes: 4

Related Questions