Untitled
unknown
plain_text
a year ago
2.4 kB
11
Indexable
#include <iostream>
#include <vector>
using namespace std;
void printMatrixWithParity(const vector<vector<int> >& matrix) {
int rows = matrix.size();
int cols = matrix[0].size();
// Create a new matrix with an additional row and column for parity bits
vector<vector<int> > parityMatrix(rows + 1, vector<int> (cols + 1));
// Fill the original matrix and calculate row parity
for (int i = 0; i < rows; ++i) {
int rowParity = 0;
for (int j = 0; j < cols; ++j) {
parityMatrix[i][j] = matrix[i][j];
rowParity ^= matrix[i][j]; // Calculate row parity (XOR)
}
parityMatrix[i][cols] = rowParity; // Store row parity in the last column
}
// Calculate column parity
for (int j = 0; j < cols; ++j) {
int colParity = 0;
for (int i = 0; i < rows; ++i) {
colParity ^= parityMatrix[i][j]; // Calculate column parity (XOR)
}
parityMatrix[rows][j] = colParity; // Store column parity in the last row
}
// Set the bottom-right cell to the overall parity
int overallParity = 0;
for (int i = 0; i < cols; ++i) {
overallParity ^= parityMatrix[rows][i];
}
parityMatrix[rows][cols] = overallParity; // Overall parity
// Print the matrix with parity bits
for (int i = 0; i <= rows; ++i) {
for (int j = 0; j <= cols; ++j) {
cout << parityMatrix[i][j] << " ";
}
cout << endl;
}
}
int main() {
int rows, cols;
cout << "Enter number of rows: ";
cin >> rows;
cout << "Enter number of columns: ";
cin >> cols;
// Initialize the matrix
vector<vector<int> > matrix(rows, vector<int> (cols));
// Input the matrix from the user
cout << "Enter the binary matrix (0s and 1s only):\n";
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> matrix[i][j];
// Validate input (optional)
if (matrix[i][j] != 0 && matrix[i][j] != 1) {
cout << "Invalid input. Please enter 0 or 1.\n";
--j; // Decrement j to retry the input for the same position
}
}
}
cout << "Matrix with 2D Parity:\n";
printMatrixWithParity(matrix);
return 0;
}
Editor is loading...
Leave a Comment