Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not getting correct result when solving a challenge

I am trying to solve this coding challenge
Result that I need

 1 8 9 16 17
 2 7 10 15 18
 3 6 11 14 19
 4 5 12 13 20

logic for colindex that is even
rowsNumber * colIndex+1 // 4*0+1 which gives 1 for column 0 row 1

logic for colindex that is odd
rowsNumber*(colIndex+1); // 4*(1+1) which gives 8 for column 2 row 1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const rowsNumber = 4;
const columnsNumber = 5;

for(let i=0;i<rowsNumber;i++) {

    for(let j=0;j<columnsNumber;j++) {
        if(j%2 == 0) {
        console.log(rowsNumber*j+1);
    }   else {
        console.log(rowsNumber*(j+1))
    }
  }

}

I am getting following result

1
8
9
16
17
1
8
9
16
17
1
8
9
16
17
1
8
9
16
17

What am I doing wrong?

>Solution :

Your logic is only valid for first row. You’ll also have to consider the rowIndex.
The actual logic is
For even rows : rowsNumber * (colIndex+1) – rowIndex
For odd rows : rowsNumber * colIndex+1 + rowIndex
So the code would be as follows

const rowsNumber = 4;
const columnsNumber = 5;
for(let i=0;i<rowsNumber;i++) {
    for(let j=0;j<columnsNumber;j++) {
        if(j%2 == 0) {
        console.log(rowsNumber*j+1+i);
    }   else {
        console.log(rowsNumber*(j+1)-i)
    }
  }
}

This gives the output as :

1
8
9
16
17
2
7
10
15
18
3
6
11
14
19
4
5
12
13
20
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading