0

I am trying to come up with an algorithm to generate a nested array of consecutive numbers using only one loop. I feel it should be solved somehow using remainder operator but can't quite come up with a general solution. Anyone has any suggestion or hints?

input: 4 output: 1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4

2
  • 1
    Why not just use nested loop ? Simple and easy to understand Commented Dec 6, 2014 at 13:01
  • I guess it's more a math problem ... Commented Dec 6, 2014 at 13:06

2 Answers 2

3

You would use the modulo operator (%), but note that you should loop from zero and up, and the result from modulo is also from zero and up, so you have to add one to it.

var input = 4;

for (var i = 0; i < input * input; i++) {
  var n = (i % input) + 1;
  
  document.write(n + '<br>');

}

Sign up to request clarification or add additional context in comments.

Comments

2

Something like that should do the trick:

int input = ...
int i = 0;

while(i<=(input*input)){
    int output = (i % input) + 1;
    i++;
}

2 Comments

This is very elegant, but my next thought is that it is not quite as intuitive as a nested array would be.
@Ludovic, I certainly understand that ... just throwing in the random thoughts I'm having after being up all night.

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.