Cプログラムの配列に最大AND値のペアを出力します。
n個の正の整数の配列が与えられた問題によると、配列から最大のAND値を持つペアを見つける必要があります。
例
Input: arr[] = { 4, 8, 12, 16 }
Output: pair = 8 12
The maximum and value= 8
Input:arr[] = { 4, 8, 16, 2 }
Output: pair = No possible AND
The maximum and value = 0 最大AND値を見つけることは、配列内の最大AND値を見つけることと似ています。プログラムは、取得されたAND値をもたらす要素のペアを見つける必要があります。要素を見つけるには、配列全体をトラバースして、取得した最大AND値(結果)を持つ各要素のAND値を見つけます。arr[i]&result ==resultの場合、arr[i]が次の要素になることを意味します。最大AND値を生成します。また、最大AND値(結果)がゼロの場合は、「不可能」と出力する必要があります。
アルゴリズム
int checkBit(int pattern, int arr[], int n) START STEP 1: DECLARE AND INITIALIZE count AS 0 STEP 2: LOOP FOR i = 0 AND i < n AND i++ IF (pattern & arr[i]) == pattern THEN, INCREMENT count BY 1 STEP 3: RETURN count STOP int maxAND(int arr[], int n) START STEP 1: DECLARE AND INITIALIZE res = 0 AND count STEP 2: LOOP FOR bit = 31 AND bit >= 0 AND bit-- count = GOTO FUNCTION checkBit(res | (1 << bit), arr,n) IF count >= 2 THEN, res |= (1 << bit); END IF IF res == 0 PRINT "no possible AND” ELSE PRINT "Pair with maximum AND= " count = 0; LOOP FOR int i = 0 AND i < n && count < 2 AND i++ IF (arr[i] & res) == res THEN, INCREMENT count BY 1 PRINT arr[i] END IF END FOR END FOR RETURN res STOP
例
#include <stdio.h>
int checkBit(int pattern, int arr[], int n){
int count = 0;
for (int i = 0; i < n; i++)
if ((pattern & arr[i]) == pattern)
count++;
return count;
}
// Function for finding maximum AND value pair
int maxAND(int arr[], int n){
int res = 0, count;
for (int bit = 31; bit >= 0; bit--) {
count = checkBit(res | (1 << bit), arr, n);
if (count >= 2)
res |= (1 << bit);
}
if (res == 0) //if there is no pair available
printf("no possible and\n");
else { //Printing the pair available
printf("Pair with maximum AND= ");
count = 0;
for (int i = 0; i < n && count < 2; i++) {
// incremnent count value after
// printing element
if ((arr[i] & res) == res) {
count++;
printf("%d ", arr[i]);
}
}
}
return res;
}
int main(int argc, char const *argv[]){
int arr[] = {5, 6, 2, 8, 9, 12};
int n = sizeof(arr)/sizeof(arr[0]);
int ma = maxAND(arr, n);
printf("\nThe maximum AND value= %d ", ma);
return 0;
} 出力
上記のプログラムを実行すると、次の出力が生成されます-
pair = 8 9 The maximum and value= 8
-
配列の左回転をCプログラムのO(n)時間とO(1)空間で出力します。
いくつかのサイズnと複数の整数値の配列が与えられているので、与えられたインデックスkから配列を回転させる必要があります。 -のようなインデックスkから配列を回転させたい 例 Input: arr[] = {1, 2, 3, 4, 5} K1 = 1 K2 = 3 K3 = 6 Output: 2 3 4 5 1 4 5 1 2 3 2 3 4 5 1 アルゴリズム START Step 1 -> Declare functio
-
Cプログラムで、配列内の最後に出現する要素を相対的な順序で出力します。
要素を含む配列a[]が与えられ、タスクは、リスト内の指定された要素の最後の出現を出力することです。ここでは、重複する要素を削除するだけでなく、配列内の要素が最後に発生したときの順序を維持する必要があります。 6つの要素の配列があり、いくつかの重複する値、つまり{1,3、2、3、1、2}も含まれているため、結果は312の形式になります。 例 Input: a[]={4,2,2,4,1,5,1} Output : 2 4 5 1 アルゴリズム START Step 1-> Declare function void printelements(int a[], int n) &nbs