gpt4 book ai didi

javascript - JavaScript 中的 "Look and say sequence"

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:03:13 29 4
gpt4 key购买 nike

1
11
12
1121
122111
112213
122211
....
I was trying to solve this problem. It goes like this. I need to check the former line and write: the number and how many time it was repeated.
ex. 1 -> 1(number)1(time)

var antsArr = [[1]];
var n = 10;

for (var row = 1; row < n; row++) {
var lastCheckedNumber = 0;
var count = 1;
antsArr[row] = [];

for (var col = 0; col < antsArr[row-1].length; col++) {

if (lastCheckedNumber == 0) {
lastCheckedNumber = 1;
antsArr[row].push(lastCheckedNumber);

} else {

if (antsArr[row-1][col] == lastCheckedNumber) {
count++;

} else {
lastCheckedNumber = antsArr[row-1][col];
}

}

}
antsArr[row].push(count);
antsArr[row].push(lastCheckedNumber);
}



for (var i = 0; i < antsArr.length; i++) {
console.log(antsArr[i]);
}

我从 2 天前就开始关注这个了。自己很难解决。我知道这对你们来说真的是基本代码。但是,如果有一个真正热心的人帮助我,我会很高兴! :>

最佳答案

试试这个:

JSFiddle Sample

function lookAndSay(seq){
var prev = seq[0];
var freq = 0;
var output = [];
seq.forEach(function(s){
if (s==prev){
freq++;
}
else{
output.push(prev);
output.push(freq);
prev = s;
freq = 1;
}
});
output.push(prev);
output.push(freq);
console.log(output);
return output;
}

// Sample: try on the first 11 sequences
var seq = [1];
for (var n=0; n<11; n++){
seq = lookAndSay(seq);
}

快速解释

输入序列是一个包含序列中所有数字的简单数组。函数遍历序列中的元素,统计当前出现的次数。当它遇到一个新数字时,它会将先前出现的数字连同频率一起推送到输出。

保持迭代直到结束,确保将最后出现的数字和频率添加到输出中,仅此而已。

关于javascript - JavaScript 中的 "Look and say sequence",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31222938/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com