[exercise] obfuscated word counting

2 views
Skip to first unread message

Matthew Fernandez

unread,
Nov 18, 2011, 3:38:32 AM11/18/11
to code-p...@googlegroups.com
This week we finally saw the return of the International Obfuscated C
Code Contest (http://www.ioccc.org/) after an epic hiatus. In honour
of this, I thought I'd propose an obfuscated exercise for this month.
The goal is to write a program that counts the number of words in a
string. As usual, receive the input and return the output in any way
you see fit. Ideally, your code should work, but it should be
extremely hard to understand (look at some of the past IOCCC winners
for examples).

I tend to approach these things by starting out with a reference
implementation and then step-by-step obscuring it. Here's a reference
implementation in C to get you going. If you prefer to hack in another
language and are too lazy, let me know and I'll write you one in your
language of choice.

#include <stdio.h>

int main(int argc, char **argv) {
int c,
last_char_whitespace = 1,
words = 0;

while ((c = getchar()) != EOF) {
switch (c) {
case ' ':
case '\n':
case '\t':
if (!last_char_whitespace)
++words;
last_char_whitespace = 1;
break;

default:
last_char_whitespace = 0;
}
}

printf("%d\n", words + !last_char_whitespace);
return 0;
}

Reply all
Reply to author
Forward
0 new messages