কম্পিউটার টিউটোরিয়াল

সি প্রোগ্রামিং-এ অ্যারে থেকে সর্বোচ্চ AND ভ্যালু 가진 জোড়া (Pair) বের করা


n সংখ্যক পজিটিভ ইন্টিজার অ্যারে দেওয়া থাকলে, সর্বোচ্চ AND ভ্যালু দেওয়া জোড়া (pair) বের করতে হবে।

উদাহরণ

Input: arr[] = {4, 8, 12, 16}
Output: pair = 8 12, Maximum AND value = 8

Input: arr[] = {4, 8, 16, 2}
Output: pair = No possible AND, Maximum AND value = 0

সর্বোচ্চ AND ভ্যালু বের করা একটি অ্যারের সর্বোচ্চ AND ভ্যালু বের করার মতোই। জোড়া বের করতে পুরো অ্যারে ট্রাভার্স করে প্রতিটি এলিমেন্টের সাথে সর্বোচ্চ AND ভ্যালু (result) AND করলে যদি ফলাফল result হয়, তবে সেটি জোড়ার অংশ। যদি result ০ হয়, তবে "Not possible" প্রিন্ট করা হবে।

অ্যালগরিদম

int checkBit(int pattern, int arr[], int n)
    count = 0
    FOR i = 0 to n-1
        IF (pattern & arr[i]) == pattern THEN count++
    RETURN count

int maxAND(int arr[], int n)
    res = 0
    FOR bit = 31 down to 0
        count = checkBit(res | (1 << bit), arr, n)
        IF count >= 2 THEN res |= (1 << bit)
    IF res == 0 PRINT "no possible AND"
    ELSE
        PRINT "Pair with maximum AND= "
        count = 0
        FOR i = 0 to n-1 AND count < 2
            IF (arr[i] & res) == res THEN count++, PRINT arr[i]
    RETURN res

সি প্রোগ্রাম

#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;
}

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)
        printf("no possible and\n");
    else {
        printf("Pair with maximum AND= ");
        count = 0;
        for (int i = 0; i < n && count < 2; i++) {
            if ((arr[i] & res) == res) {
                count++;
                printf("%d ", arr[i]);
            }
        }
    }
    return res;
}

int main() {
    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

  1. C প্রোগ্রাম: অ্যারে-এর উপাদানগুলোর গুণফল (Product) বের করা

  2. C প্রোগ্রামে দেওয়া আকারের সর্বোচ্চ যোগফলযুক্ত সাব-ম্যাট্রিক্স বের করা

  3. C প্রোগ্রামে অ্যারে লেফ্ট রোটেশন O(n) টাইম ও O(1) স্পেসে

  4. C প্রোগ্রামে অ্যারেতে উপাদানগুলোর শেষ অকরেন্স রিলেটিভ অর্ডারে প্রিন্ট করা