gpt4 book ai didi

javascript - 使用 for 循环和 If/Else 循环队列

转载 作者:太空宇宙 更新时间:2023-11-04 16:27:41 25 4
gpt4 key购买 nike

您好,感谢您花时间查看此内容。

我正在尝试实现以下输出:

Iteration 0:
Queue 1 = 2345678910 | Queue 2 =
Iteration 1:
Queue 1 = 3579 | Queue 2 = 2
Iteration 2:
Queue 1 = 57 | Queue 2 = 23
Iteration 3:
Queue 1 = 7 | Queue 2 = 235
Iteration 4:
Queue 1 = | Queue 2 = 2357

这应该是“The Sieve of Eratosthenes”的实现
我不会撒谎,这显然是学校作业! (虽然截止日期已经过去,但我并不是想获得一个简单的成绩。我实际上想知道为什么我无法让它发挥作用)
我确实进行了深入的搜索,但我发现的所有类似的东西都是使用数组实现的。(教授不允许)

here 是一个 fiddle ,显示我所在的位置:

这似乎是我的问题,它不会删除最后一项。

if (this.first == this.last) {
this.first = null;
return this.first.content;
this.length--;
}

我用各种控制语句搞乱了它,以找出逻辑问题......

当我开始时,我非常确定我可以这样做:

循环队列 1 并将当前值保存到 (x)-- 循环队列1,将第一项移至队列2---- IF/Else 当前项可被 x 整除,则继续移动 else 重新排队

我将其切换为 while 循环,但它因删除最后一项而卡住

// find the primes function
function fp() {
fillQueue(); // call the fillQueue function below

document.getElementById("output").innerHTML += "Ctrl " + "|it. " + it + " |queue length " + q1.length + " |x " + x + " |current x" + cx + " |Q1: = " + q1.toString() + " | Q2: = " + q2.toString() + " | Q3: = " + q3.toString() + "<br />";

while (q1.length >= 0) {
dq1();
cx = x;
q3.enqueue(cx);

while (q1.length >= 0) {
dq1();
eval();
it++;
}

while (q2.length >= 0) {
dq2();
d1.enqueue(x);
}
}

最佳答案

我建议在数字的第一个元素小于数字时使用不同的方法和循环,直到进行检查。进行协议(protocol)输出,将数字的第一个元素插入multiples,然后通过检查索引零处数字的倍数来过滤numbers

最后制作另一个协议(protocol)输出。

function calculate() {
var number = document.getElementById('number').value,
numbers = Array.apply(null, { length: number - 1 }).map(function (_, i) { return i + 2; }),
multiples = [];

while (numbers[0] < number) {
document.getElementById('out').innerHTML += numbers.join(' ') + ' ||| ' + multiples.join(' ') + '\n';
multiples.push(numbers[0]);
numbers = numbers.filter(function (a) {
return a % numbers[0];
});
}
document.getElementById('out').innerHTML += numbers.join(' ') + ' ||| ' + multiples.join(' ') + '\n';
}
<input id="number" /><button onclick="calculate()">calculate</button>
<pre id="out"></pre>

关于javascript - 使用 for 循环和 If/Else 循环队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40090373/

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