19
4
Create a program that computes the hamming weight of a string. Winner is the program with the lowest hamming weight.
Rules:
- Hamming weight for an ASCII character is defined as the total number of bits set to
1
in its binary representation. - Assume input encoding is 7-bit ASCII, passed through whatever input mechanism is normal for your language (e.g. stdin, args, etc.)
- Output the result, as a number, to stdout or whatever default/normal output mechanism your language uses.
- It should go without saying, but you have to be able to actually run the program, in real life, for it to be a valid solution.
- Winner is the solution whose code has the lowest hamming weight.
Sorry, no solutions in whitespace for this one!Ok, you can code in whitespace now I've sorted out the rules :)
Per-character examples:
char | binary | weight
-----+----------+-------
a | 01100001 | 3
x | 01111000 | 4
? | 00111111 | 6
\x00 | 00000000 | 0
\x7F | 01111111 | 7
if we take
0x20
/ASCII 32 as the reference, isn't the humming weight ofhello world
10 rather than 11? – Cristian Lupascu – 2012-06-07T13:11:32.747Why is the weight of
hello world
11? Only 10 characters are different from a space. Also - a program's Hamming weight seems to be just its length, excluding spaces. Not so different from normal code golf. – ugoren – 2012-06-07T13:12:58.943Sorry, I totally screwed this up. Wikipedia's hamming weight article is rather misleading, and I totally fubar'ed the rules. Re-writing now. Update: Ok, re-written to define it as the number of bits set to 1 in the ASCII string, sorry for the screw-up. – Polynomial – 2012-06-07T13:16:31.960
@ugoren A solution with lower-value ASCII characters has a lower hamming weight. – Polynomial – 2012-06-07T13:18:23.190
1Now it all makes sense. USE UPPERCASE, BEWARE OF
~
ANDo
. – ugoren – 2012-06-07T13:22:33.533@ugoren Yup, pretty much.
TEST
has a weight of 13, whereastest
has a weight of 17. – Polynomial – 2012-06-07T13:25:27.253So Hamming weight of a string is the sum of the Hamming weights of the characters, or is it the number of unique bits set? – user unknown – 2012-06-07T13:51:17.353
@userunknown Sum of the Hamming weights of the characters. – Polynomial – 2012-06-07T13:59:03.420
@Polynomial Now that you've corrected the measurement of the Hamming weight, will you be lifting the ban on Whitespace? – breadbox – 2012-06-07T19:08:29.843
@breadbox Good idea, though I can't imagine solutions would be particularly competitive ;) – Polynomial – 2012-06-07T19:11:57.543
Tip: Name your variables
A
,B
,D
,H
, orP
. – dan04 – 2012-06-08T03:39:32.237