【问题标题】:javascript recursive dice combination and store the result in a matrixjavascript递归骰子组合并将结果存储在矩阵中
【发布时间】:2018-09-08 06:52:02
【问题描述】:

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

感谢您的帮助

【问题讨论】:

  • “一个错误”?什么错误?

标签: javascript arrays recursion nested


【解决方案1】:

固定长度组合

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

下面,我们使用建议的Array.prototype.flatMap,但包含一个用于尚不支持它的环境的polyfill。当n = 0 达到我们的基本情况时,我们返回空结果。归纳案例是n &gt; 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 ] ]

削弱

好的,所以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 中。在使用生成器时,这通常不是必需的。相反,我们可以使用 as 它们正在生成的值

下面,我们使用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 块中写任何我们想要的东西。下面,我们使用continue 为皇后区Q 添加一个附加条件skip

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 函数。下面,我们找到了三个 20 面骰子的所有组合,它们构成了一个 Pythagorean triple - 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', '♢' ]
// ]

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-17
  • 2016-10-14
  • 2019-06-24
  • 1970-01-01
相关资源
最近更新 更多