当前位置:首页 > JavaScript

js实现24点算法

2026-03-01 21:47:55JavaScript

24点算法实现思路

24点游戏要求通过加、减、乘、除四则运算,使得4个数字的运算结果为24。以下是用JavaScript实现的核心方法:

js实现24点算法

递归穷举所有可能组合

采用递归方式遍历所有数字和运算符的排列组合:

function calculate24(numbers) {
  if (numbers.length === 1) {
    return Math.abs(numbers[0] - 24) < 1e-6;
  }

  for (let i = 0; i < numbers.length; i++) {
    for (let j = 0; j < numbers.length; j++) {
      if (i === j) continue;

      const remaining = numbers.filter((_, index) => index !== i && index !== j);
      const a = numbers[i], b = numbers[j];

      // 尝试所有运算符
      if (tryCombine(a + b, remaining)) return true;
      if (tryCombine(a - b, remaining)) return true;
      if (tryCombine(b - a, remaining)) return true;
      if (tryCombine(a * b, remaining)) return true;
      if (b !== 0 && tryCombine(a / b, remaining)) return true;
      if (a !== 0 && tryCombine(b / a, remaining)) return true;
    }
  }
  return false;
}

function tryCombine(value, remaining) {
  return calculate24([value, ...remaining]);
}

优化版本记录运算过程

以下实现会记录具体的运算步骤:

function solve24(numStr) {
  const nums = numStr.split('').map(Number);
  const solutions = [];

  function dfs(list, path) {
    if (list.length === 1) {
      if (Math.abs(list[0] - 24) < 1e-6) {
        solutions.push(path[0]);
      }
      return;
    }

    for (let i = 0; i < list.length; i++) {
      for (let j = 0; j < list.length; j++) {
        if (i === j) continue;

        const next = [];
        const newPath = [];
        for (let k = 0; k < list.length; k++) {
          if (k !== i && k !== j) {
            next.push(list[k]);
            newPath.push(path[k]);
          }
        }

        const a = list[i], b = list[j];
        const aPath = path[i], bPath = path[j];

        // 加法
        next.push(a + b);
        newPath.push(`(${aPath} + ${bPath})`);
        dfs(next, newPath);
        next.pop(); newPath.pop();

        // 减法(两种顺序)
        next.push(a - b);
        newPath.push(`(${aPath} - ${bPath})`);
        dfs(next, newPath);
        next.pop(); newPath.pop();

        next.push(b - a);
        newPath.push(`(${bPath} - ${aPath})`);
        dfs(next, newPath);
        next.pop(); newPath.pop();

        // 乘法
        next.push(a * b);
        newPath.push(`(${aPath} * ${bPath})`);
        dfs(next, newPath);
        next.pop(); newPath.pop();

        // 除法(两种顺序,且除数不为0)
        if (b !== 0) {
          next.push(a / b);
          newPath.push(`(${aPath} / ${bPath})`);
          dfs(next, newPath);
          next.pop(); newPath.pop();
        }

        if (a !== 0) {
          next.push(b / a);
          newPath.push(`(${bPath} / ${aPath})`);
          dfs(next, newPath);
          next.pop(); newPath.pop();
        }
      }
    }
  }

  dfs(nums, nums.map(String));
  return solutions.length > 0 ? solutions[0] : "No solution found";
}

使用示例

console.log(solve24("1234"));  // 输出类似:(4 * (1 + (3 + 2)))
console.log(calculate24([1, 2, 3, 4])); // 输出: true

注意事项

  1. 浮点数比较使用近似判断Math.abs(result - 24) < 1e-6,避免精度问题
  2. 除法运算时需要检查除数不为0
  3. 算法时间复杂度为O(4! * 4^3) ≈ O(1536),对于4个数字完全可接受
  4. 如需显示所有解而非第一个解,可以收集solutions数组中的所有结果

这种方法通过深度优先搜索遍历所有可能的运算顺序和组合,能够找到是否存在解以及具体的运算步骤。

js实现24点算法

标签: 算法js
分享给朋友:

相关文章

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callbac…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…

js实现驼峰

js实现驼峰

实现驼峰命名的几种方法 使用正则表达式和字符串替换 通过正则表达式匹配字符串中的特定模式(如下划线或短横线),并将其后的字母转换为大写,同时移除分隔符。 function toCamelCase(s…

js树实现

js树实现

树的基本概念 树是一种非线性的数据结构,由节点和边组成。每个节点包含一个值和指向子节点的引用。树的顶部节点称为根节点,没有子节点的节点称为叶节点。 树的实现方式 在JavaScript中,树可以通…

js计算器的实现

js计算器的实现

实现基础结构 HTML部分需要创建计算器的基本框架,包含显示区域和按钮。使用<div>容器包裹整个计算器,内部设置一个显示屏和多个按钮。 <div class="calculat…

js实现按钮点击

js实现按钮点击

实现按钮点击的JavaScript方法 HTML按钮元素 在HTML中创建按钮元素,为其添加id或class以便JavaScript选择: <button id="myButton">点…