简体   繁体   中英

Why does my code work in one environment, but not in another?

I'm doing a kata on Codewars. I'm supposed to write a function that returns the index of which number, is not like the others, in evenness(ie [1, 2, 4] should return 0). I believe I have a solution, and it proves true when copy/pasting the code, and console.logging on freecodecamps live server, however, when i try to run the code where it is written, it only passes one test. What is going wrong here?

I've tried testing with console.logs, and my solution holds. I know I could just use filter to solve the problem, but i wan't to practice fundamentals.

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

The function should accept a string of numbers, one of which will not be either even or odd, then return the index of that number + 1.

You could take the in comments mentioned approach and search for at least one odd and one even and one additional item, at least three items and exit early if this combination is found.

No need to convert the values in advance, because the value get converted to number by using the remainder operator of isEven function.

For a faster return value store the index instead of the value and omit a later indexOf seach.

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM