0

I have a loop

for (var i=0; i < x; i++){
  // ..
}

I want to wrap each 8 numbers between two characters. So my output would look something like this:

< 0 1 2 3 4 5 6 7 > < 8 9 10 11 12 13 14 15 > < 16 17 18 19 20 21 22 23 > < ...

My solution was

if(i == 0) console.info('<');
if(i == 7) console.info('>');
if(i == 8) console.info('<');
if(i == 15) ...

But this would be pretty verbose. Is it possible to make this task easier?

0

5 Answers 5

2

You can check if i falls between 7 and 8 using the % (mod) operator. x % y returns the remainder if dividing x by y. For example:

0 % 4 == 0

1 % 4 == 1

2 % 4 == 2

3 % 4 == 3

4 % 4 == 0

5 % 4 == 1

A solution using this method would look like:

var limit = 64;
console.info('< ');
for (var i = 0; i < limit; i++) {
  if (i % 8 == 0 && i > 0) {
     console.info('> <');
  }
  console.info(i, ' ');
}
console.info('>');
Sign up to request clarification or add additional context in comments.

2 Comments

You can try console.log(i, ' ') as well.
Although your console.info()s aren't in all the optimal places, this is the best answer here so far.
0

Sure.

var iterations = 3;
for (var i = 0; i < iterations; i++) {
    console.log("<");
    for (var j = i * 8; j < ( i * 8 ) + 8; j++)
        console.log(j);
    console.log(">");
}

Comments

0

Try this:

(function() {
  var result = "";
  var x = 25;
  for (var i = 0; i < x; i++) {
    if (i % 8 == 0) {
      result += "> <"
    }
    result += " " + i + " ";
  }
  result += " >"
  console.log(result.substring(1));
})()

Comments

0
console.info('<');
for (var i=0; i < x; i++){
    if ((i > 0) && (i %8) == 0) {
        console.info('><');
    }
}
console.info('>');

Basically, what we are doing here is saying, if i divided by 8 has a remainder of 0, then add the brackets. Thus, every 8 numbers.

Hope this helps!

Comments

0

My suggestion,

var limit = x/8;
var chunk;
for (var i=0; i<limit; i++) {
    console.log('<');
    chunk = i*8;
    for (var j=chunk; j<chunk+8; j++)
        console.log(j);
    console.log('>');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.