Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรมตรวจสอบว่าเมทริกซ์สองตัวเหมือนกันหรือไม่ใน C++


ให้เมทริกซ์สองตัว M1[r][c] และ M2[r][c] ที่มี 'r' แถว และ 'c' คอลัมน์ เราต้องตรวจสอบว่าทั้งสองเมทริกซ์เหมือนกันหรือไม่ หากเหมือนกันพิมพ์ "Matrices are identical" ไมเหมือนกันพิมพ์ "Matrices are not identical"

Identical Matrix

เมทริกซ์สองตัว M1 และ M2 จะเหมือนกันเมื่อ −

  • จำนวนแถวและคอลัมน์ของทั้งสองเมทริกซ์เท่ากัน
  • ค่า M1[i][j] เท่ากับ M2[i][j] ทุกค่า

เช่นในภาพด้านล่าง เมทริกซ์ m1 และ m2 ขนาด 3x3 เหมือนกัน −

$$M1[3][3]=\begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \\ \end {bmatrix} \:\:\:\:M2[3][3] =\begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \\ \end{bmatrix} $$

ตัวอย่าง

Input: a[n][n] = { {2, 2, 2, 2},   {2, 2, 2, 2},   {3,3, 3, 3},   {3,3, 3, 3}};   b[n][n]= { {2, 2, 2, 2},     {2, 2, 2, 2},     {3, 3, 3, 3},     {3, 3, 3, 3}}; Output: matrices are identical Input: a[n][n] = { {2, 2, 2, 2},   {2, 2, 1, 2},   {3,3, 3, 3},   {3,3, 3, 3}};   b[n][n]= { {2, 2, 2, 2},     {2, 2, 5, 2},     {3, 3, 3, 3},     {3, 3, 3, 3}}; Output: matrices are not identical

วิธีแก้

วนลูปทั้งสองเมทริกซ์ a[i][j] และ b[i][j] ตรวจสอบ a[i][j]==b[i][j] หากจริงสำหรับทุกค่า พิมพ์ว่าเหมือนกัน ไม่จริงพิมพ์ว่าไม่เหมือนกัน

อัลกอริทึม

Start Step 1 -> define macro as #define n 4 Step 2 -> Declare function to check matrix is same or not   int check(int a[][n], int b[][n])     declare int i, j     Loop For i = 0 and i < n and i++       Loop For j = 0 and j < n and j++         IF (a[i][j] != b[i][j])           return 0         End       End     End     return 1 Step 3 -> In main()   Declare variable asint a[n][n] = { {2, 2, 2, 2},     {2, 2, 2, 2},     {3, 3, 3, 3},     {3, 3, 3, 3}}   Declare another variable as int b[n][n] = { {2, 2, 2, 2},     {2, 2, 2, 2},     {3, 3, 3, 3},     {3, 3, 3, 3}}   IF (check(a, b))     Print matrices are identical   Else     Print matrices are not identical Stop

ตัวอย่าง

#include <bits/stdc++.h> #define n 4 using namespace std; // check matrix is same or not int check(int a[][n], int b[][n]){   int i, j;   for (i = 0; i < n; i++)     for (j = 0; j < n; j++)       if (a[i][j] != b[i][j])       return 0;   return 1; } int main(){   int a[n][n] = { {2, 2, 2, 2},     {2, 2, 2, 2},     {3, 3, 3, 3},     {3, 3, 3, 3}};   int b[n][n] = { {2, 2, 2, 2},     {2, 2, 2, 2},     {3, 3, 3, 3},     {3, 3, 3, 3}};   if (check(a, b))     cout << "matrices are identical";   else     cout << "matrices are not identical";   return 0; }

ผลลัพธ์

matrices are identical