{"id":25888,"date":"2017-10-25T21:12:06","date_gmt":"2017-10-25T15:42:06","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25888"},"modified":"2017-10-25T21:12:06","modified_gmt":"2017-10-25T15:42:06","slug":"program-count-number-set-bits-big-array","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/program-count-number-set-bits-big-array\/","title":{"rendered":"Program to count number of set bits in an (big) array"},"content":{"rendered":"<p>Given an integer array of length N (an\u00a0arbitrarily\u00a0large number). How to count number of set bits in the array?<span id=\"more-11263\"><\/span><\/p>\n<p>The simple approach would be, create an efficient method to count set bits in a word (most prominent size, usually equal to bit length of processor), and add bits from individual elements of array.<\/p>\n<p>Various methods of counting set bits of an integer exists, see <a href=\"http:\/\/www.geeksforgeeks.org\/archives\/1176\" target=\"_blank\" rel=\"noopener noreferrer\">this<\/a> for example. These methods run at best O(logN) where N is number of bits. Note that on a processor N is fixed, count\u00a0can be done in O(1) time on 32 bit machine irrespective of total set bits. Overall, the bits in array can be computed in O(n) time, where \u2018n\u2019 is array size.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>However, a table look up will be more efficient method when array size is large. Storing table look up that can handle 2<sup>32<\/sup> integers will be impractical.<\/p>\n<p>The following code illustrates simple program to count set bits in a randomly generated 64 K integer array. The idea is to generate a look up for first 256 numbers (one byte), and break every element of array at byte boundary. A meta program using C\/C++ preprocessor generates the look up table for counting set bits in a byte.<\/p>\n<p>The\u00a0mathematical\u00a0derivation behind meta program is evident from the following table (Add the column and row indices to get the number, then look into the table to get set bits in that number. For example, to get set bits in 10, it can be extracted from row named as 8 and column named as 2),<\/p>\n<pre> \u00a00, 1, 2, 3\r\n 0 - 0, 1, 1, 2 -------- GROUP_A(0)\r\n 4 - 1, 2, 2, 3 -------- GROUP_A(1)\r\n 8 - 1, 2, 2, 3 -------- GROUP_A(1)\r\n12 - 2, 3, 3, 4 -------- GROUP_A(2)\r\n16 - 1, 2, 2, 3 -------- GROUP_A(1)\r\n20 - 2, 3, 3, 4 -------- GROUP_A(2)\r\n24 - 2, 3, 3, 4 -------- GROUP_A(2)\r\n28 - 3, 4, 4, 5 -------- GROUP_A(3) ... so on<\/pre>\n<p>From the table, there is a patten emerging in multiples of 4, both in the table as well as in the group parameter. The sequence can be generalized as shown in the code.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Complexity:<\/strong><\/p>\n<p>All the operations takes O(1) except iterating over the array. The time complexity is O(n) where \u2018n\u2019 is size of array. Space complexity depends on the meta program that generates look up.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">c<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">#include &lt;stdio.h&gt;<br\/>#include &lt;stdlib.h&gt;<br\/>#include &lt;time.h&gt;<br\/> <br\/>\/* Size of array 64 K *\/<br\/>#define SIZE (1 &lt;&lt; 16)<br\/> <br\/>\/* Meta program that generates set bit count<br\/>   array of first 256 integers *\/<br\/> <br\/>\/* GROUP_A - When combined with META_LOOK_UP<br\/>   generates count for 4x4 elements *\/<br\/> <br\/>#define GROUP_A(x) x, x + 1, x + 1, x + 2<br\/> <br\/>\/* GROUP_B - When combined with META_LOOK_UP<br\/>   generates count for 4x4x4 elements *\/<br\/> <br\/>#define GROUP_B(x) GROUP_A(x), GROUP_A(x+1), GROUP_A(x+1), GROUP_A(x+2)<br\/> <br\/>\/* GROUP_C - When combined with META_LOOK_UP<br\/>   generates count for 4x4x4x4 elements *\/<br\/> <br\/>#define GROUP_C(x) GROUP_B(x), GROUP_B(x+1), GROUP_B(x+1), GROUP_B(x+2)<br\/> <br\/>\/* Provide appropriate letter to generate the table *\/<br\/> <br\/>#define META_LOOK_UP(PARAMETER) \\<br\/>   GROUP_##PARAMETER(0),  \\<br\/>   GROUP_##PARAMETER(1),  \\<br\/>   GROUP_##PARAMETER(1),  \\<br\/>   GROUP_##PARAMETER(2)   \\<br\/> <br\/>int countSetBits(int array[], size_t array_size)<br\/>{<br\/>   int count = 0;<br\/> <br\/>   \/* META_LOOK_UP(C) - generates a table of 256 integers whose<br\/>      sequence will be number of bits in i-th position<br\/>      where 0 &lt;= i &lt; 256<br\/>   *\/<br\/> <br\/>    \/* A static table will be much faster to access *\/<br\/>       static unsigned char const look_up[] = { META_LOOK_UP(C) };<br\/> <br\/>    \/* No shifting funda (for better readability) *\/<br\/>    unsigned char *pData = NULL;<br\/> <br\/>   for(size_t index = 0; index &lt; array_size; index++)<br\/>   {<br\/>      \/* It is fine, bypass the type system *\/<br\/>      pData = (unsigned char *)&amp;array[index];<br\/> <br\/>      \/* Count set bits in individual bytes *\/<br\/>      count += look_up[pData[0]];<br\/>      count += look_up[pData[1]];<br\/>      count += look_up[pData[2]];<br\/>      count += look_up[pData[3]];<br\/>   }<br\/> <br\/>   return count;<br\/>}<br\/> <br\/>\/* Driver program, generates table of random 64 K numbers *\/<br\/>int main()<br\/>{<br\/>   int index;<br\/>   int random[SIZE];<br\/> <br\/>   \/* Seed to the random-number generator *\/<br\/>   srand((unsigned)time(0));<br\/> <br\/>   \/* Generate random numbers. *\/<br\/>   for( index = 0; index &lt; SIZE; index++ )<br\/>   {<br\/>      random[index] = rand();<br\/>   }<br\/> <br\/>   printf(&quot;Total number of bits = %d\\n&quot;, countSetBits(random, SIZE));<br\/>   return 0;<br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Program to count number of set bits in an (big) array- Bit Algorithm &#8211; The simple approach would be, create an efficient method to count set bits in a word.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,79658,74852],"tags":[75083,75079,75879,75268,75111,75109,75884,75078,75091,75878,75084,75093,75270,75098,75886,74432,75281,73333,75089,75070,75897,75882,75883,75893,75104,75894,75896,75891,75881,75100,75086],"class_list":["post-25888","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-array","category-bit-algorithms","tag-bitwise-operations-in-c","tag-bitwise-operator-in-c","tag-bs-it","tag-bytes-table","tag-c-byte","tag-c-xor","tag-chacker","tag-clearbit","tag-counter-bit-set","tag-counter-set","tag-counting-bits","tag-cs-counter","tag-first-in-math-hack","tag-for-bit","tag-html-graphics","tag-integer-numbers","tag-magic-bit","tag-n-number-lookup","tag-nextbit","tag-number-counter","tag-number-sets","tag-population-counter","tag-powers-of-2","tag-python-bit","tag-set-bit","tag-set-count","tag-set-number","tag-two-bit-counter","tag-vbit","tag-word-bit","tag-xor-operator-in-c"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25888","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25888"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25888\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25888"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25888"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25888"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}