Skip to content

Commit f2681dd

Browse files
committed
Use faster bit counting algorithm
1 parent 3f7ff29 commit f2681dd

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

lib/bitarray-array.rb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,9 @@ def each_byte
4343
end
4444

4545
# Returns the total number of bits that are set
46-
# (The technique used here is about 6 times faster than using each or inject direct on the bitfield)
46+
# Use Brian Kernighan's way, see
47+
# https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
4748
def total_set
48-
@field.each_byte.inject(0) { |a, byte| a += byte & 1 and byte >>= 1 until byte == 0; a }
49+
@field.each_byte.inject(0) { |a, byte| (a += 1; byte &= byte - 1) while byte > 0 ; a }
4950
end
5051
end

lib/bitarray.rb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,10 @@ def each_byte
4747
end
4848

4949
# Returns the total number of bits that are set
50-
# (The technique used here is about 6 times faster than using each or inject direct on the bitfield)
50+
# Use Brian Kernighan's way, see
51+
# https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
5152
def total_set
52-
@field.each_byte.inject(0) { |a, byte| a += byte & 1 and byte >>= 1 until byte == 0; a }
53+
@field.each_byte.inject(0) { |a, byte| (a += 1; byte &= byte - 1) while byte > 0 ; a }
5354
end
5455

5556
def byte_position(position)

0 commit comments

Comments
 (0)