+ 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.

6 Answers

+ 2

One dimensional array. Should run in O(n).

+ 1

def squarematrix(n):
for i in range(n):
for j in range(n):
print(i*n + j, end=" ")
print()

0

If it's possible to get that output.
Can you just write pseudocode ?
Even code if u r free

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

0

I saw you posted this in Code Challenges thread. Why repost in forum though?

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)