A Single Line Of Code
December 3, 2019
Today’s task challenges you write a useful program using only a single line of code. It is not fair to abuse the notion of a line. You can probably do more than you expect.
Your task is to write a useful program using only a single line of code. When you are finished, you are welcome to read a suggested solution, or to post your own solution or discuss the exercise in the comments below.
I use a lot of perl 1-liners in work (sometimes they do get very long…) – you said I couldn’t abuse 1 line… but thought I would include one – very long one-liner in Perl – which is an array to table HTML renderer I wrote probably 15+ years ago.. {I still use the same basic code regularly at work}
An example invocation would be:
Have similar code in PHP using lambdas to drive an advanced templating system
Mumps version
Using Pari/GP,
genit(mx)={forprime(p=2,mx,q=p+1;ok=0;while(q>2,q=precprime(q-1);if(isprime(round(pqPi)),ok=1;break));if(!ok,print1(p,”,”)));}
The output will be 7,113, 265381,…
These will be denominators for increasingly accurate approximations to Pi.
So they correspond to 22/7, 355/113, 833719/265381, …
The code using continued fractions is about the same length.
FindClosestDataPoint(x0::Float64, x::Array{<:Real, 1}) = argmin(abs.(x .- x0))
A simple function to find the index of the point of array x that’s closest to x. Not much on its own, but a useful auxiliary function overall.
These are more than one line, but there’s only one line of executable code.
~$ cat bin/sumcol
#!/bin/sh
exec awk "{ sum += \$${1-1}} END { print sum }"
~$ cat bin/lensort
#!/usr/bin/env python3
import fileinput
import sys
sys.stdout.write(''.join(sorted(fileinput.input(), key=len)))
~$
sumcol sums the numbers in a column of a text file — defaults to column 1 to work with
uniq -c
,wc
, etc.lensort sorts its input by line length.
Haskell seems the natural place to look for interesting one liners.
For example, Pascal’s triangle by iteration:
Or a nice impredicative definition of the Catalan numbers:
More impredicativity, we can list all integer pairs that generate primitive Pythagorean triples, as (a^2-b^2,2ab,a^2+b^2):
Or in a similar way, enumerate the rationals (as in the “Calkin-Wilf Tree”):
which can also be done with “Stern’s Diatomic Sequence”:
or by a direct iteration:
Here’s a one-liner in Python that prints the lines in a file as a list of strings (e.g., for copying and pasting elsewhere).