<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>JS 1, 11, 21, 1211, 111221 找规律</title>
</head>
<body>
<script>
//群友(大卡车)实现的方法
function countNum(str) {
let Str = str.toString();
let Strs = Str.split("");
let returnStr = [];
let position = 0;
Strs.forEach((e, i) => {
if (returnStr[position]) {
if (e === returnStr[position][0]) {
returnStr[position]+=e
} else {
returnStr[++position] = e;
}
} else {
returnStr[position]=e
}
})
return returnStr.map(e => `${e.length}${e[0]}`).join("");
}
//群主实现的方法
function countAndSay(n) {
var last = '1'
if (n <= 1) {
return last
}
for (var i = 1; i < n; i++) {
var str = last
var ret = []
for (var s = 0, sn = str.length; s < sn; s++) {
var a = str[s]
if (a === ret[ret.length - 1]) {
ret[ret.length - 2]++
} else {
ret.push(1, a) //量词在前,名词在后
}
}
last = ret.join('')
}
return last
}
console.info(countNum(countNum(countNum(countNum(1)))));
console.info(countAndSay(5))
</script>
</body>
</html>
效果图:
本文介绍了一个有趣的数列生成算法,并提供了两种不同的JavaScript实现方法。该数列从1开始,每一步通过对当前序列进行计数并描述来生成下一个序列。文中通过具体的函数实现展示了如何生成如1, 11, 21, 1211, 111221等序列。
1万+

被折叠的 条评论
为什么被折叠?



