Upload
niraj-kumar
View
91
Download
3
Embed Size (px)
Citation preview
5/12/12 Program to count number of set bits in an (big) array | GeeksforGeeks
1/9www.geeksforgeeks.org/archives/11263
GeeksforGeeks
A computer science portal for geeks
HomeQ&AInterview CornerAsk a question
FeedbackContributeAbout us
SubscribeArraysArticlesBit MagicC/C++ PuzzlesGFactsLinked ListsMCQMiscOutputStringsTrees
Program to count number of set bits in an (big) array
March 12, 2011
Given an integer array of length N (an arbitrarily large number). How to count number of setbits in the array?
The simple approach would be, create an efficient method to count set bits in a word (mostprominent size, usually equal to bit length of processor), and add bits from individual elementsof array.
Various methods of counting set bits of an integer exists, see this for example. These methodsrun at best O(logN) where N is number of bits. Note that on a processor N is fixed, count canbe done in O(1) time on 32 bit machine irrespective of total set bits. Overall, the bits in arraycan be computed in O(n) time, where ‘n’ is array size.
5/12/12 Program to count number of set bits in an (big) array | GeeksforGeeks
2/9www.geeksforgeeks.org/archives/11263
However, a table look up will be more efficient method when array size is large. Storing table
look up that can handle 232 integers will be impractical.
The following code illustrates simple program to count set bits in a randomly generated 64 Kinteger array. The idea is to generate a look up for first 256 numbers (one byte), and breakevery element of array at byte boundary. A meta program using C/C++ preprocessorgenerates the look up table for counting set bits in a byte.
The mathematical derivation behind meta program is evident from the following table (Addthe column and row indices to get the number, then look into the table to get set bits in thatnumber. For example, to get set bits in 10, it can be extracted from row named as 8 andcolumn named as 2),
0, 1, 2, 3 0 - 0, 1, 1, 2 -------- GROUP_A(0) 4 - 1, 2, 2, 3 -------- GROUP_A(1) 8 - 1, 2, 2, 3 -------- GROUP_A(1)12 - 2, 3, 3, 4 -------- GROUP_A(2)16 - 1, 2, 2, 3 -------- GROUP_A(1)20 - 2, 3, 3, 4 -------- GROUP_A(2)24 - 2, 3, 3, 4 -------- GROUP_A(2)28 - 3, 4, 4, 5 -------- GROUP_A(3) ... so on
From the table, there is a patten emerging in multiples of 4, both in the table as well as in thegroup parameter. The sequence can be generalized as shown in the code.
Complexity:
All the operations takes O(1) except iterating over the array. The time complexity is O(n)where ‘n’ is size of array. Space complexity depends on the meta program that generates lookup.
Code:
#include <stdio.h>#include <stdlib.h>#include <time.h> /* Size of array 64 K */#define SIZE (1 << 16) /* Meta program that generates set bit count array of first 256 integers */ /* GROUP_A - When combined with META_LOOK_UP generates count for 4x4 elements */
5/12/12 Program to count number of set bits in an (big) array | GeeksforGeeks
3/9www.geeksforgeeks.org/archives/11263
#define GROUP_A(x) x, x + 1, x + 1, x + 2 /* GROUP_B - When combined with META_LOOK_UP generates count for 4x4x4 elements */ #define GROUP_B(x) GROUP_A(x), GROUP_A(x+1), GROUP_A(x+1), GROUP_A(x+2) /* GROUP_C - When combined with META_LOOK_UP generates count for 4x4x4x4 elements */ #define GROUP_C(x) GROUP_B(x), GROUP_B(x+1), GROUP_B(x+1), GROUP_B(x+2) /* Provide appropriate letter to generate the table */ #define META_LOOK_UP(PARAMETER) \ GROUP_##PARAMETER(0), \ GROUP_##PARAMETER(1), \ GROUP_##PARAMETER(1), \ GROUP_##PARAMETER(2) \ int countSetBits(int array[], size_t array_size){ int count = 0; /* META_LOOK_UP(C) - generates a table of 256 integers whose sequence will be number of bits in i-th position where 0 <= i < 256 */ /* A static table will be much faster to access */ static unsigned char const look_up[] = { META_LOOK_UP(C) }; /* No shifting funda (for better readability) */ unsigned char *pData = NULL; for(size_t index = 0; index < array_size; index++) { /* It is fine, bypass the type system */ pData = (unsigned char *)&array[index]; /* Count set bits in individual bytes */ count += look_up[pData[0]]; count += look_up[pData[1]]; count += look_up[pData[2]]; count += look_up[pData[3]]; } return count;
5/12/12 Program to count number of set bits in an (big) array | GeeksforGeeks
4/9www.geeksforgeeks.org/archives/11263
Contributed by Venki. Please write comments if you find anything incorrect, or you want toshare more information about the topic discussed above.
You may also like following posts
1. Count number of bits to be flipped to convert A to B2. Write an Efficient C Program to Reverse Bits of a Number3. Count set bits in an integer4. Rotate bits of a number5. Next higher number with same number of set bits
2 comments so far
1. pranav says:October 13, 2011 at 7:57 PM
please someone explain clearly GROUP_A, GROUP_B, etc. concept and meaning ofthe definition of :
} /* Driver program, generates table of random 64 K numbers */int main(){ int index; int random[SIZE]; /* Seed to the random-number generator */ srand((unsigned)time(0)); /* Generate random numbers. */ for( index = 0; index < SIZE; index++ ) { random[index] = rand(); } printf("Total number of bits = %d\n", countSetBits(random, SIZE)); return 0;}
Send 2people
5/12/12 Program to count number of set bits in an (big) array | GeeksforGeeks
5/9www.geeksforgeeks.org/archives/11263
#define META_LOOK_UP(PARAMETER) \GROUP_##PARAMETER(0), \GROUP_##PARAMETER(1), \GROUP_##PARAMETER(1), \GROUP_##PARAMETER(2) \
ReplyVenki says:October 14, 2011 at 12:41 AM
@pranav, the idea is to create table of 256 entries. The table contains number ofset bits in the sequential index of table. The macro META_LOOK_UP(C)generates the table. After preprocessing stage the definition of look_up will besomething like
static unsigned char const look_up[] = { 0, 1, 1, 2, 1, 2, 2, 3, ... 6, 7, 7, 8 };
The code in main, simply splits the array into individual bytes and looks up the bitcount value in the table.
Reply
Comment
Name (Required) Email (Required)
Website URI Your Comment (Writing code? please paste your
code between sourcecode tags)
[sourcecode language="C"]/* Paste your code here (You may delete these lines if not writing code) */[/sourcecode]
Have Your Say
Search
5/12/12 Program to count number of set bits in an (big) array | GeeksforGeeks
6/9www.geeksforgeeks.org/archives/11263
Popular Tags
GATEJavaDynamic ProgrammingBacktrackingPattern SearchingDivide & ConquerGraphOperating SystemsRecursion
Popular Posts
All permutations of a given stringMemory Layout of C ProgramsUnderstanding “extern” keyword in CMedian of two sorted arraysTree traversal without recursion and without stack!Structure Member Alignment, Padding and Data PackingIntersection point of two Linked ListsLowest Common Ancestor in a BST.Check if a binary tree is BST or notSorted Linked List to Balanced BST
5/12/12 Program to count number of set bits in an (big) array | GeeksforGeeks
7/9www.geeksforgeeks.org/archives/11263
250 Subscribe
Forum Latest Discussion
LIS in nlogn timeLast Post By: kartik
Inside: Interview Questions
tree to fileLast Post By: Dheeraj
Inside: Interview Questions
5/12/12 Program to count number of set bits in an (big) array | GeeksforGeeks
8/9www.geeksforgeeks.org/archives/11263
Count internal nodes in a binary treeLast Post By: kartik
Inside: Interview Questions
Ancestor of two given leaf nodesLast Post By: dead
Inside: Trees specific questions
combine elements of an array, so as to minimize weights.Last Post By: rohanag
Inside: Interview Questions
FB interview questionLast Post By: ranganath111
Inside: Interview Questions
Testing of factorial of a numberLast Post By: rukawa
Inside: Interview Questions
numeric puzzleLast Post By: asm
Inside: Algorithms
Forum Categories
Interview QuestionsC/C++ Programming QuestionsAlgorithmsTrees specific questionsLinked List specific questionsMultiple Choice QuestionsObject oriented queriesGPuzzles
5/12/12 Program to count number of set bits in an (big) array | GeeksforGeeks
9/9www.geeksforgeeks.org/archives/11263
Operating SystemsMiscellaneousJava specific QuestionsPerl specific Questions
Recent Comments
Venki on Structure Member Alignment, Padding and Data Packingavi on Structure Member Alignment, Padding and Data Packingatul on A Program to check if strings are rotations of each other or notVenki on Structure Member Alignment, Padding and Data Packingrahul on Dynamic Programming | Set 13 (Cutting a Rod)Sandeep on Dynamic Programming | Set 3 (Longest Increasing Subsequence)Yueming on Dynamic Programming | Set 3 (Longest Increasing Subsequence)avi on Structure Member Alignment, Padding and Data Packing
@geeksforgeeks, Some rights reservedPowered by WordPress & MooTools, customized by geeksforgeeks team