喊7的次数重排js实现
实现思路
要实现“喊7的次数重排”功能,需要统计数字序列中所有包含7或能被7整除的数字出现的次数,并根据这些次数重新排列原始序列。以下是具体的实现方法。

方法一:遍历统计法
遍历数字序列,统计每个数字是否包含7或能被7整除,记录每个数字的“喊7”次数。根据统计结果重新排列序列。

function reorderBySevenCount(arr) {
const countMap = new Map();
// 统计每个数字的喊7次数
for (const num of arr) {
let count = 0;
if (num % 7 === 0) count++;
if (num.toString().includes('7')) count++;
countMap.set(num, (countMap.get(num) || 0) + count);
}
// 根据喊7次数重新排序
return arr.sort((a, b) => {
const countA = countMap.get(a) || 0;
const countB = countMap.get(b) || 0;
return countB - countA;
});
}
// 示例用法
const arr = [7, 14, 21, 17, 27, 3, 5];
console.log(reorderBySevenCount(arr)); // [7, 17, 27, 14, 21, 3, 5]
方法二:预计算法
预先计算每个数字的“喊7”次数,并生成一个包含数字和次数的对象数组,然后根据次数排序。
function reorderBySevenCount(arr) {
const counted = arr.map(num => {
let count = 0;
if (num % 7 === 0) count++;
if (num.toString().includes('7')) count++;
return { num, count };
});
counted.sort((a, b) => b.count - a.count);
return counted.map(item => item.num);
}
// 示例用法
const arr = [7, 14, 21, 17, 27, 3, 5];
console.log(reorderBySevenCount(arr)); // [7, 17, 27, 14, 21, 3, 5]
方法三:函数式编程
使用函数式编程风格,通过链式调用实现统计和排序。
function reorderBySevenCount(arr) {
return arr
.map(num => ({
num,
count: (num % 7 === 0 ? 1 : 0) + (num.toString().includes('7') ? 1 : 0)
}))
.sort((a, b) => b.count - a.count)
.map(item => item.num);
}
// 示例用法
const arr = [7, 14, 21, 17, 27, 3, 5];
console.log(reorderBySevenCount(arr)); // [7, 17, 27, 14, 21, 3, 5]
注意事项
- 数字包含7:使用
toString().includes('7')判断数字是否包含数字7。 - 能被7整除:使用
num % 7 === 0判断数字是否能被7整除。 - 排序规则:按照“喊7”次数从高到低排序,次数相同的保持原始顺序(稳定排序)。
以上方法均能实现“喊7的次数重排”功能,选择哪种方法取决于具体需求和编码风格偏好。






