ให้เมทริกซ์จำนวนเต็ม งานคือนับความถี่ของตัวเลข k ในเมทริกซ์ ขนาดเมทริกซ์ขึ้นอยู่กับผู้ใช้ โปรแกรมนี้ใช้ 4x4 เมทริกซ์สร้างจากเงื่อนไข matrix(i,j) = i+j โดยดัชนีเริ่มต้นที่ 0,0
อินพุต − size = 4, k = 4
เอาต์พุต − count of 4 in given matrix 4x4 is 3
คำอธิบาย − เมทริกซ์ 4x4 ค่าคือ 0,1,2,3 / 1,2,3,4 / 2,3,4,5 / 3,4,5,6 เลข 4 ปรากฏ 3 ครั้ง
อินพุต − size = 3, k = 1
เอาต์พุต − count of 1 in given matrix 3x3 is 2
แนวทาง
รับขนาดเมทริกซ์และค่า k
สร้างเมทริกซ์ด้วย matrix[i][j] = i+j
นับจำนวนที่เท่ากับ k
ตัวอย่าง
#include <cmath>
#include <iostream>
using namespace std;
int count(int size, int k){
int count = 0;
int matrix[size][size];
for(int i = 0; i<size; i++)
for(int j=0; j<size; j++) {
matrix[i][j] = i+j;
if(matrix[i][j] == k) count++;
}
return count;
}
int main(){
int size = 4, k = 4;
int total = count(size, k);
if(total>0) cout<<"Count of frequency of "<<k<<" in a matrix of size "<<size<<"X"<<size<<" where matrix(i, j) = i+j is: "<<total;
else cout<<"Frequency of element is 0 that means it is not present in a matrix";
}
เอาต์พุต
Count of frequency of 4 in a matrix of size 4X4 where matrix(i, j) = i+j is: 3