Dada una array arr con elementos únicos, la tarea es contar el número total de pares de elementos que tienen el mismo conjunto de bits.
Ejemplos:
Entrada: arr[] = {2, 5, 8, 1, 3}
Salida: 4
Los recuentos de bits establecidos para {2, 5, 8, 1, 3} son {1, 2, 1, 1, 2}
Todos los pares con el mismo conjunto de bits son {2, 8}, {2, 1}, {5, 3}, {8, 1}
Entrada: arr[] = {1, 11, 7, 3}
Salida: 1
Solo par posible es {11, 7}
Acercarse:
- Recorra la array de izquierda a derecha y cuente el número total de bits establecidos de cada entero.
- Use un mapa para almacenar el número de elementos con el mismo recuento de bits establecidos con bits establecidos como clave y recuento como valor.
- Luego iterar a través de los elementos del mapa y calcular cuántos pares de dos elementos se pueden formar a partir de n elementos (para cada elemento del mapa), es decir , (n * (n-1)) / 2 .
- El resultado final será la suma de la salida del paso anterior para cada elemento del mapa.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of above approach #include <bits/stdc++.h> using namespace std; // Function to count all pairs // with equal set bits count int totalPairs(int arr[], int n) { // map to store count of elements // with equal number of set bits map<int, int> m; for (int i = 0; i < n; i++) { // inbuilt function that returns the // count of set bits of the number m[__builtin_popcount(arr[i])]++; } map<int, int>::iterator it; int result = 0; for (it = m.begin(); it != m.end(); it++) { // there can be (n*(n-1)/2) unique two- // element pairs to choose from n elements result += (*it).second * ((*it).second - 1) / 2; } return result; } // Driver code int main() { int arr[] = { 7, 5, 3, 9, 1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << totalPairs(arr, n); return 0; }
Java
import java.util.*; class GFG { /* Function to get no of set bits in binary representation of passed binary no. */ static int countSetBits(int n) { int count = 0; while (n > 0) { n &= (n - 1) ; count++; } return count; } // Function to count all pairs // with equal set bits count static int totalPairs(int arr[], int n) { // map to store count of elements // with equal number of set bits HashMap<Integer, Integer> m = new HashMap<>(); for (int i = 0; i < n; i++) { // function that returns the // count of set bits of the number int count = countSetBits(arr[i]); if(m.containsKey(count)) m.put(count, m.get(count) + 1); else m.put(count, 1); } int result = 0; for (Map.Entry<Integer, Integer> entry : m.entrySet()) { int value = entry.getValue(); // there can be (n*(n-1)/2) unique two- // element pairs to choose from n elements result += ((value * (value -1)) / 2); } return result; } public static void main (String[] args) { int arr[] = { 7, 5, 3, 9, 1, 2 }; int n = arr.length; System.out.println(totalPairs(arr, n)); } }
Python3
# Python3 implementation of the above approach # Function to count all pairs # with equal set bits count def totalPairs(arr, n): # map to store count of elements # with equal number of set bits m = dict() for i in range(n): # inbuilt function that returns the # count of set bits of the number x = bin(arr[i]).count('1') m[x] = m.get(x, 0) + 1; result = 0 for it in m: # there can be (n*(n-1)/2) unique two- # element pairs to choose from n elements result+= (m[it] * (m[it] - 1)) // 2 return result # Driver code arr = [7, 5, 3, 9, 1, 2] n = len(arr) print(totalPairs(arr, n)) # This code is contributed by mohit kumar
C#
// C# program to rearrange a string so that all same // characters become atleast d distance away using System; using System.Collections.Generic; class GFG { /* Function to get no of set bits in binary representation of passed binary no. */ static int countSetBits(int n) { int count = 0; while (n > 0) { n &= (n - 1) ; count++; } return count; } // Function to count all pairs // with equal set bits count static int totalPairs(int []arr, int n) { // map to store count of elements // with equal number of set bits Dictionary<int,int> mp = new Dictionary<int,int>(); for (int i = 0 ; i < n; i++) { // function that returns the // count of set bits of the number int count = countSetBits(arr[i]); if(mp.ContainsKey(count)) { var val = mp[count]; mp.Remove(count); mp.Add(count, val + 1); } else { mp.Add(count, 1); } } int result = 0; foreach(KeyValuePair<int, int> entry in mp){ int values = entry.Value; // there can be (n*(n-1)/2) unique two- // element pairs to choose from n elements result += ((values * (values -1)) / 2); } return result; } // Driver code public static void Main (String[] args) { int []arr = { 7, 5, 3, 9, 1, 2 }; int n = arr.Length; Console.WriteLine(totalPairs(arr, n)); } } // This code is contributed by Princi Singh
Javascript
<script> // Javascript implementation of above approach /* Function to get no of set bits in binary representation of passed binary no. */ function countSetBits(n) { var count = 0; while (n > 0) { n &= (n - 1) ; count++; } return count; } // Function to count all pairs // with equal set bits count function totalPairs(arr, n) { // map to store count of elements // with equal number of set bits var m = new Map(); for (var i = 0; i < n; i++) { // inbuilt function that returns the // count of set bits of the number if(m.has(arr[i])) { m.set(countSetBits(arr[i]), m.get(countSetBits(arr[i]))+1); } else{ m.set(countSetBits(arr[i]), 1); } } var result = 0; m.forEach((value, key) => { // there can be (n*(n-1)/2) unique two- // element pairs to choose from n elements result += parseInt(key * (key - 1) / 2); }); return result; } // Driver code var arr = [7, 5, 3, 9, 1, 2 ]; var n = arr.length; document.write( totalPairs(arr, n)); </script>
Producción:
4
Publicación traducida automáticamente
Artículo escrito por Shashank_Sharma y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA