Codewars A wolf in sheep’s clothing – Easy Solution Javascript (8 kyu)

This is the solution for the Codewars A wolf in sheep’s clothing question in Javascript with a simple & easy to understand code and explanation.

Task:

Wolves have been reintroduced to Great Britain. You are a sheep farmer, and are now plagued by wolves which pretend to be sheep. Fortunately, you are good at spotting them.

Warn the sheep in front of the wolf that it is about to be eaten. Remember that you are standing at the front of the queue which is at the end of the array:

[sheep, wolf, sheep, sheep]      (YOU ARE HERE AT THE FRONT OF THE QUEUE)
  3            2      1

Here’s the link to the kata – A wolf in sheep’s clothing

Solution to A wolf in sheep’s clothing Question:

The simple solution to the ‘A wolf in sheep’s clothing’ question is to first reverse the given array and search for the string “wolf” and store that position in a variable, that is the position of the sheep that’s about to be eaten (as the array starts from 0). So, if the position is 0 that means, the wolf won’t be able to eat any sheep, otherwise return the position of the sheep.

//solution style 1

function warnTheSheep(queue) {
  let location;
  queue.forEach((x,i)=>{x == 'wolf' ? location=queue.length-i : 0});

  return location == 1 ? "Pls go away and stop eating my sheep" : `Oi! Sheep number ${location-1}! You are about to be eaten by a wolf!`; 
}
//solution style 2

function warnTheSheep(queue) {
  const position = queue.reverse().indexOf('wolf');

  return position === 0 ? 'Pls go away and stop eating my sheep' : `Oi! Sheep number ${ position }! You are about to be eaten by a wolf!`;
}

Leave a Comment