Skip to content

Instantly share code, notes, and snippets.

@MonkeyAndres
Last active July 8, 2022 13:28
Show Gist options
  • Select an option

  • Save MonkeyAndres/3be5d27e8d06dc93af99047becb5c243 to your computer and use it in GitHub Desktop.

Select an option

Save MonkeyAndres/3be5d27e8d06dc93af99047becb5c243 to your computer and use it in GitHub Desktop.
Hopping rabbit kata.

Rabbit kata

There's a piece of land with N number of boxes and a rabbit. You're playing a guessing game with the rabbit, you have to guess in which box the rabbit is but before every guess the rabbit is going to jump either to the box on the left or the one on the right.

The function below implements the rabbit logic and allow you to perform guesses. You must write a function capable of finding the rabbit every time.

const startRabbitGame = (fieldLength) => {
  let rabbitPosition = Math.floor(Math.random() * fieldLength)

  console.log("Rabbit starting at: " + rabbitPosition)

  const moveRabbit = () => {
    if (rabbitPosition === 0) {
      rabbitPosition++
      return
    }

    if (rabbitPosition === fieldLength) {
      rabbitPosition--
      return
    }

    if (Math.random() > 0.5) {
      rabbitPosition++
    } else {
      rabbitPosition--
    }
  }

  const guess = (index) => {
    const prevPosition = rabbitPosition
    moveRabbit()

    console.log(`Rabbit hopped from ${prevPosition} to ${rabbitPosition}`)
    console.log(`> Guessing ${index}`)

    return rabbitPosition === index
  }

  return guess
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment