Created
December 5, 2021 16:17
-
-
Save vvenv/eaa60cc4aec5be89ef7f07cd1edf3888 to your computer and use it in GitHub Desktop.
Solution for Bunny Question in "Coding Interview with Dan Abramov"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://www.youtube.com/watch?v=XEt09iK8IXs | |
let pos = 2; | |
let len = 4; | |
function jump() { | |
if (pos === 0) { | |
pos += 1 | |
} else if (pos === len - 1) { | |
pos -= 1 | |
} else { | |
if (Math.random() > 0.5) { | |
pos += 1 | |
} else { | |
pos -= 1 | |
} | |
} | |
} | |
let found = false; | |
console.log('first loop'); | |
for (let i=1; i<len-1; i++) { | |
console.log('attempt at', i, 'bunny at', pos); | |
if (i === pos) { | |
found = true; | |
console.log('found at', i); | |
break; | |
} | |
jump(); | |
} | |
if (!found) { | |
console.log('second loop'); | |
for (let i=len-2; i>0; i--) { | |
console.log('attempt at', i, 'bunny at', pos); | |
if (i === pos) { | |
found = true; | |
console.log('found at', i); | |
break; | |
} | |
jump(); | |
} | |
} | |
if (!found) { | |
console.log('not found!', 'bunny at', pos); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment