จากปัญหาดังกล่าว เราได้รับอาร์เรย์ของจำนวนเต็มบวก 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 สำหรับการค้นหาค่า Maximum AND จะคล้ายกับการหาค่า Maximum AND ในอาร์เรย์ โปรแกรมจะต้องค้นหาคู่ขององค์ประกอบที่ส่งผลให้ได้รับและค่า สำหรับการค้นหาองค์ประกอบ เพียงสำรวจทั้งอาร์เรย์และค้นหาค่า AND ของแต่ละองค์ประกอบด้วยค่า AND สูงสุด (ผลลัพธ์) ที่ได้รับ และหาก arr[i] &ผล ==ผลลัพธ์ แสดงว่า arr[i] เป็นองค์ประกอบที่จะ สร้างมูลค่าสูงสุดและ นอกจากนี้ ในกรณีที่ค่าสูงสุด 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