首页 > 解决方案 > 为什么我的代码可以在一种环境中工作,而不能在另一种环境中工作?

问题描述

我在 Codewars 上做一个 kata。我应该编写一个函数,它返回哪个数字的索引,与其他数字不同,均匀度(即 [1, 2, 4] 应该返回 0)。我相信我有一个解决方案,并且在复制/粘贴代码时证明是正确的,并且 console.logging 在 freecodecamps 实时服务器上,但是,当我尝试运行它编写的代码时,它只通过了一个测试。这里出了什么问题?

我已经尝试使用 console.logs 进行测试,并且我的解决方案成立。我知道我可以只使用过滤器来解决问题,但我不想练习基础知识。

let odd = [];
let even = [];

function isEven(num) {
  if (num % 2 === 0) {
    return true;
  } else {
    return false;
  }
}

function iqTest(numbers) {
  let nums = numbers.split(' ').map(function(item) {
    return parseInt(item, 10);
  })

  for (let i in nums) {
    if (isEven(nums[i])) {
      even.push(nums[i])
    } else {
      odd.push(nums[i])
    }
  }

  if (even.length > odd.length) {
    return nums.indexOf(odd[0]) + 1;
  } else {
    return nums.indexOf(even[0]) + 1;
  }
}

该函数应该接受一串数字,其中一个既不是偶数也不是奇数,然后返回该数字的索引 + 1。

标签: javascript

解决方案


您可以采用评论中提到的方法并搜索至少一个奇数和一个偶数以及一个附加项目,至少三个项目,如果找到此组合,请提前退出。

无需预先转换值,因为使用isEven函数的余数运算符将值转换为数字。

为了更快的返回值,存储索引而不是值并省略以后的indexOf搜索。

function isEven(i) { return i % 2 === 0; }

function iqTest(numbers) {
    var even = [], odd = [], values = numbers.split(' ');
    for (let i = 0; i < values.length; i++) {
        (isEven(values[i]) ? even : odd).push(i);
        if (even.length && odd.length && even.length + odd.length > 2)
            return (even.length < odd.length ? even : odd)[0] + 1;
    }
}

console.log(iqTest("1 2 4"));     // 1
console.log(iqTest("2 4 7 8 10")) // 3
console.log(iqTest("1 2 1 1"));   // 2


推荐阅读