A Wolf In Sheep's Clothing 8Kyu CodeWars

·

2 min read

Here's a link to the CodeWars challenge.

Challenge:

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:

If the wolf is the closest animal to you, return "Pls go away and stop eating my sheep". Otherwise, return "Oi! Sheep number N! You are about to be eaten by a wolf!" where N is the sheep's position in the queue.

Note: there will always be exactly one wolf in the array.

Breaking it down:

First we start with the function warnTheSheep. Queue is an array of sheep numbers in order of arrival.

Assign the queue to orderedQueue and reverse the order of the array, in order to compare the first element to the last element in the array:

Loop through the queue and check if the wolf is in the queue:

If the wolf is in the queue, return the message "Pls go away and stop eating my sheep":

Else if the wolf is not in the queue, return the message with the sheep number in the queue and the wolf number in the queue (indexOf):

And here is my full solution: