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

标签 javascript arrays recursion nested

我想要实现的是结合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/

相关文章:

arrays - MongoDB 更新数组元素

c# - 以编程方式创建已知维度、类型和长度的数组

Java Reflection - 获取数组对象的大小

javascript - 为什么我的提交条件没有返回 false?

algorithm - 如何从单个集合中枚举组合的组合

java - 如何使用以被除数和除数作为参数的递归创建 int[] 除法?

c++ - 递归回文测试

javascript - react : how to re-render component every x seconds?

javascript - 使用变量访问 json 对象

javascript - 动态表创建者或 <td> <tr> 创建者