当前位置:首页 > JavaScript

js实现24点算法

2026-03-01 21:47:55JavaScript

24点算法实现思路

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

递归穷举所有可能组合

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

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]);
}

优化版本记录运算过程

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

js实现24点算法

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
分享给朋友:

相关文章

js实现图片轮播

js实现图片轮播

实现基础图片轮播 使用HTML、CSS和JavaScript创建一个简单的图片轮播。HTML部分定义轮播容器和图片,CSS设置样式和动画效果,JavaScript处理轮播逻辑。 <div cl…

js实现抽奖

js实现抽奖

实现抽奖功能的基本思路 抽奖功能的核心是随机选择奖项并展示结果。可以通过数组存储奖项,利用随机数生成索引,最后通过动画增强用户体验。 准备奖项数据 定义一个数组存储奖项信息,每个奖项可以包含名称、图…

js实现驼峰

js实现驼峰

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

js实现授权

js实现授权

授权流程设计 授权流程通常涉及前端与后端的交互,常见方案包括OAuth2.0、JWT等。以JWT为例的典型流程: 用户提交凭证(如用户名密码)到认证服务 服务端验证通过后生成包含用户信息的JWT令牌…

js实现下拉刷新

js实现下拉刷新

监听触摸事件 通过监听 touchstart、touchmove 和 touchend 事件来检测用户下拉手势。记录触摸起始位置和移动距离。 let startY = 0; let currentY…

js实现图片放大

js实现图片放大

使用 CSS transform 实现图片放大 通过 CSS 的 transform: scale() 属性实现图片放大效果。当鼠标悬停时,图片会平滑放大。 const img = document…