简单的24点小游戏


简单的24点小游戏

游戏规则

随机生成4个数字(1-10),通过+-*/四则运算将4个数字算出24即可

游戏设计

生成4个数字,并给出参考答案

  • 随机生成0-10之间的4个整数
  • 穷举4个数所有四则运算得出24点的所有组合
  • 无法得到24点则重复上述两点重新生成

游戏实现

随机生成4个整数

function createNums() {
	return Array(4).fill('').map(item => Math.ceil(Math.random() * 10));
}

穷举所有组合场景

  1. 列出4个数字所有的排列方式
  2. 列出4组数字间的3个运算符的所有排列方式
  3. 列出4组数字间存在括号的所有场景
  4. 将上面3种排列组合方式进行组合排列,计算值为24的组合方式

生成4组数字的排列方式

将4组数字放置到数组内,通过递归方式得出所有排列方式的数组集合

function swap(arr, idx1, idx2) {
    const temp = arr[idx1]
    arr[idx1] = arr[idx2]
    arr[idx2] = temp
}

function createArr(_arr) {
    const tempArr = []
    function getArr(arr, idx) {
      if (idx >= arr.length - 1) {
        tempArr.push([...arr])
      } else {
        for (let index = idx; index < arr.length; index++) {
          swap(arr, index, idx)
          getArr(arr, idx + 1)
          swap(arr, index, idx)      
        }
      }
    }
    getArr(_arr, 0);
    return tempArr;
}

生成3个运算符的所有排列方式

排列方式为4的3次方,通过4进制的方式进行排列

function getOperator () {
  let i = 0
  const wArr = []
  while(i < 64) {
    wArr.push([Math.floor(i / 16), Math.floor((i % 16) / 4), i % 4])
    i++
  }
  return wArr
}

列出4组数字间存在括号的所有场景

a b c d
(a b) c d
a (b c) d
a b (c d)
(a b c) d
a (b c d)
(a b) (c d)

组合所有计算场景

计算得出可以算出成24点的组合就return

function run(arr) {
  const tempArr = createArr(arr)
  const wArr = getOperator()
  for (let idx = 0; idx < tempArr.length; idx++) {
    const [n1, n2, n3, n4] = tempArr[idx];
    
    for (let idx2 = 0; idx2 < wArr.length; idx2++) {
      const [w1, w2, w3] = wArr[idx2];
      const arr2 = [
        `${n1}${o[w1]}${n2}${o[w2]}${n3}${o[w3]}${n4}`,
        `${n1}${o[w1]}(${n2}${o[w2]}${n3})${o[w3]}${n4}`,
        `${n1}${o[w1]}(${n2}${o[w2]}${n3}${o[w3]}${n4})`,
        `${n1}${o[w1]}${n2}${o[w2]}(${n3}${o[w3]}${n4})`,
        `(${n1}${o[w1]}${n2})${o[w2]}${n3}${o[w3]}${n4}`,
        `(${n1}${o[w1]}${n2})${o[w2]}(${n3}${o[w3]}${n4})`,
        `(${n1}${o[w1]}${n2}${o[w2]}${n3})${o[w3]}${n4}`,
      ]
      for (let idx3 = 0; idx3 < arr2.length; idx3++) {
        const str = arr2[idx3];
        if (eval(str) === 24) {
          console.log(str)
          return str
        }
      }
    }
  }
}

游戏预览

地址:https://code.juejin.cn/pen/7186132764352053281

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章