Nikolai Georgiev
Nikolai Georgiev

Reputation: 39

How to iterate through every number like the displayed example? (Java Script)

This is the example of the required output :

1 2 3 4 5 6 7 8 9 0 
2 3 4 5 6 7 8 9 0 1 
3 4 5 6 7 8 9 0 1 2
4 5 6 7 8 9 0 1 2 3
5 6 7 8 9 0 1 2 3 4
6 7 8 9 0 1 2 3 4 5
7 8 9 0 1 2 3 4 5 6
8 9 0 1 2 3 4 5 6 7
9 0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8 9

This is what I have written so far :

for (var nam = 9; nam > 0; nam--){ 
    for (var x = 1 ; x <= 9; x++){
       if (x == nam){
        process.stdout.write(x +" 0 ");
       } else {
        process.stdout.write(x + " ");
       }
    }
    console.log();
}

Upvotes: 1

Views: 42

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

You could use nested for loops and take the remainder operator for adjusting the value of outer and inner counter.

var i, j, array;

for (i = 1; i <= 10; i++) {
    array = [];
    for (j = 0; j < 10; j++) {
        array.push((j + i) % 10);
    }
    console.log(array.join(' '));
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions