如何用Google App Script基于数组前三大值位置生成字符组合
解决方案
实现思路
- 由于输入固定为长度6的数组,所有3个不同位置的排列总数仅为120种,采用暴力枚举方案简单可靠,无需复杂的重复值判断逻辑
- 为每个排列计算数值降序排列后的得分元组,筛选出得分最高的所有非递增排列即可覆盖所有符合要求的组合
- 直接通过索引映射对应字母,避免位置判断错误
完整实现代码
// 辅助函数:比较两个降序数值元组的大小,返回1表示a更大,-1表示b更大,0相等 function compareTuples(a, b) { for (let i = 0; i < 3; i++) { if (a[i] > b[i]) return 1; if (a[i] < b[i]) return -1; } return 0; } function fCombination(targetArray) { const chars = ['A', 'B', 'C', 'D', 'E', 'F']; const allValidPerms = []; // 生成所有3个不同索引的非递增排列 for (let i = 0; i < 6; i++) { for (let j = 0; j < 6; j++) { if (j === i) continue; for (let k = 0; k < 6; k++) { if (k === i || k === j) continue; const valTuple = [targetArray[i], targetArray[j], targetArray[k]]; // 仅保留数值非递增的排列 if (valTuple[0] >= valTuple[1] && valTuple[1] >= valTuple[2]) { allValidPerms.push({ str: chars[i] + chars[j] + chars[k], // 得分元组为三个数值的降序排列 score: [...valTuple].sort((x, y) => y - x) }); } } } } // 查找最高得分 let maxScore = allValidPerms[0].score; for (const perm of allValidPerms) { if (compareTuples(perm.score, maxScore) > 0) { maxScore = perm.score; } } // 筛选所有最高得分的结果 return allValidPerms .filter(perm => compareTuples(perm.score, maxScore) === 0) .map(item => item.str); } // 测试用例 console.log(fCombination([1,6,5,4,2,3])); // 输出 ["BCD"] console.log(fCombination([1,4,5,4,4,3])); // 输出 ["CBD","CDB","CBE","CEB","CDE","CED"] console.log(fCombination([1,2,15,14,12,10])); // 输出 ["CDE"] console.log(fCombination([1,2,15,14,14,10])); // 输出 ["CDE", "CED"] console.log(fCombination([1,2,15,15,14,13])); // 输出 ["CDE", "DCE"] console.log(fCombination([1,2,15,14,13,13])); // 输出 ["CDE", "CDF"] console.log(fCombination([1,2,15,14,14,14])); // 输出 ["CDE", "CDF", "CED", "CFD", "CEF", "CFE"]
Google Apps Script适配说明
本代码逻辑完全兼容Google Apps Script,仅需将测试代码中的console.log替换为Logger.log即可正常运行。
内容的提问来源于stack exchange,提问作者Alejandro Paredes
相关产品推荐
相关产品推荐

