Recursive Function Game

To return "You Win!", which value should you choose for entry ?

1
2
3
4
5
6
7
def playGame(entry):
    if entry == 0:
        return "You Lose!"
    elif entry == 1:
        return "You Win!"
    else:
        return playGame(entry - 4)

103 100 101 102

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

2 solutions

Alexander Lin
Oct 1, 2015

I don't know much about computer science, but basically it says its going to keep looping when it says return playGame (entry-4) and subtract 4 from your number every time it loops until it gets either 1 or 0. Therefore, you want to choose a number that can be divided by 4 and have a remainder of 1 so you win :)

Yes, basically any positive integer x x which satisfies x 1 ( m o d 4 ) x\equiv 1\pmod{4} is a suitable candidate for entry to return "You Win!".

Similarly, any non-negative integer y y which satisfies y 0 ( m o d 4 ) y\equiv 0\pmod{4} is a suitable candidate for entry to return "You Lose!".

Prasun Biswas - 5 years, 8 months ago

i thought that just needs to press 1 at the end =)

Cisco Wicaksana - 5 years, 5 months ago
Raif Harik
May 20, 2021

const playGame = (e) => { if (e <= 0) { return false; } return e === 1 || playGame(e - 4) } console.log(playGame(102))

I can't get that to format. Sorry.

This is a simple recursive function. if the entry is less then or equal to 0 you have lost. If the entry equals 1 then you have won. If the number is greater that 1 subtract 4 and play again. A recursive function typically has a check for the desired end state which if satisfied exits the recursion. If it is not satisfied it makes an adjustment and calls it's self.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...