gpt4 book ai didi

javascript - javascript递归骰子组合并将结果存储在矩阵中

转载 作者:行者123 更新时间:2023-11-30 14:41:40 25 4
gpt4 key购买 nike

我想要实现的是结合N骰子发布的经典结果之一,但是将结果保存在具有MN字段的矩阵中(其中N是骰子数,M是可能的总数组合-通过6 ^ N获得)。到目前为止,我已经编写了以下代码:

function Dice (commonFace, singleFace){
this.diceFaces = ["critical", commonFace, commonFace, singleFace, "support1", "support2"]
this.numCases = function(){
return Math.pow(this.diceFaces.length, numberDices)
}
}
//create the attack dice
var attackDice = new Dice("smash", "fury");

//create the defence dice
var defenceDice = new Dice("block", "dodge");



//create a function that rolls the dice results and returns the number of results results
function rollDiceResults(diceTypeRolled, numberDicesRolled) {

//total possible results of the rolls of that number of dices
var totalPossibilites = diceTypeRolled.numCases(numberDicesRolled);

//store the dice results
var diceResults = new Array;


function rollDice(diceType, iteration, array) {
if (iteration == 1) {
//return the base case
for (i = 0; i < diceType.diceFaces.length; i++) {
array[i] = (diceType.diceFaces[i]);
}
} else {
//continue
for (i = 0; i < diceType.diceFaces.length; i++) {

array[i] = diceType.diceFaces[i];
rollDice(diceType, iteration - 1, tempResult);
}

}
}


for (i = 0; i < numberDicesRolled; i++) {
rollDice(diceTypeRolled, numberDicesRolled, diceResults);
}

}


我得到的是


函数声明中的错误
我错过了如何在保持m-n结构的同时调用函数内部的数组


谢谢你的帮助

最佳答案

定长组合

Recursion是一种功能性遗产,因此将其与功能性风格结合使用将产生最佳效果。递归就是将大问题分解为较小的子问题,直到达到基本情况为止。

下面,我们使用建议的Array.prototype.flatMap,但为尚未支持它的环境提供了一个polyfill。当n = 0达到基本情况时,我们返回空结果。归纳的情况是n > 0,其中choices将添加到较小问题combination (choices, n - 1)的结果中–我们说这里的问题较小,因为n - 1更接近n = 0的基本情况



Array.prototype.flatMap = function (f)
{
return this.reduce ((acc, x) => acc.concat (f (x)), [])
}

const combinations = (choices, n = 1) =>
n === 0
? [[]]
: combinations (choices, n - 1) .flatMap (comb =>
choices .map (c => [ c, ...comb ]))

const faces =
[ 1, 2, 3 ]

// roll 2 dice
console.log (combinations (faces, 2))
// [ [ 1, 1 ], [ 2, 1 ], [ 3, 1 ], [ 1, 2 ], ..., [ 2, 3 ], [ 3, 3 ] ]

// roll 3 dice
console.log (combinations (faces, 3))
// [ [ 1, 1, 1 ], [ 2, 1, 1 ], [ 3, 1, 1 ], [ 1, 2, 1 ], ..., [ 2, 3, 3 ], [ 3, 3, 3 ] ]





在程序中使用 combinations

编写 rollDice看起来像这样

const rollDice = (dice, numberOfDice) =>
combinations (dice.diceFaces, numberOfDice)

console.log (rollDice (attackDice, 2))
// [ [ 'critical', 'critical' ]
// , [ 'smash', 'critical' ]
// , [ 'smash', 'critical' ]
// , [ 'fury', 'critical' ]
// , [ 'support1', 'critical' ]
// , [ 'support2', 'critical' ]
// , [ 'critical', 'smash' ]
// , [ 'smash', 'smash' ]
// , ...
// , [ 'critical', 'support2' ]
// , [ 'smash', 'support2' ]
// , [ 'smash', 'support2' ]
// , [ 'fury', 'support2' ]
// , [ 'support1', 'support2' ]
// , [ 'support2', 'support2' ]
// ]


没有依赖

如果您好奇 flatMapmap的工作方式,我们可以自己实现它们。完全递归。



const None =
Symbol ()

const map = (f, [ x = None, ...xs ]) =>
x === None
? []
: [ f (x), ...map (f, xs) ]

const flatMap = (f, [ x = None, ...xs ]) =>
x === None
? []
: [ ...f (x), ...flatMap (f, xs) ]

const combinations = (choices = [], n = 1) =>
n === 0
? [[]]
: flatMap ( comb => map (c => [ c, ...comb ], choices)
, combinations (choices, n - 1)
)

const faces =
[ 1, 2, 3 ]

// roll 2 dice
console.log (combinations (faces, 2))
// [ [ 1, 1 ], [ 2, 1 ], [ 3, 1 ], [ 1, 2 ], ..., [ 2, 3 ], [ 3, 3 ] ]

// roll 3 dice
console.log (combinations (faces, 3))
// [ [ 1, 1, 1 ], [ 2, 1, 1 ], [ 3, 1, 1 ], [ 1, 2, 1 ], ..., [ 2, 3, 3 ], [ 3, 3, 3 ] ]





Nerfed

好的,因此 combinations允许我们确定重复的固定选择集的可能组合。如果我们有2个独特的骰子并想获得所有可能的掷骰子怎么办?

const results = 
rollDice (attackDice, defenceDice) ???


我们可以先呼叫 rollDice (attackDice, 1),然后呼叫 rollDice (defenceDice, 1),然后以某种方式组合答案。但是有更好的方法。一种允许任意数量的唯一骰子的方法,即使每个骰子的侧面数量不同也是如此。下面,我向您展示了我们编写的 combinations的两个版本以及为获得未开发的潜力而进行的必要更改

 // version 1: using JS natives
const combinations = (choices, n = 1) =>
const combinations = (choices = None, ...rest) =>
n === 0
choices === None
? [[]]
: combinations (choices, n - 1) .flatMap (comb =>
: combinations (...rest) .flatMap (comb =>
choices .map (c => [ c, ...comb ]))

// version 2: without dependencies
const combinations = (choices = [], n = 1) =>
const combinations = (choices = None, ...rest) =>
n === 0
choices === None
? [[]]
: flatMap ( comb => map (c => [ c, ...comb ], choices)
, combinations (choices, n - 1)
, combinations (...rest)
)


使用此新版本的 combinations,我们可以滚动任意大小的任意数量的骰子-即使在程序中也可以使用物理上不可能的三面骰子^ _ ^

// version 3: variadic dice
const combinations = (choices = None, ...rest) =>
choices === None
? [[]]
: flatMap ( comb => map (c => [ c, ...comb ], choices)
, combinations (...rest)
)

const d1 =
[ 'J', 'Q', 'K' ]

const d2 =
[ '♤', '♡', '♧', '♢' ]

console.log (combinations (d1, d2))
// [ [ 'J', '♤' ], [ 'Q', '♤' ], [ 'K', '♤' ]
// , [ 'J', '♡' ], [ 'Q', '♡' ], [ 'K', '♡' ]
// , [ 'J', '♧' ], [ 'Q', '♧' ], [ 'K', '♧' ]
// , [ 'J', '♢' ], [ 'Q', '♢' ], [ 'K', '♢' ]
// ]


当然,您可以掷相同骰子的集合

console.log (combinations (d1, d1, d1))
// [ [ 'J', 'J', 'J' ]
// , [ 'Q', 'J', 'J' ]
// , [ 'K', 'J', 'J' ]
// , [ 'J', 'Q', 'J' ]
// , [ 'Q', 'Q', 'J' ]
// , [ 'K', 'Q', 'J' ]
// , [ 'J', 'K', 'J' ]
// , ...
// , [ 'K', 'Q', 'K' ]
// , [ 'J', 'K', 'K' ]
// , [ 'Q', 'K', 'K' ]
// , [ 'K', 'K', 'K' ]
// ]


利用程序的这种潜能,您可以将 rollDice编写为

const rollDice = (...dice) =>
combinations (...dice.map (d => d.diceFaces))

console.log (rollDice (attackDice, defenceDice))
// [ [ 'critical', 'critical' ]
// , [ 'smash', 'critical' ]
// , [ 'smash', 'critical' ]
// , [ 'fury', 'critical' ]
// , [ 'support1', 'critical' ]
// , [ 'support2', 'critical' ]
// , [ 'critical', 'block' ]
// , [ 'smash', 'block' ]
// , ...
// , [ 'support2', 'support1' ]
// , [ 'critical', 'support2' ]
// , [ 'smash', 'support2' ]
// , [ 'smash', 'support2' ]
// , [ 'fury', 'support2' ]
// , [ 'support1', 'support2' ]
// , [ 'support2', 'support2' ]
// ]


或搭配各种骰子

const rollDice = (...dice) =>
combinations (...dice.map (d => d.diceFaces))

console.log (rollDice (defenceDice, attackDice, attackDice, attackDice))
// [ [ 'critical', 'critical', 'critical', 'critical' ]
// , [ 'block', 'critical', 'critical', 'critical' ]
// , [ 'block', 'critical', 'critical', 'critical' ]
// , [ 'dodge', 'critical', 'critical', 'critical' ]
// , [ 'support1', 'critical', 'critical', 'critical' ]
// , [ 'support2', 'critical', 'critical', 'critical' ]
// , [ 'critical', 'smash', 'critical', 'critical' ]
// , [ 'block', 'smash', 'critical', 'critical' ]
// , [ 'block', 'smash', 'critical', 'critical' ]
// , [ 'dodge', 'smash', 'critical', 'critical' ]
// , [ 'support1', 'smash', 'critical', 'critical' ]
// , ...
// ]


进入高层次

很高兴看到我们如何仅用JavaScript中的几个纯函数就能完成很多工作。但是,上述实现是缓慢的,并且在其可以产生多少组合方面受到严重限制。

下面,我们尝试确定七个6面骰子的组合。我们预计6 ^ 7会产生279936个组合

const dice =
[ attackDice, attackDice, attackDice, attackDice, attackDice, attackDice, attackDice ]

rollDice (...dice)
// => ...


根据上面选择的 combinations的实现,如果它不会导致您的环境无限期挂起,则将导致堆栈溢出错误

为了提高性能,我们提供了Javascript提供的高级功能: generators。下面,我们重写 combinations,但这一次使用与生成器交互所需的命令式样式。



const None =
Symbol ()

const combinations = function* (...all)
{
const loop = function* (comb, [ choices = None, ...rest ])
{
if (choices === None)
return
else if (rest.length === 0)
for (const c of choices)
yield [ ...comb, c ]
else
for (const c of choices)
yield* loop ([ ...comb, c], rest)
}
yield* loop ([], all)
}

const d1 =
[ 'J', 'Q', 'K', 'A' ]

const d2 =
[ '♤', '♡', '♧', '♢' ]

const result =
Array.from (combinations (d1, d2))

console.log (result)
// [ [ 'J', '♤' ], [ 'J', '♡' ], [ 'J', '♧' ], [ 'J', '♢' ]
// , [ 'Q', '♤' ], [ 'Q', '♡' ], [ 'Q', '♧' ], [ 'Q', '♢' ]
// , [ 'K', '♤' ], [ 'K', '♡' ], [ 'K', '♧' ], [ 'K', '♢' ]
// , [ 'A', '♤' ], [ 'A', '♡' ], [ 'A', '♧' ], [ 'A', '♢' ]
// ]





上面,我们使用 Array.from急切地将所有组合收集到单个 result中。使用发电机时,这通常不是必需的。相反,我们可以在生成值时使用它们

在下面,我们使用 for...of与每个组合从生成器中直接进行交互。在此示例中,我们显示了包含 J的任何组合

const d1 =
[ 'J', 'Q', 'K', 'A' ]

const d2 =
[ '♤', '♡', '♧', '♢' ]

for (const [ rank, suit ] of combinations (d1, d2))
{
if (rank === 'J' || suit === '♡' )
console.log (rank, suit)
}
// J ♤ <-- all Jacks
// J ♡
// J ♧
// J ♢
// Q ♡ <-- or non-Jacks with Hearts
// K ♡
// A ♡


当然,这里还有更多的潜力。我们可以在 for块中编写任何内容。在下面,我们添加了附加条件以使用 Q跳过皇后区 continue

const d1 =
[ 'J', 'Q', 'K', 'A' ]

const d2 =
[ '♤', '♡', '♧', '♢' ]

for (const [ rank, suit ] of combinations (d1, d2))
{
if (rank === 'Q')
continue
if (rank === 'J' || suit === '♡' )
console.log (rank, suit)
}
// J ♤
// J ♡
// J ♧
// J ♢
// K ♡ <--- Queens dropped from the output
// A ♡


也许最强大的功能是我们可以停止使用 break生成组合。下面,如果遇到King K,我们将立即停止生成器

const d1 =
[ 'J', 'Q', 'K', 'A' ]

const d2 =
[ '♤', '♡', '♧', '♢' ]

for (const [ rank, suit ] of combinations (d1, d2))
{
if (rank === 'K')
break
if (rank === 'J' || suit === '♡' )
console.log (rank, suit)
}
// J ♤
// J ♡
// J ♧
// J ♢
// Q ♡ <-- no Kings or Aces; generator stopped at K


您可以在这些条件下变得很有创意。在心脏中开始或结束的所有组合怎么样

for (const [ a, b, c, d, e ] of combinations (d2, d2, d2, d2, d2))
{
if (a === '♡' && e === '♡')
console.log (a, b, c, d, e)
}

// ♡ ♤ ♤ ♤ ♡
// ♡ ♤ ♤ ♡ ♡
// ♡ ♤ ♤ ♧ ♡
// ...
// ♡ ♢ ♢ ♡ ♡
// ♡ ♢ ♢ ♧ ♡
// ♡ ♢ ♢ ♢ ♡


并向您展示生成器适用于大型数据集

const d1 =
[ 1, 2, 3, 4, 5, 6 ]

Array.from (combinations (d1, d1, d1, d1, d1, d1, d1)) .length
// 6^7 = 279936

Array.from (combinations (d1, d1, d1, d1, d1, d1, d1, d1)) .length
// 6^8 = 1679616


我们甚至可以编写高阶函数来与生成器一起使用,例如我们自己的 filter函数。在下面,我们发现形成 Pythagorean triple的三个20边骰子的所有组合-3个整数组成一个有效直角三角形的边长

const filter = function* (f, iterable)
{
for (const x of iterable)
if (f (x))
yield x
}

const d20 =
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]

const combs =
combinations (d20, d20, d20)

const pythagoreanTriple = ([ a, b, c ]) =>
(a * a) + (b * b) === (c * c)

for (const c of filter (pythagoreanTriple, combs))
console.log (c)

// [ 3, 4, 5 ]
// [ 4, 3, 5 ]
// [ 5, 12, 13 ]
// [ 6, 8, 10 ]
// [ 8, 6, 10 ]
// [ 8, 15, 17 ]
// [ 9, 12, 15 ]
// [ 12, 5, 13 ]
// [ 12, 9, 15 ]
// [ 12, 16, 20 ]
// [ 15, 8, 17 ]
// [ 16, 12, 20 ]


或者将 Array.from与映射功能一起使用,以将每个组合同时转换为新结果并将所有结果收集到数组中

const allResults =
Array.from ( filter (pythagoreanTriple, combs)
, ([ a, b, c ], index) => ({ result: index + 1, solution: `${a}² + ${b}² = ${c}²`})
)

console.log (allResults)
// [ { result: 1, solution: '3² + 4² = 5²' }
// , { result: 2, solution: '4² + 3² = 5²' }
// , { result: 3, solution: '5² + 12² = 13²' }
// , ...
// , { result: 10, solution: '12² + 16² = 20²' }
// , { result: 11, solution: '15² + 8² = 17²' }
// , { result: 12, solution: '16² + 12² = 20²' }
// ]


什么功能?

函数式编程很深入。潜入!



const None =
Symbol ()

// Array Applicative
Array.prototype.ap = function (args)
{
const loop = (acc, [ x = None, ...xs ]) =>
x === None
? this.map (f => f (acc))
: x.chain (a => loop ([ ...acc, a ], xs))
return loop ([], args)
}

// Array Monad (this is the same as flatMap above)
Array.prototype.chain = function chain (f)
{
return this.reduce ((acc, x) => [ ...acc, ...f (x) ], [])
}

// Identity function
const identity = x =>
x

// math is programming is math is ...
const combinations = (...arrs) =>
[ identity ] .ap (arrs)

console.log (combinations ([ 0, 1 ], [ 'A', 'B' ], [ '♡', '♢' ]))
// [ [ 0, 'A', '♡' ]
// , [ 0, 'A', '♢' ]
// , [ 0, 'B', '♡' ]
// , [ 0, 'B', '♢' ]
// , [ 1, 'A', '♡' ]
// , [ 1, 'A', '♢' ]
// , [ 1, 'B', '♡' ]
// , [ 1, 'B', '♢' ]
// ]

关于javascript - javascript递归骰子组合并将结果存储在矩阵中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49553944/

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