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

นับจำนวนสมาชิกน้อยกว่าหรือเท่ากับ x ในเมทริกซ์ที่เรียงแล้วใน C++


ให้เมทริกซ์ขนาด n x n จำนวนเต็ม x และสมาชิกในเมทริกซ์เรียงลำดับแล้ว งานคือนับจำนวนสมาชิกที่น้อยกว่าหรือเท่ากับ x

อินพุต − matrix[3][3] = {{1,2,3},{4,5,6},{6,7,8}} และ X = 4

เอาต์พุต − count is 4

คำอธิบาย − สมาชิกน้อยกว่าหรือเท่ากับ 4 คือ 1,2,3,4 รวม 4 ตัว

อินพุต − matrix[3][3] = {{1,2,3},{4,5,6},{6,7,8}} และ X = 0

เอาต์พุต − count is 0

แนวทาง

  • รับขนาดเมทริกซ์และสร้างเมทริกซ์

  • วนลูปแถวและคอลัมน์ ตรวจสอบ matrix[i][j] <= x นับจำนวน

  • คืนค่าผลรวม

ตัวอย่าง

#include <bits/stdc++.h> 
using namespace std; 
#define size 3 

int count(int matrix[size][size], int x){ 
    int count=0; 
    for(int i = 0; i<size; i++) 
        for (int j = 0; j<size; j++) 
            if(matrix[i][j] <= x) count++; 
    return count; 
} 

int main(){ 
    int matrix[size][size] = {{1,2,3},{4,5,6},{7,8,9}}; 
    int x = 5; 
    cout<<"Count of elements smaller than or equal to x in a sorted matrix is: "<<count(matrix,x); 
    return 0; 
}

เอาต์พุต

Count of elements smaller than or equal to x in a sorted matrix is: 5