最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - Javascript even and odd range - Stack Overflow

programmeradmin4浏览0评论

I an trying to solve an online quiz but i don't seem to be able to pass all the tests. here is the question

Given two numbers X and Y, write a function that: 1 returns even numbers between X and Y, if X is greater than Y else it returns odd numbers between x and y For instance, take the integers 10 and 2 . the function would return all the even numbers between 2 and 10.

Examples:

12, 0 => [2,4,6,8,10]

2, 12 => [3, 5, 7, 9, 11]

0, 0 => [ ]

Here is my code:

    function number_game(x, y){
      let numbers = [];

      if (x > y){
        for (let i = y; i <= x; i++){
          if (i > y){
            numbers.push(i);
          }
        }
      }else{
        for (let i = x; i <= y; i++){
          if (i > x){
            numbers.push(i);
        }
      }
    }

      const result = numbers.filter(function(num){
        return x > y ? num % 2 === 0: num % 2 === 1;
      });
      return result;
  }

I an trying to solve an online quiz but i don't seem to be able to pass all the tests. here is the question

Given two numbers X and Y, write a function that: 1 returns even numbers between X and Y, if X is greater than Y else it returns odd numbers between x and y For instance, take the integers 10 and 2 . the function would return all the even numbers between 2 and 10.

Examples:

12, 0 => [2,4,6,8,10]

2, 12 => [3, 5, 7, 9, 11]

0, 0 => [ ]

Here is my code:

    function number_game(x, y){
      let numbers = [];

      if (x > y){
        for (let i = y; i <= x; i++){
          if (i > y){
            numbers.push(i);
          }
        }
      }else{
        for (let i = x; i <= y; i++){
          if (i > x){
            numbers.push(i);
        }
      }
    }

      const result = numbers.filter(function(num){
        return x > y ? num % 2 === 0: num % 2 === 1;
      });
      return result;
  }
Share Improve this question asked Oct 2, 2018 at 20:01 Oparah DimkpaOparah Dimkpa 391 silver badge4 bronze badges 5
  • 1 Do you have info on what tests are failing? Why do you push every number between x and y to the numbers array? Why not only fit the ones that pass the appropriate test? – Jake T. Commented Oct 2, 2018 at 20:07
  • 1 Why don't you check the oddness or evenness in the loops that push the numbers, instead of using filter afterward? – Barmar Commented Oct 2, 2018 at 20:07
  • I am a newbie and i just want to get a different perspective on how you would solve it or a hint – Oparah Dimkpa Commented Oct 2, 2018 at 20:08
  • 1 Also, I suggest you do an on paper run through with the values [2, 2], see what happens. – Jake T. Commented Oct 2, 2018 at 20:08
  • 2 The examples in the problem statement show that x and y should not be included in the results. Your code will include them. – Barmar Commented Oct 2, 2018 at 20:08
Add a ment  | 

6 Answers 6

Reset to default 2

While not written optimally, your code is essentially OK, except that it includes the higher number in the result. You're skipping the lower number with your if (i > y) test, although it would be simpler to just start your loop at y + 1.

To exclude the higher number, simply change the repetition criteria from <= to <.

It would also be simpler to perform the even or odd test in those loops.

function number_game(x, y) {
  let numbers = [];

  if (x > y) {
    for (let i = y + 1; i < x; i++) {
      if (i % 2 == 0) {
        numbers.push(i);
      }
    }
  } else {
    for (let i = x + 1; i < y; i++) {
      if (i % 2 == 1) {
        numbers.push(i);
      }
    }
  }

  return numbers;
}

console.log(number_game(12, 0));
console.log(number_game(2, 12));
console.log(number_game(0, 0));
console.log(number_game(3, 13));
console.log(number_game(1, 1));

Because I'm such a damn sucker for code golfing:

const number_game = (x, y) => {
  const min = Math.min(x, y), max = Math.max(x, y);

  return Array.from(Array(max - min), (_, i) => i + min).slice(1)
    .filter(v => v % 2 == (x < y));
};

Perhaps something like this could help.

function number_game(x, y) {
      let result = [];
      let min=0, max=0;
      if(x==y) {
        return result;
      } else if (x > y) {
          min = y;
          max = x;
      } else {
          min = x;
          max = y;
      }
      
        for (let i = min; i <= max; i++){
          if (i%2===0 && x > y && i!=min && i!=max) {
            result.push(i);
          }
          if (i%2===1 && x < y && i!=min && i!=max) {
            result.push(i);
          }
        }

      return result;
  }
  console.log(number_game(12,0));
  console.log(number_game(2,12));
  console.log(number_game(0,0));
  console.log(number_game(13,1));
  console.log(number_game(3,13));
  console.log(number_game(1,1));
  console.log(number_game(1,1000));
  console.log(number_game(3,1300));

Instead of generating all the numbers, and then filtering them, you can generate just the numbers that you need:

function number_game(x, y) {  
  const start = Math.min(x, y);
  const end = Math.max(x, y);
  const base = x > y ? 2 - start % 2 : start % 2 + 1; // how much you need to add, to get from start to the first number in the result
  const numbers = [];
  
  for(let i = start + base; i < end; i+= 2) numbers.push(i);
  
  return numbers;
}

console.log(JSON.stringify(number_game(9, 1)));
console.log(JSON.stringify(number_game(1, 9)));
console.log(JSON.stringify(number_game(12, 2)));
console.log(JSON.stringify(number_game(2, 12)));
console.log(JSON.stringify(number_game(12, 1)));
console.log(JSON.stringify(number_game(1, 12)));
console.log(JSON.stringify(number_game(2, 2)));

function returnOddOrEven(x,y){

// return empty array if both x and y are equal to 0

let mixedArr = [];
if (x ===0 && y===0){
   return [];
}


// first condition of x greater than y
else if ( x > y){
   for (var i = 1; i < x; i++){
         if( i % 2 === 0){
           mixedArr.push(i)
         }
   }
   }

   // second condition of y > x
   else if( y > x){
     for (var i = 1; i < y; i++){
         if(i > 1 && i % 2 === 1){
           mixedArr.push(i)
         }
   }

}

return mixedArr;
} 
function number_game(x, y) {
    var numArray = new Array();
    if (x > y) {
        for (i=y+1; i<x; i++) {
            if (i%2 == 0) {
                numArray[numArray.length] = i;
            }
        }
    } else {
        for (i=x+1; i<y; i++) {
            if (i%2 != 0) {
                numArray[numArray.length] = i;
            }
        }
    }
    return numArray;
}
发布评论

评论列表(0)

  1. 暂无评论