Issue
Hi I am trying to create a matrix on the console using 2D array. The idea is that the output should look like this one :
1|8|9 |16
2|7|10|15
3|6|11|14
4|5|12|13
Is there any one who has an idea how it can be done?
Solution
Few things you can guess from the matrix: -
First, you have to traverse all rows of a columns first before moving to the next column
Second, you need to alternate between
downwardsandupwardsdirection on each iterationSo, you would need two nested for loop, for iterating through rows for a particular column. One will go from
row 0 to max - 1, and the next will go fromrow = max - 1 to 0.Now, to alternate the iteration direction, you can use a boolean variable, and toggle it after each iteration of inner loop finishes.
Each loop needs to be enclosed inside an
if-else. Both of them will be executed on a certain condition. Ifboolean downwards = false;, then loop moving upwards will be executed and vice-versa.On each iteration, fill the current cell with an integer counter, that you would have to initialize with
1, and increment it after each fill.
Pseudo code : -
// Initialize variables row, col, and count = 1
boolean goDown = true;
int[][] matrix = new int[row][col]; // declare matrix
for i = 0 to col:
if (goDown)
for j = 0 to row: // Move in downwards direction
assign count++ to matrix[j][i]
// assign to `[j][i]` because, we have to assign to rows first
goDown = false; // Toggle goDown
else
for j = row - 1 to 0: // Move in upwards direction
assign count++ to matrix[j][i]
goDown = true; // toggle goDown
}
Answered By - Rohit Jain
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.