Hacker News new | ask | show | jobs
by ianbishop 5127 days ago
I made a prime sieve: http://i.imgur.com/Elk5A.png

It was pretty fun.

JS generated isn't so bad..

  var n;
  var A;
  var i;
  var x;
  var j;

  n = 100;
  A = [];
  for (i = 0; i <= n; i++) {
    A[i - 1] = true;
  }
  var i_end = Math.sqrt(n);
  for (i = 2; i <= i_end; i++) {
    if (A[i - 1] == true) {
      j = Math.pow(i, 2);
      while (j <= n) {
        A[j - 1] = false;
        j = (j || 0) + i;
      }
    }
  }
  for (x = 2; x <= n; x++) {
    window.alert([x,': ',A[x - 1]].join(''));
  }
2 comments

You win the prize for most impressive Blockly program yet. Looking forward to what you will write once we get procedures landed. -- The Blockly Team.
So that explains why I couldn't figure out how to call a procedure...
Same here, I was already going crazy hehe
Taking advantage of JavaScript-translation-specific behavior allows procedures to work right now: just use arguments[1], arguments[2], and so on.
Interesting that in the initialization loop it sets A[0 - 1] to true, yet in your blocky code it appears to be iterating from 0 to n. In fact it always seems to be offsetting by one in array access ... 1 based indexing maybe?
Correct, you should see the looks on non-programmers' faces when you tell them that the first element in a Java list is #0, the second is #1, etc. It's approximately the same look as you see on programmers' faces when you tell them that the first element in a Blockly list is #1, the second is #2, etc.
Still, the blocky code reads "count with i from 0 to (get n)", but the loop generated is accessing A[0-1]..A[n-1]. JavaScript is forgiving here, but A[0..n] is not the same as A[-1..(n-1)] (at least I'm not familiar enough with JavaScript to think otherwise).
If they are mapping index 1 to index 0, then it makes sense that 0 would map to -1 since it is one less than the first index. The bug is in the blockly sieve.

As an aside, Lua also uses 1-based indexing.

I understand why they are offsetting the index, it just makes things somewhat unintuitive. In most programming languages A[-1] is the same as A[len(A)-1] (assuming zero based indexing) ... so in Blocky is A[0] expected to mean the same thing as A[len(A)-1]? Nothing here is a show stopper, just a detail that could use a bit of tightening up.
Yeah, I didn't realize it was 1-indexed until you guys pointed it out.

Unsurprisingly, it still works (it just loops a few too many times).