Find the stray number

Asked by At

Practicing some katas in Code Wars and ran into this "Find the stray number" - I thought this was a pretty simple exercise (thank God I am started to feel comfortable with these challenges), but I am failing one of the test. Not sure why I am failing the test, nor does the site give me any ideas of what the array is they are passing

Below is the code that I used - if anyone can help me out that would be great.

Here is the link to the challenge & question


https://www.codewars.com/kata/find-the-stray-number/train/javascript

You are given an odd-length array of integers, in which all of them are the same, except for one single number.

Complete the method which accepts such an array, and returns that single different number.

The input array will always be valid! (odd-length >= 3)

Examples
[1, 1, 2] ==> 2
[17, 17, 3, 17, 17, 17, 17] ==> 3

function stray(numbers) {
let strayChar = numbers[0];

 for(let i = 1; i < numbers.length; i++){
  if(strayChar !== numbers[i]){
  return strayChar = numbers[i];
   }
 }
       return 0;
 } 

3 Answers

0
DCR On

function stray(numbers) {
    //take first element
    let strayChar = numbers[0];

    // see if it is different from the next 2
    if (strayChar !== numbers[1] && strayChar !== numbers[2]) return strayChar;

    // if not find the first value that is different
    for(let i = 1; i < numbers.length; i++){
      if(strayChar !== numbers[i])return numbers[i];
    }
 }
 
 const data = [17, 17, 3, 17, 17, 17, 17];
 console.log(stray(data));

0
Bibberty On

Here, we do a find to find an element, using the evaluator filter and test is simple. Find an element that has a filtered array length of 1.

let testArrays = [[1, 1, 2], [17, 17, 3, 17, 17, 17, 17]];

function stray(numbers) {
  return numbers.find((e) => numbers.filter((v) => v===e).length === 1); 
} 

testArrays.forEach(arr => {
  console.log(stray(arr));
});

0
kemicofa On

You could do something like this by using Set, Map, Array#from, Array#slice, and Array#find.

Use Set to find the unique numbers in the list. Then simply only loop through the first 3 elements of the list. If one of the unique numbers has a count greater than 1, that means the other unique number must be the odd one.

const data = [17, 17, 3, 17, 17, 17, 17];

function stray(numbers){
  //find unique numbers and set their count to 0
  const map = new Map(Array.from(new Set(numbers)).map(v=>([v,0])));
  
  //take first three numbers from numbers array
  return Array.from(
      numbers.slice(0,3).reduce((a,c)=>{
        //update the count
        return map.set(c, map.get(c) + 1);
      }, map)
      //find the number with a count of 0 or 1
  ).find(([,v])=>v<=1)[0];
}

const res = stray(data);

console.log(res);

One of the more impressive solutions offered on code wars is:

const data = [17, 17, 3, 17, 17, 17, 17];
const stray = nums => nums.reduce((a, b) => a ^ b);


const res = stray(data);

console.log(res);