简体   繁体   中英

How do I turn an ordering pair into a 3x3 matrix in using 2D arrays c++

I'm trying to turn an ordered pair of numbers into a 3x3 matrix and am having troubles writing the conversion.

I've tried multiple variations of nested for loops to solve this issue, but I'm not getting the desired results.

This is my current attempt:

  for(i = 0; i < 6; i++) {
    row = matrixAin[i][0];
    col = matrixAin[i][1];

    for(j = 1; j <= row; j++) {
      for(int k = 1; k <= col; k++) {
        matrixA[j][k] = 1;
      }
    }
  }

This is all the code I have:

  #include <iostream>
  using namespace std;

  int main() {

    int matrixAin[6][2]; // ordered pair of Matrix A
    int matrixA[3][3];   // 3x3 matrix of Matrix A
    int i, j, row, col;  // for the for loops

    // Sets Matrix A & B values to 0
    for (i = 0; i < 3; i++) {
        for(j = 0; j < 3; j++) {
            matrixA[i][j] = 0;
            matrixB[i][j] = 0;
        }
    }

    // input of Matrix A
    cout << "Please input the ordered pairs for matrix A: ";
    for (i = 0; i < 6; i++) {
        cin >> matrixAin[i][0] >> matrixAin[i][1]; // row , col
    }

    // sets row / col to 1 for Matrix 3x3
    // this is the code with the issue
    for(i = 0; i < 6; i++) {
        row = matrixAin[i][0];
        col = matrixAin[i][1];

        for(j = 1; j <= row; j++) {
            for(int k = 1; k <= col; k++) {
                matrixA[j-1][k] = 1;
            }
        }
    }

    // Displays matrix A
    cout << "A= ";
    for(int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            cout << matrixA[i][j] << ' ';
        }
        cout << endl;
    }

}

This is what the input for this matrix should look like

Please input the ordered pairs for matrix A:

1 2

1 3

2 1

2 2

3 2

3 3

This is the expected results:

A =

0 1 1

1 1 0

0 1 1

Your current code takes in each pair and then for each subrectangle of size row x col , sets the area of the rectangle to 1. It's really close. You just need to set once for each ordered pair:

for(i = 0; i < 6; i++) {
    row = matrixAin[i][0];
    col = matrixAin[i][1];
    matrixA[row - 1][col - 1] = 1;
}

Replace the inner for-loop with matrixA[row - 1][col - 1] = 1; . Do not forget to check if col and row are between 1 and 3.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM