Last active
January 29, 2024 06:01
-
-
Save Cat7373/17bc7f095033bb715f422b972bf02496 to your computer and use it in GitHub Desktop.
逃离 Nami 小游戏
This file contains 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
// 原型 | |
逃离纳米 = callback => { | |
// 经典游戏: | |
// Nami 抓住了 200 名群员,为他们每个人分配了 1 ~ 200 的编号,然后准备了标有 1 ~ 200 编号的盒子,将标有 1 ~ 200 的球乱序放入盒子中 | |
// 每个人依次单独进入放盒子的房间,允许翻看最多 100 个盒子,若所有人都找到自己编号的球,则允许所有人离开,否则所有人都要葬身 Nami 腹中 | |
// 注:即使没有找到自己编号的球,游戏仍会继续下去,直到所有人都进完房间,才会得知可以离开还是被吃 | |
// 请发挥你的聪明才智,编写逃出率更高的代码吧! | |
// callback 会按顺序为每个编号的群员调用,参数为(群员编号, 开盒子(盒子编号)),开盒子函数会返回开出的球编号 | |
// 你的函数会自动用于进行 1000 轮游戏,并输出逃出率 | |
// 示例使用方式: > 逃离纳米((no, viewBox) => { viewBox(1); viewBox(2); viewBox(3); ... }) | |
const game = () => { | |
// 初始化盒子和球 | |
const boxes = [] | |
for (let i = 1; i <= 200; i++) boxes[i] = i | |
boxes.sort(() => Math.random() - .5) | |
// 翻看盒子的函数 | |
let gameWin = true // 当前局游戏是否胜利 | |
let peopleNo = 1 // 当前群员的编号 | |
let peopleWin = false // 当前群员是否找到了自己的球 | |
let viewCount = 0 // 当前群员看过的盒子数 | |
const viewBox = no => { | |
if (viewCount >= 100) throw '您的算法有误,翻看了太多次盒子' | |
if (no < 1 || no > 200) throw `您的算法有误,翻看了不存在的盒子${no}` | |
viewCount += 1 | |
const n = boxes[no - 1] // 数组索引从 0 开始 | |
if (n === peopleNo) peopleWin = true | |
return n | |
} | |
// 把每个人送入房间 | |
while (peopleNo <= 200) { | |
callback(peopleNo, viewBox) | |
if (!peopleWin) gameWin = false | |
peopleNo += 1 | |
peopleWin = false | |
viewCount = 0 | |
} | |
return gameWin | |
} | |
let win = 0 | |
const round = 1000 | |
for (let i = 0; i < round; i++) win += (game() ? 1 : 0) | |
return `在 ${round} 轮游戏中,您一共成功逃出 ${win} 次,逃出率 ${Math.floor(win / round * 10000) / 100}%!` | |
} | |
// 示例解法 | |
逃离纳米((no, viewBox) => { | |
let next = no | |
for (let i = 0; i < 100; i++) { | |
next = viewBox(next) | |
} | |
}) | |
// 示例解法 | |
逃离纳米((_, viewBox) => { | |
const boxes = [] | |
for (let i = 0; i < 100; i++) { | |
let next = 0 | |
while (next == 0 || boxes.includes(next)) { | |
next = Math.floor(Math.random() * 200 + 1) | |
} | |
boxes.push(next) | |
viewBox(boxes[i]) | |
} | |
}) | |
// 示例解法 | |
逃离纳米((no, viewBox) => { | |
let next = no | |
for (let i = 0; i < 100; i++) { | |
viewBox(next) | |
next += 1 | |
if (next > 200) next = 1 | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment