Making perfect squares using nested loops in JavaScript

So I was asked this question today:

You have 100 cats. (You are very lucky to have so many cats!)

You put all your cats in a line. Initially, none of your cats have hats. You take 100 rounds by walking around the cats. every time you stay with a cat, you put your hat on it if it doesn’t have one, and you take off your hat if it does.

In the first round, you stop at each cat. In the second round, you only stop at every other cat (# 2, # 4, # 6, # 8, etc.). Round three, you only stop at every third cat (# 3, # 6, # 9, # 12, etc.). You continue this until the 100th round (i.e. you only visit the 100th cat).

Write a program that prints out which cats have hats at the end.

I know the answer is all perfect squares. I tried to solve this with JavaScript, my answer is almost correct except for the 100th cat. I think there is something wrong with one of my loops, so the last element of the array is not what it should be.

This is what I came up with:

var cats = [];
for (var i = 0; i < 100; i++) {
  cats.push(0);
}
for (var j = 1; j <= cats.length; j++) {
  for (var k = 0; k <= cats.length; k+= j) {
    if (cats[k] === 0) {
      cats[k] = 1;
    } else if (cats[k] === 1) {
      cats[k] = 0;
    }
  }
}
console.log(cats);

      

Expected Result:

[ 1, 0, 0, 1, 0, 0, 0, 0, 1, 0,
  0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
  0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]

      

While the day off I get:

[ 0, 1, 0, 0, 1, 0, 0, 0, 0, 1,
  0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
  0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

      

+3


source to share


1 answer


If you know that the answers should be perfect squares up to 100, you can simply write your own program to do so. While writing nested loops can be useful for exercise, if you know the problem can be solved in a smaller O order, use it.



var n = 100;
var c = Array.apply(null, new Array(n)).map(Number.prototype.valueOf, 0);
for (var i = 1; 1; i++) {
  var s = i * i;
  if (s > n) break;
  c[--s] = 1;
}

      

-1


source







All Articles