在deveco studio中用js写一个24点算法
时间: 2024-05-07 10:22:01 浏览: 14
以下是用 JavaScript 编写的 24 点算法:
```javascript
function calculate24(nums) {
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
const multiply = (a, b) => a * b;
const divide = (a, b) => a / b;
const ops = [add, subtract, multiply, divide];
const permutations = permute(nums);
for (let nums of permutations) {
for (let o1 of ops) {
for (let o2 of ops) {
for (let o3 of ops) {
if (o3(o2(o1(nums[0], nums[1]), nums[2]), nums[3]) === 24) {
return true;
}
if (o3(o1(nums[0], nums[1]), o2(nums[2], nums[3])) === 24) {
return true;
}
if (o3(o1(nums[0], o2(nums[1], nums[2])), nums[3]) === 24) {
return true;
}
if (o3(nums[0], o2(o1(nums[1], nums[2]), nums[3])) === 24) {
return true;
}
if (o3(nums[0], o1(nums[1], o2(nums[2], nums[3]))) === 24) {
return true;
}
}
}
}
}
return false;
}
function permute(nums) {
if (nums.length <= 1) {
return [nums];
}
const result = [];
for (let i = 0; i < nums.length; i++) {
const current = nums[i];
const remaining = nums.slice(0, i).concat(nums.slice(i + 1));
const permutations = permute(remaining);
for (let p of permutations) {
result.push([current].concat(p));
}
}
return result;
}
```
你可以将 4 个数字作为数组传递给 `calculate24` 函数,该函数将返回一个布尔值,表示是否存在一种运算方式,使得这 4 个数字可以组合成 24。例如:
```javascript
console.log(calculate24([4, 6, 8, 9])); // true
console.log(calculate24([1, 2, 3, 4])); // false
```
请注意,这个算法并不保证始终能找到一个可行的解决方案,因为有些数字组合可能无法生成 24。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)