In this challenge, you'll be given an array with a length of at least three, containing (possibly quite large) integers. The array is either comprised of entirely odd integers or even integers with one exception. Write a method that returns the integer that is not like the others.
Example:
findOutlier([2, 4, 0, 100, 4, 11, 2602, 36])
=> 11
Additional practice arrays:
[160, 3, 1719, 19, 11, 13, -21]
[4, 8, 15, 16, 24, 42]
[16, 6, 40, 66, 68, 28]
Good luck, happy coding~!
This challenge comes from user obnounce. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Latest comments (31)
this only iterates the array 3 times, and with that you can know if the number is even or odd and with the find it will only iterate until it finds it, when it finds it it will stop and so I will not have to iterate over the array in case it has 10000000000 elements and it is in a close position.
what do you guys think?
Go:
Here is the simple solution with PHP:
Python
Erlang.
Python :
Not elegant, but it'll do the job.
Here's my code:
I believe I could have used filters on the arrays method but just decided to follow the long step.
Here's my code:
I believe I could have used filters on the arrays method but just decided to follow the long step.
Here's my code:
I believe I could have used filters on the arrays method but just decided to follow the long step.
Ruby Language
With specs!
output
array = [500,502,1002,1234,601]
odd = even = i = 0
oddValue = evenValue = 0
a = len(array)
while (i < a):
if (array[i] % 2):
oddValue = array[i]
odd += 1
else:
evenValue = array[i]
even += 1
i += 1
if (odd > even == 1):
print(evenValue)
elif (odd == 1):
print(oddValue)
else:
print("Wrong list of numbers")
array = [500,502,1002,1234,601]
odd = even = i = 0
oddValue = evenValue = 0
a = len(array)
while (i < a):
if (array[i] % 2):
oddValue = array[i]
odd += 1
else:
evenValue = array[i]
even += 1
i += 1
if (odd > even == 1):
print(evenValue)
elif (odd == 1):
print(oddValue)
else:
print("Wrong list of numbers")
This is my proposal:
In this case, Array.find will stop looping when both the even and odd arrays have at least one item.
There is only one loop on the array values, and this loop stops just when the "strange element" is found.
At the end, the group with just one element has the solution.
In the last test, an array formed entirely by even numbers, null is returned.
With JS
Explanation:
even
andodd
numbers.Dart solution:
Link to the online playground: dartpad.dartlang.org/d5e83e228c72d...
ruby 2.7