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}
sub produce_table{ my( $C,$T ) = (0,{}); return map { qq(<table cellpadding="2" cellspacing="0" align="@{[ exists $_[2]{align} ? $_[2]{align} : 'center' ]}" width="@{[ exists $_[2]{width} ? $_[2]{width} : '100%' ]}">@{[ map( { $T->{$_->{key}||$C}=0 if exists $_->{total}; $C++; () }@{$_[0]} ), ($_[2]{'header'}||'' eq 'no' ? () : qq(<tr valign="middle">@{[ map{ $T->{$_->{key}||$C}=0 if exists $_->{total}; $C++; qq(<th>$_->{title}</th>) }@{$_[0]} ]}</tr>)) ]}@{[ map{ my $a=$_; $C=0; qq(<tr valign="@{[ exists $_[2]{valign} ? $_[2]{valign} : 'top' ]}" @{[ exists $_[2]{rows} ? qq( class="@{[ [ push( @{$_[2]{rows}},shift @{$_[2]{rows}}) , $_[2]{rows}[-1] ]->[1] ]}") : '' ]}>@{[ map{ my $b = ref($a) eq 'ARRAY' ? $a->[$C] : ref($a) eq 'HASH' ? $a->{$_->{key}} : $a->${\$_->{key}}; exists $_->{total} and $T->{$_->{key}||$C}+=$b; $C++; qq(<td@{[ $_->{align} ? qq( align="$_->{align}") : '' ]}@{[ $_->{width} ? qq( width="$_->{width}") : '' ]}>@{[ $b eq'' ? ' ' : $_->{format} ? $_->{format}->($b,$a) : $b ]}</td>) }@{$_[0]} ]}</tr>) }@{$_[1]} ]}@{[ ($C=-1)&&%$T ? qq(<tr valign="@{[ exists $_[2]{valign} ? $_[2]{valign} : 'top' ]}">@{[ map { $C++; qq(<td @{[ $_->{align} ? qq( align="$_->{align}") : '' ]}>@{[ !exists $_->{total} ? ' ' : ref $_->{total} eq 'CODE' ? $_->{total}->($T->{$_->{key}||$C},$T) : $_->{total} || $T->{$_->{key}||$C} ]}</td>) } @{$_[0]} ]}</tr>) : '' ]}</table>) } 1; }An example invocation would be:
print produce_table( [ { 'key'=>'c', 'title'=>'Amount', 'align' => 'center', 'format' => sub { sprintf '<b>£%0.2f</b>', $_[0]}, 'total' => '<b>Total</b>', 'width'=>'50%' }, { 'key'=>'a', 'title'=>'x', 'align' => 'right' , TOTAL_BOLD , 'width'=>'20%' }, { 'key'=>'b', 'title'=>'x^2', 'align' => 'right' , TOTAL_BOLDITALIC , FORMAT_ITALIC, 'width'=>'10%' }, { 'key'=>'d', 'title'=>'x^3', 'align' => 'right' , TOTAL_BOLD, 'width' => '10%' }, { 'key'=>'z', 'title'=>'x^4', 'align' => 'right' , TOTAL_BOLD, 'width' => '10%' }, ], [ map {{'z'=>$_*$_*$_*$_,'a'=>$_,'b'=>$_*$_,'c'=>"$_",'d'=>$_*$_*$_}} 0..$MAX_VALUE ], );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).
with open('/path/to/file') as f: print(repr(f.read().splitlines()))