A Dozen Lines Of Code

January 24, 2012

Today’s task will require your imagination and creativity.

A high-school programming teacher recently asked for examples of short programs with a high “cool” factor, the idea being to get his students interested in programming computers. I’m not sure the suggestions would work; today’s high-school students have been surrounded by computers their entire lives, and it takes a lot to make them think a program is cool. Being from a different generation, I can remember when I thought it was cool that a program properly skipped over the perforation on a stack of green-bar paper — many programs didn’t!

Your task is to write a cool program in a dozen lines of code. You can define cool in any way that you wish. Try not to abuse the definition of “line of code,” at least not too badly; to be concrete, we will say that your solution must not exceed 12 lines, and each line must not exceed 80 characters including white space. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Like this:

LikeLoading...

Related

16 Responses to “A Dozen Lines Of Code”

In ruby, less than a dozen lines you can write a program to display the frequency all the words in a file (“word” defined loosely here as C/C++ style identifier, except it also accepts leading digits as “words” so it should do a reasonable job for text (i.e. not programming language) documents)

#!/usr/bin/env python
"""
pinc.py: an arbitraty text include filter.
Pinc.py reads a source file with include directives in the following format:
...
(> file_to_include.ext <)
(!> file_to_execute.sh --args foo <)
...
Included files will be included verbatim. If executing a file, the stdout will be included.
If a directive is indented, as follows:
...
normal text
(> file_to_include.ext <)
more normal text
...
Then the indentation will be preserved for all included lines.
Includes cannot be escaped, but any non-whitespace character before a directive will make pinc.py ignore the directive. For example:
...
some text
(> will_be_included.txt <)
some more text
this (> will_NOT_be_included.txt <)
even more text
...
pinc.py reads from the stdin and writes to stdout. It takes no arguments.
pinc.py is one pass non-recursive. The included text is not parsed for pinc.py directive.
"""
import sys, re, od.path, shlex, subprocess
for line in sys.stdin:
match_exe = re.match(r'(\s*)\(!>(.*)<\)\s*', line)
match_inc = re.match(r'(\s*)\(>(.*)<\)\s*', line)
if match_exe:
space, args = match_exe.groups()
sys.stdout.writelines(map(lambda x: space+x+"\n", subprocess.check_output(shlex.split(args)).split("\n")))
elif match_inc:
space, inc = match_inc.groups()
sys.stdout.writelines(map(lambda x: space+x, open(inc.strip())))
else:
sys.stdout.write(line)