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.

Pages: 1 2

7 Responses to “A Single Line Of Code”

  1. James Smith said

    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'' ?
                    '&nbsp;' :
                    $_->{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} ?
                    '&nbsp;' :
                    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>&pound;%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

  2. Steve said

    Mumps version

    
    FOR  READ !,X:5 QUIT:'$T  S ARR($INCREMENT(ARRAY))=X
    
    This allows reading in lines of text into an array (ARR) until there are no more lines of text.  This will then enable me to process the text using the Mumps programming language.  Have used this hundreds of times.
    
    
  3. Bill said

    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.

  4. Zack said

    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.

  5. kernelbob said

    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.

  6. matthew said

    Haskell seems the natural place to look for interesting one liners.

    For example, Pascal’s triangle by iteration:

    Prelude> s = iterate (\s-> zipWith (+) ([0]++s) (s++[0])) [1]
    Prelude> take 6 s
    [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1]]
    

    Or a nice impredicative definition of the Catalan numbers:

    Prelude> s = map head $ iterate (\t -> sum (zipWith (*) s t) : t) [1]
    Prelude> take 15 s
    [1,1,2,5,14,42,132,429,1430,4862,16796,58786,208012,742900,2674440]
    

    More impredicativity, we can list all integer pairs that generate primitive Pythagorean triples, as (a^2-b^2,2ab,a^2+b^2):

    Prelude> s = (2,1) : concat [[(2*a-b,a),(2*a+b,a),(a+2*b,b)] | (a,b) <- s]
    Prelude> take 10 s
    [(2,1),(3,2),(5,2),(4,1),(4,3),(8,3),(7,2),(8,5),(12,5),(9,2)]
    

    Or in a similar way, enumerate the rationals (as in the “Calkin-Wilf Tree”):

    Prelude> s = (1,1) : concat [[(a,a+b),(a+b,b)] | (a,b) <- s]
    Prelude> take 20 s
    [(1,1),(1,2),(2,1),(1,3),(3,2),(2,3),(3,1),(1,4),(4,3),(3,5),
     (5,2),(2,5),(5,3),(3,4),(4,1),(1,5),(5,4),(4,7),(7,3),(3,8)]
    

    which can also be done with “Stern’s Diatomic Sequence”:

    Prelude> s = 1 : ileave s (zipWith (+) s (tail s)) where ileave (a:s) t = a : ileave t s
    Prelude> take 20 s
    [1,1,2,1,3,2,3,1,4,3,5,2,5,3,4,1,5,4,7,3]
    Prelude> take 20 $ zipWith (,) s (tail s)
    [(1,1),(1,2),(2,1),(1,3),(3,2),(2,3),(3,1),(1,4),(4,3),(3,5),
     (5,2),(2,5),(5,3),(3,4),(4,1),(1,5),(5,4),(4,7),(7,3),(3,8)]
    

    or by a direct iteration:

    Prelude> s = iterate g (1,1) where g(a,b) = (b,(a`div`b*2+1)*b-a)
    Prelude> take 20 s
    [(1,1),(1,2),(2,1),(1,3),(3,2),(2,3),(3,1),(1,4),(4,3),(3,5),
     (5,2),(2,5),(5,3),(3,4),(4,1),(1,5),(5,4),(4,7),(7,3),(3,8)]
    
  7. Daniel said

    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()))
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: