Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Problem 810. Hamming Weight - Size Scoring

Created by Richard Zapor

The Hamming Weight, wiki Hamming Weight, in its most simple form is the number of ones in the binary representation of a value.

The task here is to create a fast Hamming Weight function/method such that processing many 4K x 4K images of 32 bit integer can be evaluated rapidly. Saw this question posed on Stack Overflow.

Input: Vector of length N of 32 bit integer values.

Output: Total number of ones of the binary representation

Scoring: Normal Cody Size, while solving multiple cases without timing out

Examples: Input [7 ; 3], output=[3 ; 2]; [16 32], output [1 ; 1]; [0 4294967295] output [ 0 ; 32] FFFFFFFF Hex = 2^32-1

Stressing Test vector : uint32(randi(2^32,[4096*4096,1])-1)

Helpful, possibly, global variables.

b1=uint32(1431655765); b2=uint32(858993459); b3=uint32(252645135) b4=uint32(16711935); b5=uint32(65535);

Hex: b1=55555555 b2=33333333 b3=0F0F0F0F b4=00FF00FF b5=0000FFFF

The array num_ones is created for values 0-65535 (0:2^16-1). num_ones(1)=0, num_ones(2)=1, num_ones(3)=1,num_ones(4)=2,...num_ones(65536)=15

Due to lack of zero indexing num_ones(value+1) is number of ones for value.

Tags

Problem Group

Solution Statistics

6 correct solutions 25 incorrect solutions
Last solution submitted on Sep 07, 2014

Solution Comments