#javascript challenge ---- Write a function to print square matrix | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

#javascript challenge ---- Write a function to print square matrix

Write a function squarematrix(n) to print square matrix of size n*n containing element from 0 to n*n-1. Let n=3, we call squarematrix (3) Then , output should 0 1 2 3 4 5 6 7 8 Solution with O(N*N) is obvious but here question is to write a program which takes lesser than that time complexity. You are free to use any string and array methods.

31st Jan 2023, 12:01 AM
AMAN
AMAN - avatar
5 Answers
+ 1
def squarematrix(n): for i in range(n): for j in range(n): print(i*n + j, end=" ") print()
1st Feb 2023, 1:44 AM
Patrick ONeil
Patrick ONeil - avatar
0
If it's possible to get that output. Can you just write pseudocode ? Even code if u r free
31st Jan 2023, 4:02 AM
AMAN
AMAN - avatar
0
AMAN KUMAR how about this? just linear iteration from 1 to n*n and string formatting the output. But Sololearn seem to have a whitespace trimmer in the console, so I had to work around that... https://code.sololearn.com/WvWyZI08Qt9i/?ref=app
31st Jan 2023, 4:45 AM
Bob_Li
Bob_Li - avatar
0
I saw you posted this in Code Challenges thread. Why repost in forum though?
31st Jan 2023, 9:46 AM
Ipang
0
Patrick ONeil a little f-string formatting modification to your code for prettier printing: def squarematrix(n): for i in range(n): for j in range(n): print(f'{i*n + j:^{len(str(n-1))+1}}', end=" ") print() squarematrix(10)
1st Feb 2023, 2:08 AM
Bob_Li
Bob_Li - avatar