vincent thorpe
vincent thorpe

Reputation: 294

JS: This algorithm is doing weird thing, (analysis)

This code is took from my constructor a tiny part.

The first output should be ('1' or '2') then '0' til the end; Instead of pure '0' only. It gives me 1000 of 0. I don't know why.

I tested with lower values at the 'cols' and 'row' variables, and it works fine. (it outputs: '1' the first time, then '0')But when the cols and rows are higher the problem appears again. Its for a memory limit? I dont know about how much memory.

What should I do, to avoid this problem in future? Should I use functions? for each or something like recursive? Thank you.

P.N. if you dont seem any problem, try to set higher values to cols and rows. maybe this should trigger the issue.

var i, row_rate
var cols = 50
var rows = 31
var count = 0

for (i = 0; i < cols * rows; i++) {

  row_rate = Math.trunc(Math.trunc(i / cols) * 100 / rows)

  if (count > 0) {
    console.log(0)
  }
  else if (row_rate <= 20) {
    // the first time must pass here...
    count++
    console.log(1)
  }
  else {
    // ...or here
    count++
    console.log(2)
  }
}

Upvotes: 1

Views: 95

Answers (1)

The first console.log() is not 0, but 1, and after that one thousand of zeros are logged:

enter image description here

(the 1549 number means 1549 repeats of the same log line)

The problem is that the output don't supports that number of lines, so the older ones are removed. On Chrome Developer Tools (F12) you can check Group similar to avoid this problem: enter image description here

You can see it easily also by breaking on the 0 console log. You will see that the first log line is actually 1 before logging the 0:

var i, row_rate
var cols = 50
var rows = 31
var count = 0

for (i = 0; i < cols * rows; i++) {

  row_rate = Math.trunc(Math.trunc(i / cols) * 100 / rows)

  if (count > 0) {
    console.log(0)
    break;
  }
  else if (row_rate <= 20) {
    // the first time must pass here...
    count++
    console.log(1)
  }
  else {
    // ...or here
    count++
    console.log(2)
  }
}

Upvotes: 1

Related Questions