gpt4 book ai didi

javascript - 寻找更好的方法来减少数组并确定数字是否有序

转载 作者:行者123 更新时间:2023-12-01 00:18:34 24 4
gpt4 key购买 nike

const dice = [1,3,4,5,6]
const score = straightScore(dice,4)

function straightScore(dice, sizeOfStraight) {
let score = 0
sizeOfStraight > 4 ? score = 40 : score = 30
dice.sort( (a, b) => a-b )
// filter to eliminate duplicates
const filteredDice = dice.reduce( (acc, die) => {
if ( acc.indexOf(die) === -1 ) acc.push(die)
return acc
}, [] )
//determine straight
const straightFinder = filteredDice.reduce( (acc, die) => {
const lastNumInArray = acc.slice(-1)[0]
// here is my hack if the small straight starts with 3 and the last die is a 1
if ( die - lastNumInArray === 2) acc = [die]
if ( lastNumInArray === undefined || die - lastNumInArray === 1 ) acc.push(die)
return acc
}, [] )
if (straightFinder.length >= sizeOfStraight) return score
return 0
}

console.log(score)

我已经做到了,但感觉很糟糕。任何想法将不胜感激。

我正在尝试制作一款基本的 Yahtzee 游戏。确定顺子是否滚动是我陷入困境的地方。它基本上有效,但如果它是一个小顺子(五个骰子中连续四个)从 3 - 6 并且第五个骰子是 1,我的减少将无法正常工作。它始终解析为 1 项数组。我可以在我的逻辑中看到问题,所以我在那里做了一些修改以使其工作,但我觉得必须有十几种更好的方法。这是我的代码。感谢您的浏览。

骰子是一个由 5 个数字 1-6 组成的数组,代表骰子,sizeOfStraight 只是为了让我可以将其重复用于大顺子。不过问题只出现在小顺子上,所以你可以直接放 4 进去。

输入骰子 = [1, 3, 4, 5, 6]输出(无,仅返回,因为 StraightFinder.length = 1)

最佳答案

在最后的操作中,您实际上并不需要reduce。只需检查索引 0 和索引 3 处的排序骰子。如果后者的值比第一个多 3,则前 4 个排序骰子代表小顺子。可以在索引 1 和索引 4 处重复相同的操作。对于小顺子,没有其他可能的位置。大顺子只能从索引 0 开始,因此只需要一次检查。

注意:可以在临时集的帮助下提取唯一值。

const dice = [1, 3, 4, 5, 6];
const score = straightScore(dice, 4);

function straightScore(dice, sizeOfStraight) {
let score = 0;
sizeOfStraight > 4 ? score = 40 : score = 30;
dice.sort( (a, b) => a-b );
// duplicates can be eliminated with a Set:
const filteredDice = [...new Set(dice)];
// determine straight: only two locations are of interest (at most)
if (filteredDice[sizeOfStraight-1] - filteredDice[0] === sizeOfStraight-1) return score;
if (filteredDice[sizeOfStraight] - filteredDice[1] === sizeOfStraight-1) return score;
return 0;
}

console.log(score);

关于javascript - 寻找更好的方法来减少数组并确定数字是否有序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59594042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com