Problem Description: Write a function x(n) that takes in a number n and returns an nxn array with an X in the middle.
The X will be represented by 1's and the rest will be 0's.
E.g.
x(5) === [[1, 0, 0, 0, 1],
[0, 1, 0, 1, 0],
[0, 0, 1, 0, 0],
[0, 1, 0, 1, 0],
[1, 0, 0, 0, 1]];
x(6) === [[1, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 1, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 1, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 1]];
Level:6kyu
Link To Kata: X marks the spot!
This kata asks us to prepare a nxn array with an X printed in the middle. To print an X we have to make all the diagonal elements equal to 1 and keep other elements equal to 0.
We start doing this kata by initializing all the elements of the nxn array to 0.
Then we loop through the nxn array through two while loops and make all the elements equal to 1 whose both looping index are same. Doing this process makes all the elements on our right diagonal equal o 1.
We once again loop through the array and make all the elements equal to 1 where the sum of looping indexes is equal to n-1. This process makes all the elements on our left diagonal equal to 1.
After these two processes we end up with a nxn array with a X in the middle. We return the nxn array as the solution to this kata.
Please go through the code for a better understanding.
Here is the link to code: Kata Day 46
Please mention your suggestions or your doubts in the comment below.
Happy coding. :)
No comments:
Post a Comment