Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print array in transpose format using jquery

Tags:

javascript

I am little bit stuck in the below logic.

var t = new Array(),
  i = 1;
for (var s = 0; s < 7; s++) {
  t[s] = [];
  for (j = 0; j < 7; j++) {
    t[s][j] = i;
    if (i === 6) {
      i = 0;
    }
    i++;
  }
}
console.log(t);

In my tried logic i am getting array like below

0: [1,2,3,4,5,6,1]
1: [2,3,4,5,6,1,2]
2: [3,4,5,6,1,2,3]
3: [4,5,6,1,2,3,4]
4: [5,6,1,2,3,4,5]
5: [6,1,2,3,4,5,6]
6: [1,2,3,4,5,6,1]

But I want output

0: [1,2,3,4,5,6,0]
1: [2,3,4,5,6,0,1]
2: [3,4,5,6,0,1,2]
3: [4,5,6,0,1,2,3]
4: [5,6,0,1,2,3,4]
5: [6,0,1,2,3,4,5]
6: [0,1,2,3,4,5,6]

Looking for help.

like image 807
Nirav Joshi Avatar asked Jun 07 '26 02:06

Nirav Joshi


2 Answers

You can achieve it by rotating array.

let len = 7;
let a = Array.from(Array(len).keys());

let ans = [];

for(let i = 0; i < len; i++){
	a = a.slice(1,a.length).concat(a.slice(0,1));
	ans.push(a);
}

console.log(ans);
like image 93
Akshay Bande Avatar answered Jun 08 '26 15:06

Akshay Bande


I would solve it in a different approach - You are building a two dimensional array that each new element (or row) is shifted or incremented by one (6 is the max value) So increment each value by one and store the result.

    $column = [1,2,3,4,5,6,0];
    $max    = 6; 
    $rows   = 7;
    $result = [];

    for ($i = 0; $i < $rows; $i++) {
      $result[$i] = [...$column];
      for ($j = 0; $j < $column.length; $j++) {
        if ($column[$j] == $max) $column[$j] = 0;
        else $column[$j]++;
      }
    }

    console.log($result);
like image 37
Shlomi Hassid Avatar answered Jun 08 '26 15:06

Shlomi Hassid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!