So basically I'm trying to make this matrix (with a 2d array) in the format
1
1 1
1 1
1 1 1
1 2 1
1 1 1
1 1 1 1
1 2 2 1
1 2 2 1
1 1 1 1
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
depending on what size the user inputs. I can do this with hard code as shown:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int userSize;
do {
cin >> userSize;
int userArray[userSize][userSize];
int size = 1;
int maxSize = 99;
for (int i = 0; i < userSize; i++) {
for (int j = 0; j < userSize; j++) {
if ((j > 2 && j < userSize - 3) &&
(i > 2 && i < userSize - 3)){
userArray[i][j] = size + 3;
}
if ((j > 1 && j < userSize - 2) &&
(i > 1 && i < userSize - 2)) {
userArray[i][j] = size + 2;
}
else if ((j > 0 && j < userSize - 1) &&
(i > 0 && i < userSize - 1)) {
userArray[i][j] = size + 1;
}
else {
userArray[i][j] = size;
}
}
}
for (int i = 0; i < userSize; i++) {
for (int j = 0; j < userSize; j++) {
cout << setw(3) << userArray[i][j];
}
cout << endl;
}
cout << endl;
}while(userSize != 0);
return 0;
}
however I need to be able to do this up to 99, which would obviously be a lot to write. Is there a way I can do this with a while loop instead? Below is my failed attempt that only outputs garbage:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int userSize;
int maxSize = 99;
int size = 1;
do {
cin >> userSize;
int myMatrix[userSize][userSize];
for (int i = 0; i < userSize; i++) {
for (int j = 0; j < userSize; j++) {
while (maxSize >= 0) {
if ((j > maxSize) && (j < userSize - (maxSize + 1)) &&
((i > maxSize) && (i < userSize - (maxSize + 1)))) {
myMatrix[i][j] = size + maxSize;
}
/*
if ((j > 1 && j < userSize - 2) &&
(i > 1 && i < userSize - 2)) {
myMatrix[i][j] = size + 2;
}
else if ((j > 0 && j < userSize - 1) &&
(i > 0 && i < userSize - 1)) {
myMatrix[i][j] = size + 1;
}
*/
else {
myMatrix[i][j] = size;
}
maxSize = maxSize - 1;
}
}
}
for (int i = 0; i < userSize; i++) {
for (int j = 0; j < userSize; j++) {
cout << setw(3) << myMatrix[i][j];
}
cout << endl;
}
cout << endl;
}while(userSize != 0);
return 0;
}
looks to me like you want the minimum steps from an outer edge. Here is some psuedo-code
int[,] ComputeMatrix(int m,int n)
{
int[,] matrix = new int[m,n]
for(int i = 0;i < m;i++)
for(int j = 0;j < n;j++)
{
//Minimum distance from each of the 4 walls
matrix[i,j] = 1 + Math.Min(Math.Min(Math.Min(i,j),m-i-1),n-j-1);
}
return matrix;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.