C++のソートされた行列でx以下の要素をカウントします
入力 −
matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {6, 7, 8}} and X = 4 出力 −
count is 4
説明 −行列データを値xと一致させる必要があるため、x以下の要素、つまり4は1、2、3、4です。したがって、カウントは4です。
入力 −
matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {6, 7, 8}} and X = 0 出力 −
count is 0
説明 −行列データを値xと一致させる必要があるため、x以下の要素はありません。したがって、カウントは0です。
以下のプログラムで使用されているアプローチは次のとおりです
-
行列のサイズを入力してから、サイズnxnの行列を作成します
-
ループを開始します。0から行サイズまで
-
ループ内で、I、0から列サイズまでの別のループjを開始します
-
ここで、matrix [i] [j] =xかどうかを確認し、yesの場合は、カウントを1増やします。それ以外の場合は、条件を無視します
-
合計数を返す
-
結果を印刷します。
例
#include <bits/stdc++.h>
using namespace std;
#define size 3
//function to count the total elements
int count(int matrix[size][size], int x){
int count=0;
//traversing the matrix row-wise
for(int i = 0 ;i<size; i++){
for (int j = 0; j<size ; j++){
//check if value of matrix is less than or
//equals to the x
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
-
C++でソートされた配列内の小さい要素をカウントします
このチュートリアルでは、C++でソートされた配列内の小さな要素をカウントするプログラムについて説明します。 ここでは番号が与えられ、私たちのタスクは、指定された数よりも小さい、ソートされた配列に存在するすべての要素をカウントすることです。 例 #include <bits/stdc++.h> using namespace std; int countSmaller(int arr[], int n, int x){ return upper_bound(arr, arr+n, x) - arr; } int main(){ i
-
C++のマトリックスでソートされたすべての行をカウントします
このチュートリアルでは、行列内のすべてのソートされた行の数を見つけるプログラムについて説明します。 このために、m*n行列が提供されます。私たちのタスクは、昇順または降順で並べ替えられた、指定されたマトリックス内のすべての行をカウントすることです。 例 #include <bits/stdc++.h> #define MAX 100 using namespace std; //counting sorted rows int count_srows(int mat[][MAX], int r, int c){ int result = 0;