Suma de Bitwise AND de cada elemento de la array con los elementos de otra array

Dadas dos arrays arr1[] de tamaño M y arr2[] de tamaño N , la tarea es encontrar la suma de AND bit a bit de cada elemento de arr1[] con los elementos de la array arr2[]

Ejemplos:

Entrada: arr1[] = {1, 2, 3}, arr2[] = {1, 2, 3}, M = 3, N = 3
Salida: 2 4 6
Explicación:
Para elementos en el índice 0 en arr1[], Suma = arr1[0] & arr2[0] + arr1[0] & arr2[1] + arr1[0] & arr2[2], Suma = 1 & 1 + 1 & 2 + 1 & 3 = 2
Para elementos en índice 1 en arr1[], Sum = arr1[1] & arr2[0] + arr1[1] & arr2[1] + arr1[1] & arr2[2], Sum= 2 & 1 + 2 & 2 + 2 & 3 = 4
Para elementos en el índice 2 en arr1[], Sum = arr1[2] & arr2[0] + arr1[2] & arr2[1] + arr1[2] & arr2[2], Sum= 3 & 1 + 3 y 2 + 3 y 3 = 6

Entrada: arr1[] = {2, 4, 8, 16}, arr2[] = {2, 4, 8, 16}, M = 4, N = 4
Salida: 2 4 8 16

Enfoque ingenuo: el enfoque más simple para resolver el problema es recorrer la array arr1[] y, para cada elemento de la array arr1[] , recorrer la array arr2[] y calcular la suma de Bitwise Y de los elementos actuales de arr1[] con todos los elementos de arr2[] para cada elemento 

Tiempo Complejidad: O(N 2 )
Espacio Auxiliar: O(N)

Enfoque eficiente: la idea es utilizar la manipulación de bits para resolver el problema anterior. Suponga que cada elemento de la array se puede representar usando solo 32 bits.

  • De acuerdo con la propiedad AND bit a bit , mientras se realiza la operación, el i -ésimo bit se establecerá bit solo cuando ambos números tengan un bit establecido en la i -ésima posición, donde 0≤i<32 . 
  • Por lo tanto, para un número en arr1[], si el i -ésimo bit es un bit establecido, entonces el i -ésimo lugar contribuirá con una suma de K*2 i , donde K es el número total de números en arr2[] habiendo establecido el bit en la i -ésima posición.

Siga los pasos a continuación para resolver el problema:

  1. Inicialice una frecuencia de array de enteros [] para almacenar el recuento de números en arr2 [] habiendo establecido el bit en la i -ésima posición donde 0≤i<32
  2. Recorra la array arr2[] y para cada elemento represéntelo en forma binaria e incremente el conteo en la array de frecuencia[] en uno en la posición que tiene 1 en la representación binaria .
  3. Atraviesa la array arr1[]
    1. Inicialice una variable entera bitwise_AND_sum con 0 .
    2. Traverse en el rango [0, 31] usando una variable j .
    3. Si el j -ésimo bit se establece en bit en la representación binaria de arr2[i] , entonces incremente bitwise_AND_sum por la frecuencia[j]*2 j .
    4. Imprime la suma obtenida, es decir, bitwise_AND_sum .

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to compute the AND sum
// for each element of an array
void Bitwise_AND_sum_i(int arr1[], int arr2[], int M, int N)
{
 
    // Declaring an array of
    // size 32 for storing the
    // count of each bit
    int frequency[32] = { 0 };
 
    // Traverse the array arr2[]
    // and store the count of a
    // bit in frequency array
    for (int i = 0; i < N; i++) {
 
        // Current bit position
        int bit_position = 0;
        int num = arr1[i];
 
        // While num is greater
        // than 0
        while (num) {
 
            // Checks if ith bit is
            // set or not
            if (num & 1) {
 
                // Increment the count of
                // bit by one
                frequency[bit_position] += 1;
            }
 
            // Increment the bit position
            // by one
            bit_position += 1;
 
            // Right shift the num by one
            num >>= 1;
        }
    }
 
    // Traverse in the arr2[]
    for (int i = 0; i < M; i++) {
 
        int num = arr2[i];
 
        // Store the ith bit
        // value
        int value_at_that_bit = 1;
 
        // Total required sum
        int bitwise_AND_sum = 0;
 
        // Traverse in the range [0, 31]
        for (int bit_position = 0; bit_position < 32;
             bit_position++) {
 
            // Checks if current bit is set
            if (num & 1) {
 
                // Increment the bitwise sum
                // by frequency[bit_position]
                // * value_at_that_bit;
                bitwise_AND_sum += frequency[bit_position]
                                   * value_at_that_bit;
            }
 
            // Right shift num by one
            num >>= 1;
 
            // Left shift vale_at_that_bit by one
            value_at_that_bit <<= 1;
        }
 
        // Print the sum obtained for ith
        // number in arr1[]
        cout << bitwise_AND_sum << ' ';
    }
 
    return;
}
 
// Driver Code
int main()
{
 
    // Given arr1[]
    int arr1[] = { 1, 2, 3 };
 
    // Given arr2[]
    int arr2[] = { 1, 2, 3 };
 
    // Size of arr1[]
    int N = sizeof(arr1) / sizeof(arr1[0]);
 
    // Size of arr2[]
    int M = sizeof(arr2) / sizeof(arr2[0]);
 
    // Function Call
    Bitwise_AND_sum_i(arr1, arr2, M, N);
 
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
class GFG
{
   
      // Driver Code
    public static void main(String[] args)
    {
       
        // Given arr1[]
        int[] arr1 = { 1, 2, 3 };
 
        // Given arr2[]
        int[] arr2 = { 1, 2, 3 };
 
        // Size of arr1[]
        int N = arr1.length;
 
        // Size of arr2[]
        int M = arr2.length;
 
        // Function Call
        Bitwise_AND_sum_i(arr1, arr2, M, N);
    }
 
    // Function to compute the AND sum
    // for each element of an array
    static void Bitwise_AND_sum_i(int arr1[], int arr2[],
                                  int M, int N)
    {
 
        // Declaring an array of
        // size 32 for storing the
        // count of each bit
        int[] frequency = new int[32];
 
        // Traverse the array arr2[]
        // and store the count of a
        // bit in frequency array
        for (int i = 0; i < N; i++)
        {
 
            // Current bit position
            int bit_position = 0;
            int num = arr1[i];
 
            // While num is greater
            // than 0
            while (num != 0)
            {
 
                // Checks if ith bit is
                // set or not
                if ((num & 1) != 0)
                {
 
                    // Increment the count of
                    // bit by one
                    frequency[bit_position] += 1;
                }
 
                // Increment the bit position
                // by one
                bit_position += 1;
 
                // Right shift the num by one
                num >>= 1;
            }
        }
 
        // Traverse in the arr2[]
        for (int i = 0; i < M; i++)
        {
            int num = arr2[i];
 
            // Store the ith bit
            // value
            int value_at_that_bit = 1;
 
            // Total required sum
            int bitwise_AND_sum = 0;
 
            // Traverse in the range [0, 31]
            for (int bit_position = 0; bit_position < 32;
                 bit_position++)
            {
 
                // Checks if current bit is set
                if ((num & 1) != 0)
                {
 
                    // Increment the bitwise sum
                    // by frequency[bit_position]
                    // * value_at_that_bit;
                    bitwise_AND_sum
                        += frequency[bit_position]
                           * value_at_that_bit;
                }
 
                // Right shift num by one
                num >>= 1;
 
                // Left shift vale_at_that_bit by one
                value_at_that_bit <<= 1;
            }
 
            // Print the sum obtained for ith
            // number in arr1[]
            System.out.print( bitwise_AND_sum + " ");
        }
    }
}
 
// This code is contributed by Dharanendra L V

Python3

# Python3 program for the above approach
 
# Function to compute the AND sum
# for each element of an array
def Bitwise_AND_sum_i(arr1, arr2, M, N):
 
    # Declaring an array of
    # size 32 for storing the
    # count of each bit
    frequency = [0]*32
 
    # Traverse the array arr2[]
    # and store the count of a
    # bit in frequency array
    for i in range(N):
 
        # Current bit position
        bit_position = 0
        num = arr1[i]
 
        # While num is greater
        # than 0
        while (num):
 
            # Checks if ith bit is
            # set or not
            if (num & 1):
 
                # Increment the count of
                # bit by one
                frequency[bit_position] += 1
 
            # Increment the bit position
            # by one
            bit_position += 1
 
            # Right shift the num by one
            num >>= 1
 
    # Traverse in the arr2[]
    for i in range(M):
        num = arr2[i]
 
        # Store the ith bit
        # value
        value_at_that_bit = 1
 
        # Total required sum
        bitwise_AND_sum = 0
 
        # Traverse in the range [0, 31]
        for bit_position in range(32):
 
            # Checks if current bit is set
            if (num & 1):
 
                # Increment the bitwise sum
                # by frequency[bit_position]
                # * value_at_that_bit
                bitwise_AND_sum += frequency[bit_position] * value_at_that_bit
 
            # Right shift num by one
            num >>= 1
 
            # Left shift vale_at_that_bit by one
            value_at_that_bit <<= 1
 
        # Print sum obtained for ith
        # number in arr1[]
        print(bitwise_AND_sum, end = " ")
    return
 
# Driver Code
if __name__ == '__main__':
 
    # Given arr1[]
    arr1 = [1, 2, 3]
 
    # Given arr2
    arr2 = [1, 2, 3]
 
    # Size of arr1[]
    N = len(arr1)
 
    # Size of arr2[]
    M = len(arr2)
 
    # Function Call
    Bitwise_AND_sum_i(arr1, arr2, M, N)
 
# This code is contributed by mohit kumar 29

C#

// C# program for the above approach
using System;
class GFG
{
 
      // Driver code
    static public void Main()
    {
 
        // Given arr1[]
        int[] arr1 = { 1, 2, 3 };
 
        // Given arr2[]
        int[] arr2 = { 1, 2, 3 };
 
        // Size of arr1[]
        int N = arr1.Length;
 
        // Size of arr2[]
        int M = arr2.Length;
 
        // Function Call
        Bitwise_AND_sum_i(arr1, arr2, M, N);
    }
 
    // Function to compute the AND sum
    // for each element of an array
    static void Bitwise_AND_sum_i(int[] arr1, int[] arr2,
                                  int M, int N)
    {
 
        // Declaring an array of
        // size 32 for storing the
        // count of each bit
        int[] frequency = new int[32];
 
        // Traverse the array arr2[]
        // and store the count of a
        // bit in frequency array
        for (int i = 0; i < N; i++)
        {
 
            // Current bit position
            int bit_position = 0;
            int num = arr1[i];
 
            // While num is greater
            // than 0
            while (num != 0)
            {
 
                // Checks if ith bit is
                // set or not
                if ((num & 1) != 0)
                {
 
                    // Increment the count of
                    // bit by one
                    frequency[bit_position] += 1;
                }
 
                // Increment the bit position
                // by one
                bit_position += 1;
 
                // Right shift the num by one
                num >>= 1;
            }
        }
 
        // Traverse in the arr2[]
        for (int i = 0; i < M; i++)
        {
 
            int num = arr2[i];
 
            // Store the ith bit
            // value
            int value_at_that_bit = 1;
 
            // Total required sum
            int bitwise_AND_sum = 0;
 
            // Traverse in the range [0, 31]
            for (int bit_position = 0; bit_position < 32;
                 bit_position++) {
 
                // Checks if current bit is set
                if ((num & 1) != 0)
                {
 
                    // Increment the bitwise sum
                    // by frequency[bit_position]
                    // * value_at_that_bit;
                    bitwise_AND_sum
                        += frequency[bit_position]
                           * value_at_that_bit;
                }
 
                // Right shift num by one
                num >>= 1;
 
                // Left shift vale_at_that_bit by one
                value_at_that_bit <<= 1;
            }
 
            // Print the sum obtained for ith
            // number in arr1[]
            Console.Write(bitwise_AND_sum + " ");
        }
    }
}
 
// The code is contributed by Dharanendra L V

Javascript

<script>
// Javascript program for the above approach
 
// Function to compute the AND sum
// for each element of an array
function Bitwise_AND_sum_i(arr1, arr2, M, N) {
 
    // Declaring an array of
    // size 32 for storing the
    // count of each bit
    let frequency = new Array(32).fill(0);
 
    // Traverse the array arr2[]
    // and store the count of a
    // bit in frequency array
    for (let i = 0; i < N; i++) {
 
        // Current bit position
        let bit_position = 0;
        let num = arr1[i];
 
        // While num is greater
        // than 0
        while (num) {
 
            // Checks if ith bit is
            // set or not
            if (num & 1) {
 
                // Increment the count of
                // bit by one
                frequency[bit_position] += 1;
            }
 
            // Increment the bit position
            // by one
            bit_position += 1;
 
            // Right shift the num by one
            num >>= 1;
        }
    }
 
    // Traverse in the arr2[]
    for (let i = 0; i < M; i++) {
 
        let num = arr2[i];
 
        // Store the ith bit
        // value
        let value_at_that_bit = 1;
 
        // Total required sum
        let bitwise_AND_sum = 0;
 
        // Traverse in the range [0, 31]
        for (let bit_position = 0; bit_position < 32; bit_position++) {
 
            // Checks if current bit is set
            if (num & 1) {
 
                // Increment the bitwise sum
                // by frequency[bit_position]
                // * value_at_that_bit;
                bitwise_AND_sum += frequency[bit_position] * value_at_that_bit;
            }
 
            // Right shift num by one
            num >>= 1;
 
            // Left shift vale_at_that_bit by one
            value_at_that_bit <<= 1;
        }
 
        // Print the sum obtained for ith
        // number in arr1[]
        document.write(bitwise_AND_sum + ' ');
    }
 
    return;
}
 
// Driver Code
 
// Given arr1[]
let arr1 = [1, 2, 3];
 
// Given arr2[]
let arr2 = [1, 2, 3];
 
// Size of arr1[]
let N = arr1.length;
 
// Size of arr2[]
let M = arr2.length
 
// Function Call
Bitwise_AND_sum_i(arr1, arr2, M, N);
 
 
 
// This code is contributed by _saurabh_jaiswal
</script>
Producción: 

2 4 6

 

Complejidad de Tiempo: O(N * 32)
Espacio Auxiliar: O(N * 32) 

Publicación traducida automáticamente

Artículo escrito por nk14646 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *