population

command
v0.0.0-...-544ef16 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 14, 2022 License: MIT Imports: 3 Imported by: 0

README

Population Count

Task

Count the number of 1s in a bit array of size n.

Solution

Inspect Every Bit

Simply count the bits which are set, in θ(n)

Skip the Zeros

c := 0 while w != 0 do { c++; w := intersect (w, w - 1) }

For every set 1 one iteration. O(n)

Logarithmic Bit Sum
  • Use bitmasks 01010101, 00110011, 00001111 etc.
  • For all masks i:
  • Mask the input word w with mask i (weven)
  • Right-shift w by 2i bits
  • Mask again shifted w with mask i (wodd)
  • w := (weven + wodd)

θ(log(n))

Lookup (Fastest)

Pre-calculate population count for, say, 8bit words and look them up. For words a multiple of 8bits shift them accordingly, do n lookups, sum up the counts.

Documentation

The Go Gopher

There is no documentation for this package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL