Given a positive integer n print matrix containing an X as in the example below
Example:
Input: n = 5 Output: x---x -x-x- --x-- -x-x- x---x Explanation: Each line contains exactly n = 5 characters and two 'x's. Each diagonal contains 'x'
x
and the other characters are all -
. The only exception is the middle line which will have only one x
.
How can we use this info?
x
.
How can we know these two columns for every line?
firstX
and secondX
, initially equal to 1
and n
respectively for the first line. firstX
should get incremented and secondX
should get decremented. for
loop to iterate through every column index from 1
to n
. if - else
statement and check if the current index is firstX
or secondX
and if so, print x
. Otherwise, print -
.
The core challenge of this problem is to generate a matrix of size n x n
where the diagonals are marked with 'x' and the rest of the elements are '-'. This problem is significant in understanding how to manipulate and generate patterns in a matrix, which is a common task in computer graphics, game development, and various algorithmic challenges.
To solve this problem, we can follow these steps:
firstX
and secondX
, to keep track of the positions of 'x' in each row.firstX
and secondX
and '-' elsewhere.Here is a step-by-step breakdown of the algorithm:
firstX
to 0 and secondX
to n-1
.n-1
:
line
.n-1
:
firstX
or secondX
, append 'x' to line
.line
.line
.firstX
and decrement secondX
.#include <iostream>
using namespace std;
void printX(int n) {
int firstX = 0;
int secondX = n - 1;
for (int i = 0; i < n; ++i) {
string line = "";
for (int j = 0; j < n; ++j) {
if (j == firstX || j == secondX) {
line += 'x';
} else {
line += '-';
}
}
cout << line << endl;
firstX++;
secondX--;
}
}
int main() {
int n;
cout << "Enter the value of n: ";
cin >> n;
printX(n);
return 0;
}
The time complexity of this approach is O(n^2)
because we have a nested loop where both the outer and inner loops run n
times. The space complexity is O(1)
if we do not consider the space used for the output.
Some potential edge cases include:
n = 1
: The output should be a single 'x'.n = 2
: The output should be:
xx xx
To test the solution comprehensively, consider the following test cases:
n = 1
and n = 2
.n
.n
to test the performance.When approaching such problems, it is essential to:
In this blog post, we discussed how to generate a matrix containing an 'X' pattern given a positive integer n
. We explored the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for developing strong problem-solving skills and algorithmic thinking.
For further reading and practice problems related to this topic, consider the following resources: