【问题标题】:Looping through a queue with for loops and If / Else使用 for 循环和 If / Else 遍历队列
【发布时间】:2016-10-17 15:32:37
【问题描述】:

您好,感谢您抽出宝贵时间查看此内容。

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

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 是一个显示我所在位置的小提琴:

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

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

我用各种控制语句把它弄得乱七八糟,以找到逻辑问题......

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

循环通过队列 1 并将当前值保存到 (x) -- 遍历队列 1,将第一项移动到队列 2 ---- IF/Else 当前项目可被 x 整除,否则重新排队

我将它切换到 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);
    }
  }

【问题讨论】:

  • 记住:= 是赋值,==(或者更好,===)用于比较。这条线会给你带来一些麻烦it = n - 1。那也应该是&lt;&lt;= 而不是=
  • 感谢您的回复...解决了迭代问题并让我更接近...仍然有一些问题需要解决,因为输出仍然不正确

标签: javascript loops queue


【解决方案1】:

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

最后再做一个协议输出。

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>

【讨论】:

  • 非常感谢...我喜欢...教授不允许使用数组。我将尝试使用队列来实现这一点。
  • 我的出队过程有问题...它不会删除最后一项;-(
猜你喜欢
  • 2020-05-02
  • 1970-01-01
  • 2017-07-24
  • 2016-04-14
  • 2019-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
相关资源
最近更新 更多