ให้เมทริกซ์สี่เหลี่ยมจัตุรัส mat[][] ให้องค์ประกอบของเมทริกซ์ me mat[i][j] =i*j ภารกิจคือการนับจำนวนองค์ประกอบใน เมทริกซ์เท่ากับ x
เมทริกซ์เป็นเหมือนอาร์เรย์ 2 มิติที่แสดงตัวเลขหรือองค์ประกอบเป็นแถวและคอลัมน์
ดังนั้นมาทำความเข้าใจวิธีแก้ปัญหาด้วยความช่วยเหลือของตัวอย่าง -
ป้อนข้อมูล −
matrix[row][col] = { {1, 2, 3}, {3, 4, 3}, {3, 4, 5}}; x = 3
ผลผลิต −
Count of entries equal to x in a special matrix: 4
ป้อนข้อมูล −
matrix[row][col] = { {10, 20, 30}, {30, 40, 30}, {30, 40, 50}}; x = 30
ผลผลิต −
Count of entries equal to x in a special matrix: 4
แนวทางที่ใช้ในโปรแกรมด้านล่างดังนี้
-
ใช้เมทริกซ์ mat[][] และ x เป็นค่าอินพุต
-
ในการนับฟังก์ชัน เราจะนับจำนวนรายการ
-
สำรวจเมทริกซ์ทั้งหมด โดยคุณจะพบค่าของ mat[i][j] ==x แล้วเพิ่มจำนวนขึ้น 1
-
ส่งคืนค่าจำนวนและพิมพ์ออกมาเป็นผลลัพธ์
ตัวอย่าง
#include<bits/stdc++.h> using namespace std; #define row 3 #define col 3 //count the entries equal to X int count (int matrix[row][col], int x){ int count = 0; // traverse and find the factors for(int i = 0 ;i<row;i++){ for(int j = 0; j<col; j++){ if(matrix[i][j] == x){ count++; } } } // return count return count; } int main(){ int matrix[row][col] = { {1, 2, 3}, {3, 4, 3}, {3, 4, 5} }; int x = 3; cout<<"Count of entries equal to x in a special matrix: "<<count(matrix, x); return 0; }
ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น เราจะได้ผลลัพธ์ดังต่อไปนี้ -
Count of entries equal to x in a special matrix: 4