# Question
Title: Code Golf: Create a string of 100 of the same character
The problem is to create a string of the same character repeated 100 times.

One potential solution in JavaScript is:

```
var i = 100,
    s = '';

while(i--) s += "Z";

```

Shortest code wins.

# Answer
> 9 votes
## golflua: ~~109~~ 15

```
w(S.t("a",100))

```

Which is more-or-less equivalent to Heiko's Lua answer

# Answer
> 6 votes
# Python2.7 - 7 bytes

```
'a'*100

```

String manipulation using `*` pretty simple.

# Answer
> 6 votes
# Lua, 24 bytes

This variant is based on Geobits' comment:

```
print(("").rep("a",100))

```

---

## Older version, 38 bytes

```
a=""for i=0,99 do a=a.."a"end print(a)

```

**Ungolfed:**

```
a = ""              -- start with empty string
for i = 0, 99, 1 do -- 100 times
  a = a .. "a"      -- append "a" to variable a
end
print(a)            -- print result

```

# Answer
> 4 votes
# GolfScript, 4 characters:

```
100*

```

The input should be on the stack. This program assumes a single-character input.

Test online.

If the character needs to be hardcoded, it's **7 characters**:

```
'a'100*

```

If the character is a newline and it needs to be hardcoded, **5 characters** (thanks to Jan Dvorak):

```
100n*

```

# Answer
> 4 votes
# JavaScript - 20 chars

At least, shorter than Bash ;)

```
Array(101).join("a")

```

An array of length `100` joined with letter `a`.

# Perl - 12 chars

First Perl golf !

```
print"a"x100

```

Thanks to ace for shortening one character.

# Answer
> 4 votes
# QBasic : 22

```
PRINT STRING$(100,"A")

```

Why not?

# Answer
> 3 votes
# Bash+tr, 20 bytes

```
$ printf %100s|tr \  Z
ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ$

```

---

# Pure Bash, 31 bytes

```
$ printf -vs %100s;echo ${s// /Z}
ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
$

```

Pretty standard stuff.

---

# GNU dc, 14 bytes

```
2 800^255/90*P

```

Output:

```
$ dc -e '2 800^255/90*P'
ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ$

```

# Answer
> 3 votes
# J (7)

Very similar to the Python one

```
100$'a'

```

`100$'ab'` would output 50 times `ab`, for 100 characters total.

# Answer
> 2 votes
## Perl, 7 bytes

```
"a"x100

```

Almost completely the same as the Python one.

# Answer
> 2 votes
# Brainfuck, 27 characters (or ~~26~~ 25)

```
,>++++++++++[<..........>-]

```

This program requires input, because hardcoding a character is not possible in Brainfuck.

If it is allowed to always output 100 times the NUL character, there is a 25 char solution (thanks to Quincunx):

```
++++++++++[>..........<-]

```

# Answer
> 2 votes
# Haskell

```
replicate 100 'a'

```

GHCi output:

```
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"

```

Code for GHC:

```
main = print $ replicate 100 'a'

```

---
Tags: code-golf, string
---


title: Output a solid PNG from scratch

text:
# Question
Title: Output a solid PNG from scratch
**Input**: An RGBA hex color `c` (ex. `FFFF00FF`) and an integer \> 0 and \< 1000 `n` (ex. `200`).

**Output**: Raw bytes of a PNG file such that when the output is saved to a file and opened in an image viewer, an `n` by `n` image filled with the color `c` is displayed.

**Specification**: Your program should output **exactly**:

* a PNG header (`89504E470D0A1A0A` in hex)
* an `IHDR` chunk containing these specifications:
    + width: the previous input `n`
    + height: the previous input `n`
    + bit depth: `8` (`RGBA`)
    + color type: `6` (truecolor with alpha)
    + compression method: `0`
    + filter method: `0`
    + interlace method: `0`
* one or more `IDAT` chunks containing the image data (a solid image of color previously input `c`); may be compressed or uncompressed
* an `IEND` image end chunk

Further details available on Wikipedia, on the W3 site, or via a Google search.

**Restrictions**:

* You may not use any image libraries or functions designed to work with images of any kind.
* Your program must run in under 3 minutes and output a file under 10 MB for all inputs (sanity check).
* This is , so the shortest code in bytes will win!

# Answer
# Perl, 181

```
/ /;use String::CRC32;use Compress::Zlib;sub k{$_=pop;pack'Na*N',y///c-4,$_,crc32$_}$_="\x89PNG\r\n\cZ\n".k(IHDR.pack NNCV,$',$',8,6).k(IDAT.compress pack('CH*',0,$`x$')x$').k IEND

```

Size is 180 bytes and option `-p` is needed (+1). Score is then 181.

The arguments are given via STDIN in a line, separated by a space, the color as hex value (16 chars) and the number of pixels for width/height, e.g.:

```
 echo "FFFF00FF 200" | perl -p solidpng.pl >yellow200.png

```

The file size is 832 bytes. The maximal sized image (n=999) with the same color has 6834 bytes (way below 10 MB).

The solution uses two libraries:

* `use Digest::CRC crc32;` for the CRC32 values at the chunk ends.
* `use IO::Compress::Deflate deflate;` to compress the image data.

Both libraries are not related to images.

**Ungolfed:**

```
# Perl option "-p" adds the following around the program:
#     LINE:
#     while (<>) {
#         ... # the program goes here
#     } continue {
#         print or die "-p destination: $!\n";

/ /;    # match the separator of the arguments in the input line
        # first argument, color in hex:  $`
        # second argument, width/height: $'                              #'

# load the libraries for the CRC32 fields and the data compression
use String::CRC32;
use Compress::Zlib;

# function that generates a PNG chunk:
#   N (4 bytes, big-endian: data length
#   N:                      chunk type
#   a* (binary data):       data
#   N:                      CRC32 of chunk type and data
sub k {
    $_ = pop; # chunk data including chunk type and
              # excluding length and CRC32 fields
    pack 'Na*N',
        y///c - 4,   # chunk length                                      #/
                     # netto length without length, type, and CRC32 fields
        $_,          # chunk type and data
        crc32($_)    # checksum field
}

$_ =                      # $_ is printed by option "-p".
    "\x89PNG\r\n\cZ\n"    # PNG header
        # IHDR chunk: image header with
        #   width, height,
        #   bit depth (8), color type (6),
        #   compresson method (0), filter method (0), interlace method (0)
    . k('IHDR' . pack NNCV, $', $', 8, 6)
        # IDAT chunk: image data
    . k('IDAT' .
          compress        # compress/deflate data
          pack('CH*',     # scan line with filter byte
              0,          # filter byte: None
              ($` x $')   # pixel data for one scan line                 #'`
          ) x $'          # n lines                                      #'
      )
        # IHDR chunk: image end
    . k('IEND');

```

**Edits**

* `use IO::Compress::Deflate':all';` is replaced by `use Compress::Zlib;`. The latter does export the deflate function `compress` by default. The function does not need references as arguments and also returns the result directly. That allows to get rid of variable `$o`.

Thanks for Michael's answer:

* Function `k`: A call of `pack` could be removed by using template `Na*N` for the first `pack` in the function.
* `pack` template `NNCV` with four values optimizes `NNC3n` with six values.

Thanks for VadimR's comment with lots of tips:

* `use String::CRC32;` is shorter than `use Digest::CRC crc32;`.
* `y///c-4` is shorter than `-4+y///c`.
* The scan line is now constructed by the template `CH*` with the repetition in the value.
* Removal of `$i` by using a value reference.
* Bare words instead of strings for the chunk types.
* Options now read by matching a STDIN input line (option `-p`) with matching the space separator `/ /`. Then the first option is in `$`` and the second argument goes in `$'`.
* Option `-p` also automatically prints `$_`.
* `"\cZ"` is shorter than `"\x1a"`.

## Better compression

At the cost of code size the image data can be further compressed, if filtering is applied.

* Unfiltered file size for `FFFF0FF` `200`: 832 bytes
* Filter `Sub` (horizontal pixel differences): 560 bytes

```
$i = (                            # scan line:
         "\1"                     # filter "Sub"
         . pack('H*',$c)          # first pixel in scan line
         . ("\0" x (4 * $n - 4))  # fill rest of line with zeros
      ) x $n;                     # $n scan lines

```
* Filter `Sub` for the first line and `Up` for the remaining lines: 590 bytes

```
$i = # first scan line
     "\1"                     # filter "Sub"
     . pack('H*',$c)          # first pixel in scan line
     . ("\0" x (4 * $n - 4))  # fill rest of line with zeros
     # remaining scan lines
     . (
           "\2"               # filter "Up"
           . "\0" x (4 * $n)  # fill rest of line with zeros
       ) x ($n - 1);

```
* First unfiltered line, then filter `Up`: 586 bytes

```
$i = # first scan line
     pack('H*', ("00" . ($c x $n)))  # scan line with filter byte: none
     # remaining scan lines
     . (
           "\2"               # filter "Up"
           . "\0" x (4 * $n)  # fill rest of line with zeros
       ) x ($n - 1);

```
* Also `Compress::Zlib` can be tuned; the highest compression level can be set by additional option for the compression level in function `compress` at the cost of two bytes:

```
compress ..., 9;

```

File size of example `yellow200.png` without filtering decreases from 832 bytes to 472 bytes. Applied to the example with `Sub` filter, the file size shrinks from 560 bytes to 445 bytes (`pngcrush -brute` can't compress further).
> 6 votes

# Answer
## PHP 214

I'm not an expert on PHP, there is place for golfing. Tips are welcomed.

```
<?function c($d){echo pack("Na*N",strlen($d)-4,$d,crc32($d));}echo"\x89PNG\r\n\x1a\n";c("IHDR".pack("NNCV",$n=$argv[1],$n,8,6));c("IDATx^".gzdeflate(str_repeat("\0".str_repeat(hex2bin($argv[2]),$n),$n)));c("IEND");

```

Generate a PNG file:

```
php png.php 20 FFFF00FF > output.png

```

Generate base64 stream (paste the result in your browser address bar)

```
echo "data:image/png;base64,`php png.php 200 0000FFFF | base64`"

```

Ungolfed version :

```
<?php

//function used to create a PNG chunck
function chunck($data) {
  return pack("Na*N", //write a big-endian integer, a string and another integer
    strlen($data)-4,     //size of data minus the 4 char of the type
    $data,               //data
    crc32($data));       //compute CRC of data
}

//png header
echo "\x89PNG\r\n\x1a\n";

//IHDR chunck
echo chunck("IHDR".pack("NNCV", //2 big-endian integer, a single byte and a little-endian integer
                   $n=$argv[1], $n,
                   8, 6)); //6 also write 3 zeros (little endian integer)

//IDAT chunck
//create a binary string of the raw image, each line begin with 0 (none filter)
$d = str_repeat("\0".str_repeat(hex2bin($argv[2]),$n),$n);
echo chunck("IDATx^".
       gzdeflate($d)); //compress raw data

//IEND chunck
echo chunck("IEND");

```
> 5 votes

# Answer
# Python, 252 bytes

```
import struct,sys,zlib as Z
P=struct.pack
A=sys.argv
I=lambda i:P(">I",i)
K=lambda d:I(len(d)-4)+d+I(Z.crc32(d)&(2<<31)-1)
j=int(A[2])
print "\x89PNG\r\n\x1A\n"+K("IHDR"+P(">IIBI",j,j,8,6<<24))+K("IDAT"+Z.compress(("\0"+I(int(A[1],16))*j)*j))+K("IEND")

```

This script takes input from argv. Run this script from command line, like `python 27086.py deadbeef 999`
> 4 votes

---
Tags: code-golf, graphical-output
---


title: Filter a large file in small memory

text:
# Question
Title: Filter a large file in small memory
The challenge is a follow-up to Filter a large file quickly which had two submissions where were as fast as wc! This time the difficulty is that RAM is severely restricted which means that new methods will have to be used.

* Input: Each line has three space separated positive integers.
* Output: All input lines `A` `B`, `T`that satisfy either of the following criterion.

1. There exists another input line `C`, `D`, `U` where `D = A` and `0 <= T - U < 100`.
    2. There exists another input line `C`, `D`, `U` where `B = C` and `0 <= U - T < 100`.

To make a test file use the following python script which will also be used for testing. It will make a 1.3G file. You can of course reduce nolines for testing.

```
import random
nolines = 50000000 # 50 million
for i in xrange(nolines):
    print random.randint(0,nolines-1), random.randint(0,nolines-1), random.randint(0,nolines-1)

```

**Rules.** Your code must use no more than 200MB of RAM. I will enforce this using `ulimit -v 200000`. Your code must therefore also run on ubuntu using only easily installable and free software.

**Score.** You can report your unofficial score by testing on your machine as (the time in seconds needed by Keith Randall's submission from Filter a large file quickly divided by the time in seconds taken by your submission )\*100 .

**Winning criterion.** The winner will be the one with the highest score when I test the code on my computer using a file created by the sample python code. I will first run

```
sync && sudo bash -c 'echo  3 > /proc/sys/vm/drop_caches'

```

before each test run.

The deadline is one week from the time of the first correct entry.

**My Machine** The timings will be run on my machine. This is a standard 8GB RAM ubuntu install on an AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code.

**Some relevant timing information**

largefile.file is a file created using the sample python code.

```
sync && sudo bash -c 'echo  3 > /proc/sys/vm/drop_caches'

time wc largefile.file

real    0m26.835s
user    0m18.363s
sys     0m0.495s

time sort -n largefile.file  > /dev/null

real    1m32.344s
user    2m9.530s
sys     0m6.543s

```

# Answer
> 2 votes
## C, score 55.55

Same as my other implementation, but it does the radix sort using disk files. Uses ~25MB of memory, mostly for buffers.

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

#define R 3
#define B 9
#define M ((1<<B)-1)
#define BUFSIZE 4096
#define PARSEBUF 65536

typedef struct {
  int a,b,t;
} entry;

typedef struct {
  int fd;
  int lo;
  int hi; // bytes buf[lo]..buf[hi-1] are valid.
  entry e; // scratch
  char buf[PARSEBUF];
} ParseState;

entry *parse(ParseState *s) {
  int n = s->hi - s->lo;

  // if we need to, grab some more data
  if(n < 100 && s->fd != -1) {
    memmove(&s->buf[0], &s->buf[s->lo], n);
    int k = read(s->fd, &s->buf[n], PARSEBUF - n);
    if(k == 0) s->fd = -1;
    n += k;
    s->lo = 0;
    s->hi = n;
  }
  if(n == 0) return NULL;

  // parse line
  char *p = &s->buf[s->lo];
  int a = 0;
  while(*p != ' ') {
    a *= 10;
    a += *p - '0';
    p++;
  }
  p++;
  int b = 0;
  while(*p != ' ') {
    b *= 10;
    b += *p - '0';
    p++;
  }
  p++;
  int t = 0;
  while(*p != '\n') {
    t *= 10;
    t += *p - '0';
    p++;
  }
  p++;
  s->lo += p - &s->buf[s->lo];
  s->e.a = a;
  s->e.b = b;
  s->e.t = t;
  return &s->e;
}

typedef struct {
  int fd;
  int lo;
  int hi;
  entry buf[BUFSIZE];
} ReadBuf;

entry *bread(ReadBuf *b) {
  if(b->lo == b->hi) {
    int k = read(b->fd, &b->buf[0], BUFSIZE*sizeof(entry));
    if(k == 0) return NULL;
    b->lo = 0;
    b->hi = k / sizeof(entry);
  }
  return &b->buf[b->lo++];
}

typedef struct {
  int fd;
  int offset;   // offset in file to write buffer
  int n;        // # of entries
  entry buf[BUFSIZE];
} WriteBuf;

void bflush(WriteBuf *b) {
  int size = b->n * sizeof(entry);
  pwrite(b->fd, &b->buf[0], size, b->offset);
  b->offset += size;
  b->n = 0;
}

void bwrite(WriteBuf *b, entry *e) {
  b->buf[b->n++] = *e;
  if(b->n == BUFSIZE)
    bflush(b);
}

int count[R][1<<B];
int accum[R][1<<B];

unsigned char bcount[16384];

ParseState s;
ReadBuf rd;
WriteBuf wr[1<<B];
entry recent[65536];
char print[65536];

int main(int argc, char *argv[]) {
  int fd = open(argv[1], O_RDONLY);
  int fd1 = open("tmp1", O_RDWR | O_CREAT | O_TRUNC, 0666);
  int fd2 = open("tmp2", O_RDWR | O_CREAT | O_TRUNC, 0666);

  // parse input, write first file, do stats for radix sort
  entry *e;
  s = (ParseState){fd, 0, 0};
  wr[0] = (WriteBuf){fd1, 0, 0};
  while((e = parse(&s)) != NULL) {
    bwrite(&wr[0], e);
    // compute counts for radix sort
    int t = e->t;
    for(int r = 0; r < R; r++) {
      count[r][t&M]++;
      t >>= B;
    }
  }
  bflush(&wr[0]);

  // accumulate count entries
  for(int r = 0; r < R; r++) {
    int sum = 0;
    for(int i = 0; i < 1<<B; i++) {
      accum[r][i] = sum;
      sum += count[r][i];
    }
  }

  // radix sort
  int fda = fd1;
  int fdb = fd2;
  for(int r = 0; r < R; r++) {
    lseek(fda, 0, SEEK_SET);
    rd = (ReadBuf){fda, 0, 0};
    for(int i = 0; i < 1<<B; i++) {
      wr[i] = (WriteBuf){fdb, accum[r][i]*sizeof(entry), 0};
    }
    while((e = bread(&rd)) != NULL) {
      bwrite(&wr[(e->t>>r*B)&M], e);
    }
    for(int i = 0; i < 1<<B; i++) {
      bflush(&wr[i]);
    }
    int t = fda;
    fda = fdb;
    fdb = t;
  }

  // find matches
  lseek(fda, 0, SEEK_SET);
  ReadBuf rd = {fda, 0, 0};
  int lo = 0;
  int hi = 0;
  while((e = bread(&rd)) != NULL) {
    recent[hi] = *e;
    print[hi] = 0;
    while(recent[lo].t <= e->t - 100) {
      int x = recent[lo].b & 16383;
      if(bcount[x] != 255) bcount[x]--;
      if(print[lo])
    printf("%d %d %d\n", recent[lo].a, recent[lo].b, recent[lo].t);
      lo++;
    }
    if(bcount[e->a & 16383] != 0) {
      // somewhere in the window is a b that matches the
      // low 14 bits of a.  Find out if there is a full match.
      for(int k = lo; k < hi; k++) {
    if(e->a == recent[k].b)
      print[k] = print[hi] = 1;
      }
    }
    int x = e->b & 16383;
    if(bcount[x] != 255) bcount[x]++;
    hi++;
    if(hi == 65536) {
      if(lo == 0) {
    printf("recent buffer too small!\n");
    exit(1);
      }
      memmove(&recent[0], &recent[lo], (hi - lo) * sizeof(entry));
      memmove(&print[0], &print[lo], (hi - lo) * sizeof(char));
      hi -= lo;
      lo = 0;
    }
  }
}

```

# Answer
> 3 votes
# Tcl with SQLite, score less than 0.05

Shove the lines into an SQL database, then make SQLite do the work. Requires the Tcl bindings for SQLite 3, OpenBSD package sqlite3-tcl, Ubuntu package libsqlite3-tcl.

Usage: `tclsh filter.tcl <input.txt >output.txt`

```
package require sqlite3

sqlite3 db ""
db eval {
    begin transaction;
    create table lines(i integer primary key,
               a integer, b integer, t integer);
}
while {[gets stdin line] >= 0} {
    lassign [split $line] a b t
    db eval {insert into lines values(null,$a,$b,$t)}
}
db eval {
    create view pairs as
      select first.i, second.i as j
      from lines as first, lines as second
      where first.a == second.b and
        first.t - second.t between 0 and 99 and
        first.i != second.i;
    select a, b, t from lines
      where i in (select i from pairs union select j from pairs);
} {
    puts "$a $b $t"
}
db close

```

## Comparison of time

The motto of SQLite is, "Small. Fast. Reliable. Choose any three," but my SQL query is not fast. My program took more than **six hours** with my slow hard disk. I compare times for three programs:

With 50 million lines of input, *cfilter* and *hfilter* both crash because my data size limit is only 1 GB. (The default limit in OpenBSD is 512 MB.) If I raise my limit to 8 GB with `ulimit -Sd 8388608`, then I can run both *cfilter* and *hfilter*. I also lower my physical memory limit with `-m 3000000` so that other programs stay in RAM, not in swap space. I have only 4 GB of RAM.

```
$ ulimit -Sd 8388608 -m 3000000
$ time ./cfilter input.txt >output.txt
    0m9.03s real     0m5.17s user     0m1.97s system
$ ln -sf input.txt test.file
$ time ./hfilter >output2.txt
    0m25.62s real     0m22.08s user     0m2.04s system
$ time tclsh8.6 filter.tcl <input.txt >output3.txt
^Z  371m19.57s real     0m0.00s user     0m0.00s system
[1] + Suspended            tclsh8.6 filter.tcl < input.txt > output3.txt

```

I suspended *filter.tcl* after more than 6 hours. `top` shows that *filter.tcl* used less than 15 MB of memory and less than 12 minutes of processor time. Most of the 6 hours went to wait for my slow hard disk (5400 rpm).

For score, 10 seconds for *cfilter*, divided by more than 6 hours for *filter.tcl*, times 100, equals **less than 0.05**.

## Comparison of results

The different filters do not select the same lines! Consider these 6 lines of input:

```
$ cat example.txt
1 801 33
802 1 33
2 803 499
804 2 400
805 2 400
3 3 555

```

My *filter.tcl* outputs five lines, all except `3 3 555`.

```
$ tclsh8.6 filter.tcl <example.txt
1 801 33
802 1 33
2 803 499
804 2 400
805 2 400

```

But *cfilter* only outputs three lines:

```
$ ./cfilter example.txt
804 2 400
805 2 400
2 803 499

```

*cfilter* seems to have a bug when `T - U == 0`. It fails to output the lines `1 801 33` and `802 1 33`, though I believe them to be a matching pair.

Now for *hfilter* and the Scala program by the same author:

```
$ ln -sf example.txt test.file
$ ./hfilter
804 2 400
2 803 499
805 2 400
2 803 499
3 3 555
3 3 555
$ scala Filterer example.txt /dev/stdout
804 2 400
2 803 499
802 1 33
1 801 33
805 2 400
2 803 499
3 3 555
3 3 555

```

*hfilter* also misses the lines `1 801 33` and `802 1 33`, but the Scala version finds them. Both programs output `2 803 499` twice (because it is in two matching pairs), but I might ignore such duplication. Both programs also output `3 3 355`. This line is in a pair with itself because `A = B`. This is only correct if the phrase "another input line" includes the same line.

When the input is the random 50 million lines from the Python script, these differences might disappear. The probability that any matching pair has `T - U = 0`, or any line has `A = B`, is close to zero when the input has random numbers up to 50 million.

---
Tags: code-challenge, fastest-code, restricted-memory
---


# Question
Title: Write a Boolfuck Compiler or Interpreter
**From now on considering the word "fuck" to be non-profane would be a good idea**

Make the smallest compiler or an interpreter for the Brainfuck variant, Boolfuck. It has to be executable in Windows, DOS, or a Unix operating system (so Linux, Mac, OpenBSD etc). Boolfuck is very similar to Brainfuck, and a complete definition can be found here.

# Differences from Brainfuck

1. Works with bits not bytes (each cell is a single bit)
2. The output character is `;` not `.`
3. The input is read in little endian mode and reads a single bit at a time.
4. Output is stored to a stream, then outputted in little endian mode

# Rules

1. Use **bits** for the cells, not bytes
2. Support the complete list of operations from the official definition:

```
+  Flips the value of the bit under the pointer.

,  Reads a bit from the input stream, storing it under the pointer.
   The end-user types information using characters, though. Bytes
   are read in little-endian order; the first bit read from the
   character a, for instance, is 1, followed by 0, 0, 0, 0, 1, 1,
   and finally 0.

;  Outputs the bit under the pointer to the output stream. The bits
   get output in little-endian order, the same order in which they
   would be input. If the total number of bits output is not a
   multiple of eight at the end of the program, the last character
   of output gets padded with zeros on the more significant end. If
   the end-of-file character has been input, outputs a zero to the
   bit under the pointer.

<  This moves the pointer left by one bit.

>  This moves the pointer right by one bit.

[  If the value under the pointer is zero, jumps forward, just past
   the matching ] character.
]  Jumps back to the matching [ character.

```

Any character not in the official definition is ignored.
3. The program must start in the middle of the tape, not on an end.
4. The tape must be unbounded in size (infinite in both directions).

Here is a sample Boolfuck program; it outputs `Hello, world!`:

```
;;;+;+;;+;+;
+;+;+;+;;+;;+;
;;+;;+;+;;+;
;;+;;+;+;;+;
+;;;;+;+;;+;
;;+;;+;+;+;;
;;;;;+;+;;
+;;;+;+;;;+;
+;;;;+;+;;+;
;+;+;;+;;;+;
;;+;;+;+;;+;
;;+;+;;+;;+;
+;+;;;;+;+;;
;+;+;+;

```

# Answer
> 8 votes
## Perl - 171 bytes

```
#!perl -0
%h=qw(< --$p > ++$p + $$p^=1 [ while($$p){ ] } ; $o|=$$p<<$g++;$g&=7or$o=!print+chr$o , $f&=7or$_=getc;$$p=1&ord>>$f++);$p=-1e9;eval<ARGV>=~s/./$h{$&};/gr;$g&&print+chr$o

```

Counting the shebang as 1 byte.

This translates the source into perl, and then evaluates the translation. The target program is taken as a command line argument, input sent to the program should be piped via stdin.

Sample usage:

```
$ perl boolf.pl hello.blf
Hello, world!

```

---

**Details**

Each of the commands is translated as follows:

`<``--$p;`
`>``++$p;`
`+``$$p^=1;`
`[``while($$p){`
`]``}`
`;``$o|=$$p<<$g++;$g&=7or$o=!print+chr$o;`
`,``$f&=7or$_=getc;$$p=1&ord>>$f++;`

Negative integers are valid variable names, which is exploited here. `$p`, the cell pointer, is initialized as *-1000000000*, which is approximately at the center of the valid range, *-2147483648 .. -1*.

I've violated the specification in one regard: output is not printed all at once at the end, but rather as soon as a full byte has been collected. It's slightly longer this way, but I think it's more useful, as it allows for interactive scripts. For example, the Rot13 program below can be run in 'interactive mode', terminating the program with an eof char (`^D` on linux, `^Z` on windows).

> **Edit - Demonstration of Endianness**
>
> There seems to be some doubt as to whether this interpreter reads bits in the proper (little-endian) order. I offer the following Boolfuck program, which reads a total of *8* bits, one at a time, and outputs each value read as its numeric ascii representation (`0` outputs character *48*, `1` outputs character *49*). Each value is output entirely before the next bit is even read.
>
> ```
> ,;[+];;;+;;+;;
> ,;[+];;;+;;+;;
> ,;[+];;;+;;+;;
> ,;[+];;;+;;+;;
> ,;[+];;;+;;+;;
> ,;[+];;;+;;+;;
> ,;[+];;;+;;+;;
> ,;[+];;;+;;+;;
>
> ```
>
> Sample usage:
>
> ```
> $ echo a | perl boolf.pl test.blf
> 10000110
>
> ```
>
> From the problem description:
> *"Bytes are read in little-endian order; the first bit read from the character `a`, for instance, is 1, followed by 0, 0, 0, 0, 1, 1, and finally 0."*
>
> According to this description, the bits are read in the proper order.

---

**Stress Testing**

First, a script to translate Brainfuck programs into Boolfuck:

```
#!perl -n0

%h = (
  '+' => '>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<<',
  '-' => '>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]<<<<<<<<<',
  '<' => '<<<<<<<<<',
  '>' => '>>>>>>>>>',
  ',' => '>,>,>,>,>,>,>,>,<<<<<<<<',
  '.' => '>;>;>;>;>;>;>;>;<<<<<<<<',
  '[' => '>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]',
  ']' => '>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]'
);

$o .= $h{$_} for /./g;
$o =~ s/<(?R)?>//g;
print $o

```

---

The Rot13 program from the Brainfuck Wiki Page translates thusly (with slight modification for null byte eof, rather than 255):

```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<+[>+]<[<]>>>>>>>>>]<[+<]+<<<<<<
<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<
<<+[>+]<[<]>>>>>>>>>]<[+<]<<<<<<<<;>;>;>;>;>;>;>;>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<
<<[>]+<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]+<
<<<<<<<+[>+]<[<]>>>>>>>>>[+]<<<<<<<<,>,>,>,>,>,>,>,>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]

```

On a 26 character string, this runs in approximately 0.17 seconds:

```
$ echo abcdefghijklmnopqrstuvwxyz | timeit perl boolf.pl rot13.blf
nopqrstuvwxyzabcdefghijklm

Elapsed Time:     0:00:00.171

```

---

The `squares.b` from Daniel Cristofani's site:

```
>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<
<<<[>]+<[+<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>>[>]+<
[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]
+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+
]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<
<<<<[>]+<[+<]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]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+]<[<]>>>>>>>>>]<[+<]>>>>>>>>>+<<<<
<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>;>;>;>;>;>;>;>;<<<<<<<;>;>;>;>;>;>;>;<<<<<<
<;>;>;>;>;>;>;>;>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]

```

Runs in about 2.4s:

```
$ timeit perl boolf.pl out.dat
0
1
4
9
16
25
36
49
64
81
100
121
144
169
196
225
256
289
324
361
400
441
484
529
576
625
676
729
784
841
900
961
1024
1089
1156
1225
1296
1369
1444
1521
1600
1681
1764
1849
1936
2025
2116
2209
2304
2401
2500
2601
2704
2809
2916
3025
3136
3249
3364
3481
3600
3721
3844
3969
4096
4225
4356
4489
4624
4761
4900
5041
5184
5329
5476
5625
5776
5929
6084
6241
6400
6561
6724
6889
7056
7225
7396
7569
7744
7921
8100
8281
8464
8649
8836
9025
9216
9409
9604
9801
10000

Elapsed Time:     0:00:02.421

```

# Answer
> 3 votes
# Python (531 byte compiler)

This is a source-to-source compiler: it compiles Boolfuck to Python. Takes input from a file as its first argument, outputs Python code to file `o` in the current dict.

```
exec"eJxdUs1u8yAQvOcpEBez/lNS9RDZpS+C+CQ3xg5RwlKMmkTV9+5l7bZue2RmZ4YdGAJe2HSfmL14DDFvndy2o0RvnOjC+KZ2Gupgul5A20vFh7/zM2CjCRHxvMI+2UQ5mZh0KJXmuu2LpD9J9WKdwNCLO4Bqdk210wMGdmfWsSn21n3G6dbKS+eFdbE8HLskytWtyLZZfk53u0G1J9mNZCcNwO3AS54OIzPnyXCuN8QfiB8bynY5Z7wQPP6T7/4/zRdcysMyHuuu74UHOzBbe/QCCGYxXeaCbyYxS8C3AJOjJ/OoiWlXxldyR9DTD6hYoOcVuh7t2bDFoSFOrRxPy7tCPrJfMKtmQK/AdjN3ijLL6hOmhqivKYbyqzcEmOtHNTRDsdeMKhkoM3RuNGJbUpcI5T4l0ka47D7XLPbVzKr0QpB4H5LlV9LhGChBvKqGXrB8ACDvV/JGSK89/6A8w2sG9TWkDyKyzae2B/gAiGHBlw".decode('base64').decode('zip')

```

If you really really mind the cheating with the zip and all that, the actual code is 631 bytes long (longer than the original Brainfuck compiler, but shorter than the original False compiler):

```
from sys import*;n=0;g=open(argv[1]).read();d=["from sys import*;from itertools import*;p=0;t=set();o=[]"];d+=["j=[bin(ord(y))[:1:-1]for y in stdin.read()];i=map(int,chain(*[x+'0'*len(x)-8for x in j]))"if","in g else""]
for c in g:d+=[n*" "+("t^={p}"if"+"==c else"t.add(p)if i.pop()else t.remove(p)"if","==c else"o+=[p in t]"if";"==c else"p-=1"if"<"==c else"p+=1"if">"==c else"while p in t:"if"["==c else"")];n+=4 if"["==c else -4 if"]"==c else 0
d+=["o=''.join(map(str,map(int,o)));o=[o[f:f+8] for f in range(0,len(o),8)];o+=[o.pop()+'0'*(8-len(o[-1]))];print''.join(chr(int(q[::-1],2))for q in o)"];open(*'ow').write('\n'.join(d))

```

> This is possibly the fugliest python I've ever written, even though the `open(*'ow')` instead of `open('o','w')` made me feel really smart ;)

With a (slightly) better layout:

```
import sys

n = 0
g = open(sys.argv[1]).read()
d = ["from sys import*;from itertools import*;p=0;t=set();o=[]"]
d += [
    "j=[bin(ord(y))[:1:-1]for y in stdin.read()];i=map(int,chain(*["
    "x+'0'*len(x)-8for x in j]))" if "," in g else ""]
for c in g:
    d += [n * " " + (
        "t^={p}" if "+" == c
        else "t.add(p)if i.pop()else t.remove(p)" if "," == c
        else "o+=[p in t]" if ";" == c
        else "p-=1" if "<" == c
        else "p+=1" if ">" == c
        else "while p in t:" if "[" == c
        else "")]
    n += 1 if "[" == c else -1 if "]" else 0
d += [
    "o=''.join(map(str,map(int,o)));o=[o[f:f+8] for f in range(0,len(o),"
    "8)];o+=[o.pop()+'0'*(8-len(o[-1]))];print''.join(chr(int(q[::-1],"
    "2))for q in o)"]

open(*'ow').write('\n'.join(d))

```

And lastly, the example output for the "Hello World" test you gave:

```
from sys import*;from itertools import*;p=0;t=set();o=[]

o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]

t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]

o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]

o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]

t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]

o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]

o+=[p in t]
o+=[p in t]
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]

t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]

t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]

o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]

o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]

o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]

t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]

o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o=''.join(map(str,map(int,o)));o=[o[f:f+8] for f in range(0,len(o),8)];o+=[o.pop()+'0'*(8-len(o[-1]))];print''.join(chr(int(q[::-1],2))for q in o)

```

A memfiller, `+[>+]` also works really well (and quick, consuming about 2 gigs in 10 seconds):

```
from sys import*;from itertools import*;p=0;t=set();o=[]

t^={p}
while p in t:
    p+=1
    t^={p}

o=''.join(map(str,map(int,o)));o=[o[f:f+8] for f in range(0,len(o),8)];o+=[o.pop()+'0'*(8-len(o[-1]))];print''.join(chr(int(q[::-1],2))for q in o)

```

# Answer
> 1 votes
# Perl, 325 bytes

```
undef$/;open C,'<',pop;@I=split//,unpack'b*',<>;@C=split//,<C>;while($c<@C){$_=$C[$c];$D=\$D{$d};$$D=!$$D if/\+/;$$D=shift@I if/,/;/</&&$d--;/>/&&$d++;$O.=$$D?1:0if/;/;if(/\[/&&!$$D){$L=1;while($L){$L++if$C[++$c]eq'[';$L--if$C[$c]eq']'}}if(/]/){$L=1;while($L){$L++if$C[--$c]eq']';$L--if$C[$c]eq'['}$c--}$c++}print pack'b*',$O

```

The script `boofuck.pl` is an interpreter for Boolfuck. The argument is a file name that contains a Boolfuck program. It reads STDIN and outputs to STDOUT.

**Remarks:**

* I have ignored the last sentence of the description for operator `;`, because I haven't understood it:

> If the end-of-file character has been input, outputs a zero to the bit under the pointer.
* The script always reads STDIN, even if the boolfuck program does not contain a `,` operator.

**Ungolfed:**

```
# name conventions:
# "I" for input:
#         @I is array with "0" and "1" for the bits in STDIN
# "O" for output:
#         $O is output string with "O" and "1" for the output bits
# "C" for code:
#         @C is array of code byts
#         $c is code pointer
# "D" for data:
#         %D is "infinite" data band, hash is used to allow negative indexes
#         $d is data pointer
undef $/;                    # without input line separator <> reads the whole file.
open C, '<', pop;            # open program file, given as command line argument
@I = split //,             #/# split input bit string into array of (bit) characters
     unpack 'b*',            # convert input string into bit string with 0 and 1
     <>;                     # get STDIN
@C = split //,             #/# split program code string in byte array
     <C>;                    # get program code as string
while ($c < @C) {            # finished if the end of the program code is reached
    $_ = $C[$c];             # $_ contains operator
    $D = \$D{$d};            # $D is a reference to the data bit under the data pointer
# case '+':
    $$D = !$$D if /\+/;      # flip data bit value under the data pointer
# case ',':
    $$D = shift @I if /,/; #/# store input bit to data bit under the pointer
# case ';':
    $O .= $$D ? 1 : 0 if /;/;
                           #/# append current data bit to the output
# case '<':
    /</ && $d--;           #/# move data pointer to the left
# case '>':
    />/ && $d++;           #/# move data pointer to the right
# case '[':
    if (/\[/ && !$$D) {      # if current data bit is unset,
                             # jump to the matching ']'
        $L = 1;              # each '[' increments $L,
                             # each ']' decrements $L
        while ($L) {         # $L is zero in case of a matching ']'
            $L++ if $C[++$c] eq '[';
            $L-- if $C[$c]   eq ']'
        }
        # at the end of the outer loop, the code pointer is automatically increased
        # to get right after the matching ']'
    }
# case ']':
    if (/]/) {               # jump back to the matching '['
        $L = 1;
        while ($L) {
            $L++ if $C[--$c] eq ']';
            $L-- if $C[$c]   eq '['
        }
        $c--                 # at the end of the outer loop the code pointer
                             # is increased; therefore the code pointer is
                             # decreased to get right at the matching '['
    }
# else:
    # ignore other characters
# continue:
    $c++                     # increment code pointer
}
print pack'b*', $O           # convert output bits to bytes and print result

```

**Examples:**

* "Hello World" example from the question

```
perl boolfuck.pl helloworld.boolfuck </dev/null

```

Result (with new line at the end):

```
Hello, world!

```
* Example that reverses the input from the Boolfuck website:

```
>,>,>,>,>,>,>,>,<<<<<<<<
>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]
>>>>>>>>>
>,>,>,>,>,>,>,>,<<<<<<<<
>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]
<<<<<<<<<
>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]
>;>;>;>;>;>;>;>;<<<<<<<<
<<<<<<<<<
>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]

```

Running it:

```
echo -ne "\nHello World" perl boolfuck.pl reverse.boolfuck

```

Result (with new line at the end):

```
dlroW olleH

```

---
Tags: code-golf, interpreter, brainfuck
---


title: Write an aphorism using valid code

text:
# Question
Title: Write an aphorism using valid code
Can you write an aphorism in at most 4 lines of code ?

Code should read as much as possible as an aphorism in plain English and should return the boolean `true`.

Language: of choice.

Criteria for accepted answer: Most votes in 180 ~~30~~ days. (8th of July 2014)

Originality: can be an old aphorism but a creative one would be much more appreciated.

# Answer
> 51 votes
# Python

```
import this
love = this
this is love, love is not True or False, love is love
# (True, True, True)

```

Okay, this returns a tuple of Truths, but that itself evaluates as True anyway.

# Answer
> 29 votes
## Forth

```
2 : b or ! 2 ." b" ;
: that s" the questi" on ;

```

# Answer
> 20 votes
# C:

You'll have to squint a bit to read this one :-)

```
int x(){ int __,L        ;
     return (__ |__ ||__ |__ ,__,__ ,__ ,__ ,__  ,
             __||  1||__ |  1L/L|__||__|1/__|  1L)
                                ;   }

```

You might notice a potential division-by-zero error on line 3, but this is never executed because the expression evaluates as `true` before the calculation is performed.

# Answer
> 19 votes
It's difficult to avoid string literals, comments and tricks fo this kind, but I tried to keep them to a mininum. Also, the first line makes no sense. Well, I had `fun` doing it

## F#

```
(fun () -> (fun (_) -> // fun fun? wtf
try not <| failwith("me") ; (*but*) with |Failure((*co*)me(*s*)) -> true)("learning"))()
// "Try not to fail with me, but with failure comes true learning

```

I could also do some declaration abusing, but I ended up not finding a way to return true:

```
let the,bodies,hit_the=floor(0.0),(),()

```

or

```
let the_games=bigint() //pun intended

```

I really need to stop with the puns.

# Answer
> 18 votes
# C

No string literals or comments:

```
Better(to,re);main(silent){and();}be(thought,a,fool){}
than(to,open,your,mouth);and(){}remove(all,doubt);

```

Split over two lines, but one would work fine as well.

When compiled using gcc on Linux (x86-64), this produces an executable which exits with success (exit code 0), the same as the `true` Unix utility; this being how I choose to interpret the requirement of returning boolean `true` in a non-scripting language.

Note: notwithstanding the abuse of the "implicit int" rule, the principal trick behind this program is that while a C program that falls off the end of `main` without a `return` statement will usually result in a non zero exit code, by calling another function we can set the `EAX` register which is then used as the exit code of the program. This is of course totally undefined behaviour and utterly non portable.

# Answer
> 17 votes
# Python

```
war=peace=freedom=slavery=ignorance=strength=0
war is peace|freedom is slavery|ignorance is strength

Power=a=means=it=an=end=0
Power is not (a, means, it is (an, end))

```

# JavaScript

```
You=true;function BigBrother(){};BigBrother.isWatching=function(y){return y};
BigBrother.isWatching(You)

```

# Answer
> 15 votes
# C#:

```
short life = 0;
return (life is short);

```

"Life is short" (Hippocrates)

# Answer
> 14 votes
# Ruby

```
class String
  def before(b) self < b end
end

```

A bit lengthy, but gets us a few aphorisms:

```
"age".before("beauty")
"business".before("pleasure")
"pearls".before("swine")

```

And (stretching slightly):

```
dont = []; y = 1
dont.count + y or ('chickens'.before('they hatch'))

```

# Answer
> 11 votes
# Scala

```
Some apply Double forall _; None isEmpty

```

# Answer
> 11 votes
# CoffeeScript

```
2 * @wrong isnt @right

```

=\> true

# Answer
> 10 votes
# C++

```
bool life = true;
bool fair = false;

assert(life != fair);

```

# Answer
> 8 votes
# Python

```
love=[True];all,fair,war=love*3
all is fair in love and war

```

# Answer
> 7 votes
An aphorism about http verbs, in

## Ruby

```
puts do
something idempotent but are considered to be unsafe
because if the value at the beginning of a chain of calls is one possibly the value at the
end != 1

```

# Answer
> 4 votes
## C

```
if ((ifs && ands) == (pots && pans))
    work_for_tinkers_hands = FALSE;

```

# Answer
> 4 votes
# Javascript

```
function be(who) {
   if (who == 'thine own self') {
      return true;
   }
}

```

An approximation of "To thine own self be true."

I'm kind of fudging with the requirements, since it only returns true in one particular case ... but I'm hoping you'll let it slide because the return value is actually part of the aphorism.

# Answer
> 4 votes
I got a wonderful error while attempting this:

It's very much inspired by Darren Stone's answer.

> TypeError: Cannot use 'in' operator to search for 'tis nobler' in mind to suffer the The Slings and Arrows of outrageous fortune

# Javascript

```
[2].be || ! [2].be ; this.is, "the question"

```

It returns an implicit true.

Slightly less terse, with a question mark:

```
[2].be || ! [2].be? is = this: !"the question"

```

# Answer
> 4 votes
# C

```
main(int I,char **think) {char *a="there"; for (;--I;) a['m'];}

```

# Answer
> 4 votes
# C

```
int main(int fear, int* computers){ int

    i; do { !fear; computers[i]; fear; "the lack of them";

} while();return true;}

```

*I do not fear computers, I fear the lack of them.*

-Isaac Asimov

# Answer
> 3 votes
A bit lazy, but my take.

# Python:

```
life = short = True; art = long = True; life=art
life is short and art is long

```

# JavaScript:

```
The = word = 'Yoga'
has = been = 'vulgarized'
and = does = not=  mean = anything =Date.now() ,!''
//Swami Rama

```

# Answer
> 3 votes
# PHP

```
$all = array('not well', 'not well', 'not well', 'well');
$end = array_pop($all);
$all = ($end == 'well') ? $end : 'not well';
return true;

```

"All's well that ends well."

# Answer
> 3 votes
# Q

`any bird:`int$"hehand"=2^`int$"hebush"`

and

`(./) 2_iscomp:any 3,'s:"a",'"crowd"`

# Answer
> 3 votes
# PHP

An apple a day...

```
$aphorism = function(){
    for($day=1;$day<=365;$day++) $apple++;
    return ($apple==365) ? true : 'doctor';
};

```

# Answer
> 3 votes
# Common Lisp

```
(Do ((as)) ('(I say no)t) as I do)
(time (and 'tide (wait-for 'no-man))) ;requires sbcl

```

# Answer
> 3 votes
# Lua

```
-- all search is in vain
function search() end
-- only the void is true
function void() return function() return true end, true end
-- and what remains is to
for ever in void() do repeat search("light") until true end
return true

```

# Answer
> 3 votes
# JavaScript

```
return (Do || !Do) || (there == !try);

```

```
return 2 * be || !(2 * be);

```

# Answer
> 3 votes
## R

```
the_whole <- c(-1,-1)
the_part <- -1
the_whole > sum(the_part,the_part)

```

-Socrates

# Answer
> 2 votes
## Simply-Basic 84

```
Label 1;a random number between 0 and 1~should be stored in~A
If A is equal to 1 Then Display A End;Stop&Else,Go to label 1
:End; Otherwise destroy quantum transmitters internationally.
Since quantum transmitters are gone, power lost. KA-POW, yes?

```

# Answer
> 2 votes
# Prolog

```
waste(not).

want(X) :-
    waste(X).

```

# Answer
> 2 votes
**Python**

```
be = that = the = question = 1
2 - be or not 2 - be
that is the & question

```

# Answer
> 2 votes
**Ruby**

Not the most elegant solution, but very easy to read

```
def you_know_meaning(x) true end

!!!("aphorism" != "aphorism" unless you_know_meaning "aphorism")

=> true

```

# Answer
> 2 votes
# JAVA

```
public static boolean think(){return true;}public static boolean so()
{return true;}public static boolean be(){return true;}static{boolean i=true;
    System.out.println((i==think())?so():i==be());
}

```

I think so i be --Descartes

# Answer
> 2 votes
# C++

```
int main() {
  int right,might;
  might==right;
}

```

Might is right.

# Answer
> 2 votes
# Haskell

Be original!

```
do otherwise

```

It returns True.

# Answer
> 1 votes
# Rebol

```
Rebol []
between: :if thought: expression: true lies: func ['a 'b] [a != b]

between thought and expression [lies a lifetime]

```

### Some explanation

The above code translates to:

```
if thought and expression [lies word-arg1 word-arg2]

```

The `if` statement is true so the `lies` function is called which returns *true* as along as the two arguments provided are different.

# Answer
> 1 votes
# Perl

```
sub between (&@) { $_[1] if $_[0]->() } sub lies { $_[0] ne $_[1] }
my ($thought, $expression) = (1,1);

between {$thought and $expression} lies a => 'lifetime';

```

NB. Above works fine with (or without) `strict` and `warnings` pragmas.

# Answer
> 1 votes
## Ruby vs Friedrich Nietzsche

```
=> class Lie
=>   def self.is_a_condition_of?(life);true;end
=> end
=> Lie.is_a_condition_of?("life") # => true

```

# Answer
> 1 votes
# Javascript

`get: with(this) 1;`

I think this makes sense.

Edit: was notified it didn't return `true`, well now it does.

# Answer
> 1 votes
Is my use of the literal string true cheating?

This is an AutoHotkey script:

```
Be("true") to yourself

Be(msg) {
    MsgBox % msg
}

```

# Answer
> 1 votes
# Rebol

```
love: true
war:  false

if true? any [love is blind and war is hell] [make love not war]

```

# Answer
> 1 votes
Not one of my favourite songs, still a great album.

# PHP

```
$_GET['this'] or die(!0);

```

**Reads as:** Get this or die! (No!)

*Get This*
Slipknot
1999

# Answer
> 1 votes
# T-SQL

I made several attempts at this challenge before arriving at an answer that expresses truth through the code itself. After a few attempts at turning favorite quotes into pithy code translations, I realized the way to go was to set aside quotation entirely and let the language of choice simply speak the wisdom it is capable of speaking.

Since SQL is verbose, I have chosen to break this 4-line program into more lines for ease of reading without horizontal scrolling. The properly "golfed" version may be found on this SQLFiddle.

```
DECLARE @mindInTurmoil BIT = 'True'
Samsara: SELECT 'equanimity' AS Attitude, 0 AS Ego INTO #Self
    WHERE @mindInTurmoil = 'True'
IF (SELECT TOP 1 Attitude FROM #Self ORDER BY Ego) = 'equanimity'
    SET @mindInTurmoil = 'False' ELSE GOTO Samsara
SELECT CASE @mindInTurmoil
    WHEN 'True' THEN 'False' WHEN 'False' THEN 'True' END AS Liberation

```

Returns:

```
Liberation
----------
True

```

# Answer
> 1 votes
## Java (probably others too)

```
boolean hasExceptions(Rule rule) { return rule != this; }

```

"There are always exceptions, except to this rule." - by me.

# Answer
> 1 votes
**JavaScript**

```
function healthy_community(diversity){
    return (diversity === true) ? true : false;
}
healthy_community(true);

```

# Answer
> 1 votes
## Groovy

```
short Short;
short life = Short;
assert life.is(Short);

```

# Answer
> 1 votes
**Java**

```
for (Person person : people) {
    if (!HouseTypeEnum.GLASS_HOUSE.equals(person.getResidence().getHouseType()))
        throw new StonesException();
}

```

# Answer
> 1 votes
**Mathematica**

```
 mo[thing__] := MemberQ[{thing}, money | problems | True]
 mo[money~mo~problems]

```

# Answer
> 1 votes
# Javascript

```
with = javascript = we = can = create = any = aphorism = returning = true;

```

# Answer
> 1 votes
## C

This quote is a line from My Fair Lady. See here https://www.youtube.com/watch?v=uVmU3iANbgk

```
#include <stdio.h>
/*the rain */int /*Spain falls*/ main/*ly*/(){return puts("on the plane")>0?1:0;}

```

# Answer
> 0 votes
## TI-BASIC

```
2_be or not(2_be)

```

---
Tags: popularity-contest
---


title: Recognize handwritten digits

text:
# Question
Title: Recognize handwritten digits
Your task is to read an image containing a handwritten digit, recognize and print out the digit.

**Input:** A 28\*28 grayscale image, given as a sequence of 784 plain-text numbers from 0 to 255, separated by space. 0 means white and 255 means black.

**Output:** The recognized digit.

**Scoring:** I will test your program with 1000 of the images from the MNIST database training set (converted to ASCII form). I have already selected the images (randomly), but will not publish the list. The test must finish within 1 hour, and will determine `n` \- the number of correct answers.
`n` must be at least 200 for your program to qualify. If the size of your source code is `s`, then your score will be calculated as `s * (1200 - n) / 1000`. Lowest score wins.

**Rules:**

* Your program must read the image from the standard input and write the digit to the standard output
* No built-in OCR function
* No third-party libraries
* No external resources (files, programs, web sites)
* Your program must be runnable in Linux using freely available software (Wine is acceptable if necessary)
* The source code must use only ASCII characters
* Please post your estimated score and a unique version number every time you modify your answer

**Example input:**

```
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 18 18 18 126 136 175 26 166 255 247 127 0 0 0 0 0 0 0 0 0 0 0 0 30 36 94 154 170 253 253 253 253 253 225 172 253 242 195 64 0 0 0 0 0 0 0 0 0 0 0 49 238 253 253 253 253 253 253 253 253 251 93 82 82 56 39 0 0 0 0 0 0 0 0 0 0 0 0 18 219 253 253 253 253 253 198 182 247 241 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 80 156 107 253 253 205 11 0 43 154 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 14 1 154 253 90 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 139 253 190 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 11 190 253 70 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 35 241 225 160 108 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 81 240 253 253 119 25 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 45 186 253 253 150 27 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 93 252 253 187 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 249 253 249 64 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 46 130 183 253 253 207 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 39 148 229 253 253 253 250 182 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 24 114 221 253 253 253 253 201 78 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 23 66 213 253 253 253 253 198 81 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 18 171 219 253 253 253 253 195 80 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 55 172 226 253 253 253 253 244 133 11 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 136 253 253 253 212 135 132 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

```

By the way, if you prepend this line to the input:

```
P2 28 28 255

```

you will obtain a valid image file in pgm format, with inverted/negated colors.

This is what it looks like with correct colors:

**Example output:**

```
5

```

**Standings:**

```
No.| Name         | Language   | Alg | Ver | n   | s   |  Score
----------------------------------------------------------------
 1 | Peter Taylor | GolfScript | 6D  | v2  | 567 | 101 |  63.933
 2 | Peter Taylor | GolfScript | 3x3 | v1  | 414 | 207 | 162.702

```

# Answer
> 8 votes
## GolfScript 6D (v2: estimated score 101 * 0.63 ~= 64)

This is a very different approach to my earlier GolfScript answer, so it makes more sense to post it as a separate answer at v1 than to edit the other answer and make this v2.

```
~]:B;569'!EM,R.==|%NL2+^=1'{{32-}%95{base}:^~\^}:&~2/{~B=<}%2^10'#]8Y,;KiZfnnRsDzPsvQ!%4C&..z,g,$m'&=

```

### Ungolfed

```
~]:B;
[30 183 21 378 31 381 7 461 113 543 15 568]
2/{~B=<}%2base
7060456576664262556515119565486100005262700292623582181233639882 10base
=

```

### Explanation

The raw problem is classification of points in a 784-dimensional space. One standard approach is dimension reduction: identifying a small subset of dimensions which provide sufficient distinguishing power to do the classification. I evaluated each dimension and each possible threshold to identify 18 pairs of (dimension, range of threshold) which looked promising. I then picked the centre of each range of threshold, and evaluated 6-element subsets of the 18 pairs. Finally I optimised the threshold for each dimension of the best 6-D projection, improving its accuracy from 56.3% to 56.6%.

Because the projection is into 6 dimensions and for each dimension I apply a simple threshold, the final lookup table only needs 64 elements. It doesn't seem to be particularly compressible, so the main golfing is to base-convert both lookup tables (the list of dimension and thresholds; and the halfspace vector to digit map) and share the base-conversion code.

# Answer
> 6 votes
## GolfScript 3x3 (v1: estimated score 207 * 0.8 ~= 166)

```
~]28/10:?/{zip?/{[]*0-!!}/}%2{base}:^~'"yN(YZ5B 7k{&w,M`f>wMb>}F2A#.{E6T9kNP_s 3Q?V`;Z\'C-z*kA5M@?l=^3ASH/@*@HeI@A<^)YN_bDI^hgD>jI"OUWiGct%7/U($*;h*<"r@xdTz6x~,/M:gT|\\:#cII8[lBr<%0r&y4'{32-}%95^?^2/{))*~}%=

```

Or in overview,

```
~]28/10:?/{zip?/{[]*0-!!}/}%2{base}:^~'MAGIC STRING'{32-}%95^?^2/{))*~}%=

```

### Explanation

My approach at a high level is:

1. Threshold the pixels: if the pixel is above `t1` then set it to `1`; otherwise to `0`.
2. Group the pixels. Initially I broke the 28x28 grid into a 4x4 grid (each subgrid being 7x7 pixels); but breaking it into a 3x3 grid (subgrids being 10x10, 10x8, or 8x8 pixels) gives a massive reduction in lookup table size while dropping accuracy rate from about 56% to about 40%.
3. Sum the pixels in each group and threshold again: if the number of set pixels is above `t2` then score the group as `1`; otherwise as `0`.
4. Do a table lookup by the vector of group scores. (The table is compressed using run-length encoding and the standard base-conversion trick. Most choices of `t1` and `t2` leave between 50% and 63% of the table as "don't care" values, which can be combined with adjacent values to increase run lengths; the average run length in my v1 table is 3.6).

It turns out that setting `t1=t2=0`, although not optimal, isn't far off the best values of `t1` and `t2` in terms of accuracy; is pretty good in terms of table compressibility; and allows me to combine the two thresholding operations into `[]*0-!!` (flatten 2D array to 1D; remove `0`s; check whether it's empty).

The lookup table gives the most likely candidate for the given vector of group scores. It may well be possible to improve the score by identifying table entries which can be changed such that the improved compressibility of the table outweighs the decreased accuracy.

---
Tags: restricted-source, test-battery, optical-char-recognition
---


title: Hot Potato Salesman

text:
# Question
Title: Hot Potato Salesman
> Given a list of points, find the shortest path that visits all points and returns to the starting point.

The Travelling Salesman Problem is well-known in the computer science field, as are many ways to calculate/approximate it. It's been solved for very large groups of points, but some of the largest take many CPU-years to finish.

> Don't get burned by the potato.

Hot Potato is a game where 2+ players pass a "potato" around in a circle while music plays. The object is to pass it to the next player quickly. If you are holding the potato when the music stops, you're out.

---

The object of **Hot Potato Salesman** is:

> Given a set of **100 unique points**, return those points in a better order (*shorter total distance as defined further down*). This will "pass" the problem to the next player. They have to improve it and pass it to the next, etc. If a player cannot improve it, they are out and play continues until one player is left.

To keep this from being a "brute-force-me-a-path" competition, there are these stipulations:

* You cannot take more than **one minute** to pass the potato. If you haven't found and passed a shorter solution by the time one minute is up, you're out.
* You cannot change the position of more than **25** points. To be exact, `>= 75` points must be in the same position as you received them. It does not matter *which* ones you decide to change, just the *amount* you change.

When only one player is left, he is the winner of that game, and receives one point. A tourney consists of `5*n` games, where `n` is the number of players. Each game, the starting player will be *rotated*, and the remaining player order will be *shuffled*. The player with the most points at the end is the winner of the tourney. If the tourney ends with a tie for first place, a new tourney will be played with only those contestants. This will continue until there is no tie.

The starting player for each game will receive a set of pseudorandomly selected points in no particular order.

Points are defined as a pair of integer `x,y` coordinates on a cartesian grid. Distance is measured using Manhattan distance, `|x1-x2| + |y1-y2|`. All coordinates will lie in the `[0..199]` range.

## Input

Input is given with a single string argument. It will consist of 201 comma-separated integers representing the number of current players(`m`) and 100 points:

```
m,x0,y0,x1,y1,x2,y2,...,x99,y99

```

The order of these points is the current path. The total distance is obtained by adding the distance from each point to the next (`dist(0,1) + dist(1,2) + ... + dist(99,0)`). *Don't forget to return to start when calculating total distance!*

Note that `m` is *not* the number of players that started the game, it is the number that are still in.

## Output

Output is given in the same way as input, minus `m`; a single string containing comma-separated integers representing the points in their new order.

```
x0,y0,x1,y1,x2,y2,...,x99,y99

```

The control program will wait for output for one minute only. When output is received, it will verify that:

* the output is well-formed
* the output consists of *only* and *all* the 100 points present in the input
* `>=75` points are in their original positions
* the path length is less than the previous path

If any of these checks fail (or there is no output), you are out and the game will proceed to the next player.

## Control Program

You can find the control program at this link. The control program itself is deterministic, and is posted with a dummy seed of `1`. The seed used during scoring will be different, so don't bother trying to analyze the turn order/point lists it spits out.

The main class is `Tourney`. Running this will do a full tournament with contestants given as arguments. It spits out the winner of each game and a tally at the end. A sample tourney with two SwapBots looks like:

```
Starting tournament with seed 1

(0) SwapBot wins a game! Current score: 1
(1) SwapBot wins a game! Current score: 1
(1) SwapBot wins a game! Current score: 2
(1) SwapBot wins a game! Current score: 3
(0) SwapBot wins a game! Current score: 2
(1) SwapBot wins a game! Current score: 4
(1) SwapBot wins a game! Current score: 5
(1) SwapBot wins a game! Current score: 6
(1) SwapBot wins a game! Current score: 7
(1) SwapBot wins a game! Current score: 8

Final Results:

Wins        Contestant
2       (0) SwapBot
8       (1) SwapBot

```

If you want to test just one game at a time, you can run the `Game` class instead. This will run one game with players in the order given as arguments. By default, it will also print a play-by-play showing the current player and path length.

Also included are a few test players: `SwapBot`, `BlockPermuter`, and `TwoSwapBot`. The first two will not be included in scoring runs, so feel free to use and abuse them during testing. `TwoSwapBot` **will** be included in judging, and he's no slouch, so bring your A-game.

## Miscellany

* You cannot save state information, and each turn is a separate run of your program. The only information you will receive each turn is the set of points.
* You cannot use external resources. This includes network calls and file access.
* You cannot use library functions designed to solve/assist with the TSP problem or its variants.
* You cannot manipulate or interfere with other players in any way.
* You cannot manipulate or interfere with the control program or any included classes or files in any way.
* Multi-threading is allowed.
* One submission per user. If you submit more than one entry, I will only enter the first one submitted. If you want to change your submission, edit/delete the original.
* The tournament will be running on Ubuntu 13.04, on a computer with an i7-3770K CPU and 16GB RAM. It will not be run in a VM. Anything I perceive as malicious will immediately disqualify the current **and** any future entry you submit.
* All entries must be runnable from the command line with free (*as in beer*) software. If I have problems compiling/running your entry, I will request aid in the comments. If you do not respond or I cannot ultimately get it running, it will be disqualified.

## Results (22 May 2014)

New results are in! UntangleBot has beaten the competition quite soundly. TwoSwapBot managed seven wins, and SANNbot snuck a victory in as well. Here's a scoreboard, and a link to the raw output:

```
Wins        Contestant
22      (2) ./UntangleBot
7       (0) TwoSwapBot
1       (5) SANNbot.R
0       (1) BozoBot
0       (3) Threader
0       (4) DivideAndConquer

```

As it stands *now*, **UntangleBot** has won the checkmark. Don't let that discourage you from entering, though, since I'll run the tournament as more contestants appear and change the accepted answer accordingly.

# Answer
# UntangleBot (formerly NiceBot)

A C++11 bot that uses two strategies.
At first it will try to "untangle" the path if possible, by detecting intersections between paths that are closer than 25 points (since untangling implies modifying all points in-between).
If the first strategy fails, it randomly swaps points to find better distances until a better path has been found.

This bot consistently beats TwoSwapBot with an approximate ratio of five victories for one loss in my test tourneys.

```
// g++ -std=c++11 -O3 -o UntangleBot UntangleBot.cpp
#include <algorithm>
#include <chrono>
#include <cmath>
#include <iostream>
#include <iterator>
#include <random>
#include <set>
#include <sstream>

const int NPOINTS = 100;

struct Point {
    int x, y;

    Point():x(0),y(0) {}
    Point(int x, int y):x(x),y(y) {}

    int distance_to(const Point & pt) const {
        return std::abs(x - pt.x) + std::abs(y - pt.y);
    }
};

std::ostream & operator<<(std::ostream & out, const Point & point) {
    return out << point.x << ',' << point.y;
}

int total_distance(const Point points[NPOINTS]) {
    int distance = 0;
    for (int i = 0; i < NPOINTS; ++i) {
        distance += points[i].distance_to(points[(i+1)%NPOINTS]);
    }
    return distance;
}

bool intersects(const Point & p1, const Point & p2, const Point & p3, const Point & p4) {
    double s1_x, s1_y, s2_x, s2_y;
    s1_x = p2.x - p1.x;
    s1_y = p2.y - p1.y;
    s2_x = p4.x - p3.x;
    s2_y = p4.y - p3.y;

    double s, t;
    s = (-s1_y * (p1.x - p3.x) + s1_x * (p1.y - p3.y)) / (-s2_x * s1_y + s1_x * s2_y);
    t = ( s2_x * (p1.y - p3.y) - s2_y * (p1.x - p3.x)) / (-s2_x * s1_y + s1_x * s2_y);

    return s >= 0 && s <= 1 && t >= 0 && t <= 1;
}

int main(int argc, char ** argv) {
    Point points[NPOINTS];

    using Clock = std::chrono::system_clock;
    const Clock::time_point start_time = Clock::now();

    // initialize points
    if (argc < 2) {
        std::cerr << "Point list is missing" << std::endl;
        return 1;
    }
    std::stringstream in(argv[1]);
    int players;
    char v;
    in >> players >> v;
    for (int i = 0; i < NPOINTS; ++i) {
        in >> points[i].x >> v >> points[i].y >> v;
    }

    int original_distance = total_distance(points);

    // detect intersection between any 4 points
    for (int i = 0; i < NPOINTS; ++i) {
        for (int j = i+1; j < NPOINTS; ++j) {
            Point & p1 = points[i];
            Point & p2 = points[(i+1)%NPOINTS];
            Point & p3 = points[j];
            Point & p4 = points[(j+1)%NPOINTS];

            // points must all be distinct
            if (p1.distance_to(p3) == 0 || p1.distance_to(p4) == 0 || p2.distance_to(p3) == 0 || p2.distance_to(p4) == 0) {
                continue;
            }

            // do they intersect ?
            if (!intersects(p1, p2, p3, p4)) {
                continue;
            }

            // can modify less than 25 points ?
            if (std::abs(j-i) > 25) {
                continue;
            }

            // swap points
            for (int m = 0; m < std::abs(j-i)/2; ++m) {
                if (i+1+m != j-m) {
                    std::swap(points[i+1+m], points[j-m]);
                    //std::cerr << "untangle " << i+1+m << " <=> " << j-m << '\n';
                }
            }

            int new_distance = total_distance(points);
            if (new_distance < original_distance) {
                std::copy(std::begin(points), std::end(points)-1, std::ostream_iterator<Point>(std::cout, ","));
                std::cout << points[NPOINTS-1];
                return 0;
            }
            else {
                // swap points back
                for (int m = 0; m < std::abs(j-i)/2; m++) {
                    if (i+1+m != j-m) {
                        std::swap(points[i+1+m], points[j-m]);
                    }
                }
            }
        }
    }

    // more traditional approach if the first fails
    std::mt19937 rng(std::chrono::duration_cast<std::chrono::seconds>(start_time.time_since_epoch()).count());
    std::uniform_int_distribution<> distr(0, NPOINTS-1);
    while (true) {
        // try all possible swaps from a random permutation
        int p1 = distr(rng);
        int p2 = distr(rng);
        std::swap(points[p1], points[p2]);

        for (int i = 0; i < NPOINTS; ++i) {
            for (int j = i+1; j < NPOINTS; ++j) {
                std::swap(points[i], points[j]);
                if (total_distance(points) < original_distance) {
                    std::copy(std::begin(points), std::end(points)-1, std::ostream_iterator<Point>(std::cout, ","));
                    std::cout << points[NPOINTS-1];
                    return 0;
                }
                else {
                    std::swap(points[i], points[j]);
                }
            }
        }

        // they didn't yield a shorter path, swap the points back and try again
        std::swap(points[p1], points[p2]);
    }
    return 0;
}

```
> 8 votes

# Answer
### SANNbot

(a simulated annealing bot in **R**)

Should be called with `Rscript SANNbot.R`.

```
input <- strsplit(commandArgs(TRUE),split=",")[[1]]
n <- as.integer(input[1])                            # Number of players
init_s <- s <- matrix(as.integer(input[-1]),ncol=2,byrow=TRUE) # Sequence of points
totdist <- function(s){                              # Distance function
    d <- 0
    for(i in 1:99){d <- d + (abs(s[i,1]-s[i+1,1])+abs(s[i,2]-s[i+1,2]))}
    d
    }
gr <- function(s){                                   # Permutation function
    changepoints <- sample(1:100,size=2, replace=FALSE)
    tmp <- s[changepoints[1],]
    s[changepoints[1],] <- s[changepoints[2],]
    s[changepoints[2],] <- tmp
    s
    }
d <- init_d <- totdist(s)                            # Initial distance
k <- 1                                               # Number of iterations
v <- 0
t <- n*(init_d/12000)                                 # Temperature
repeat{
    si <- gr(s)                                      # New sequence
    di <- totdist(si)                                # New distance
    dd <- di - d                                     # Difference of distances
    if(dd <= 0 | runif(1) < exp(-dd/t)){             # Allow small uphill changes
        d <- di
        s <- si
        v <- v+2
        }
    k <- k+1
    if(k > 10000){break}
    if(d > init_d & v>20){s <- init_s; d <- init_d; v <- 0}
    if(v>23){break}
}
cat(paste(apply(s,1,paste,collapse=","),collapse=","))

```

The idea is relatively simple: each turn is one "cooling step" of a simulated annealing with the number of players still in the game as "temperature" (modified by the current distance over 12000, i.e. roughly the initial distance). Only difference with a proper simulated annealing is that I checked that i don't permute more than 25 elements and if i used up 20 moves but the resulting sequence is worth than the initial then it start over again.
> 4 votes

# Answer
# BozoBot

Utilizes the complex logic behind Bozosort to find a better path. It looks like this.

* Swap random points
* If we improved
    + Return the answer
* Otherwise
    + Try again

~~BozoBot has now been improved with **Multithreading**! Four minions now aimlessly juggle points until they stumble upon an improvement. The first one to find a solution gets a cookie!~~

Apparently I fail at multithreading.

```
import java.util.Random;
public class BozoBot {
    public static String[] input;
    public static void main(String[] args) {
        input = args;
        for(int i = 0; i < 4; i++) new Minion().run();
    }
}

class Minion implements Runnable {
    public static boolean completed = false;
    public static synchronized void output(int[] x, int[] y) {
        if(!completed) {
            completed = true;
            String result = x[0]+","+y[0];
            for (int i = 1; i < 100; i++)
                result+=","+x[i]+","+y[i];
            System.out.print(result);
            // receiveCookie(); // Commented out to save money
        }
    }
    public void run() {
        String[] args = BozoBot.input[0].split(",");
        int[] x = new int[100];
        int[] y = new int[100];
        for (int i = 1; i < 201; i+=2) {
            x[(i-1)/2] = Integer.parseInt(args[i]);
            y[i/2] = Integer.parseInt(args[i+1]);
        }
        int startDistance = 0;
        for (int i = 1; i < 100; i++)
            startDistance += Math.abs(x[i-1]-x[i]) + Math.abs(y[i-1]-y[i]);
        int r1, r2, r3, r4, tX, tY, newDistance;
        Random gen = new java.util.Random();
        while (true) {
            r1 = gen.nextInt(100);
            r2 = gen.nextInt(100);
            r3 = gen.nextInt(100);
            r4 = gen.nextInt(100);
            tX = x[r1];
            x[r1] = x[r2];
            x[r2] = tX;
            tY = y[r1];
            y[r1] = y[r2];
            y[r2] = tY;
            tX = x[r3];
            x[r3] = x[r4];
            x[r4] = tX;
            tY = y[r3];
            y[r3] = y[r4];
            y[r4] = tY;
            newDistance = 0;
            for (int i=1; i < 100; i++)
                newDistance += Math.abs(x[i-1]-x[i]) + Math.abs(y[i-1]-y[i]);
            if(newDistance < startDistance)
                break;
            tX = x[r1];
            x[r1] = x[r2];
            x[r2] = tX;
            tY = y[r1];
            y[r1] = y[r2];
            y[r2] = tY;
            tX = x[r3];
            x[r3] = x[r4];
            x[r4] = tX;
            tY = y[r3];
            y[r3] = y[r4];
            y[r4] = tY;
        }
        output(x,y);
    }
}

```
> 4 votes

# Answer
# TwoSwapBot

An upgrade to `SwapBot`, this guy checks for every pair of swaps. First, he checks if any single swap will shorten the path. If it does, it returns immediately. If not, he checks each to see if *another* swap will shorten it. If not, he just dies.

While the path is still semi-random, it normally returns in about 100ms. If he has to check each and every 2-swap (roughly 25M), it takes about 20 seconds.

At the time of submission, this beat all other competitors in test rounds.

```
public class TwoSwapBot {

    static int numPoints = 100;

    String run(String input){
        String[] tokens = input.split(",");
        if(tokens.length < numPoints*2)
            return "bad input? nope. no way. bye.";

        Point[] points = new Point[numPoints];
        for(int i=0;i<numPoints;i++)
            points[i] = new Point(Integer.valueOf(tokens[i*2+1]), Integer.valueOf(tokens[i*2+2]));
        int startDist = totalDistance(points);

        Point[][] swapped = new Point[(numPoints*(numPoints+1))/2][];
        int idx = 0;
        for(int i=0;i<numPoints;i++){
            for(int j=i+1;j<numPoints;j++){
                Point[] test = copyPoints(points);
                swapPoints(test,i,j);
                int testDist = totalDistance(test);
                if( testDist < startDist)
                    return getPathString(test);
                else
                    swapped[idx++] = test;
            }
        }

        for(int i=0;i<idx;i++){
            for(int k=0;k<numPoints;k++){
                for(int l=k+1;l<numPoints;l++){
                    swapPoints(swapped[i],k,l);
                    if(totalDistance(swapped[i]) < startDist)
                        return getPathString(swapped[i]);
                    swapPoints(swapped[i],k,l);
                }
            }
        }
        return "well damn";
    }

    void swapPoints(Point[] in, int a, int b){
        Point tmp = in[a];
        in[a] = in[b];
        in[b] = tmp;
    }

    String getPathString(Point[] in){
        String path = "";
        for(int i=0;i<numPoints;i++)
            path += in[i].x + "," + in[i].y + ",";
        return path.substring(0,path.length()-1);
    }

    Point[] copyPoints(Point[] in){
        Point[] out = new Point[in.length];
        for(int i=0;i<out.length;i++)
            out[i] = new Point(in[i].x, in[i].y);
        return out;
    }

    static int totalDistance(Point[] in){
        int dist = 0;
        for(int i=0;i<numPoints-1;i++)
            dist += in[i].distance(in[i+1]);
        return dist + in[numPoints-1].distance(in[0]);
    }

    public static void main(String[] args) {
        if(args.length < 1)
            return;
        System.out.print(new TwoSwapBot().run(args[0]));
    }

    class Point{
        final int x; final int y;
        Point(int x, int y){this.x = x; this.y = y;}
        int distance(Point other){return Math.abs(x-other.x) + Math.abs(y-other.y);}
    }
}

```
> 3 votes

# Answer
# Threader

This bot

1. Splits the 100 points up in ~~4~~**10** pieces of ~~25~~**10** points
2. Starts a thread for each piece
3. In the thread, randomly shuffle the array, while keeping the start- and endpoint fixed
4. If distance of new array is shorter, keep it
5. After 59s, the main thread collects the results and prints it out

The idea is to find the best improvement to the path, so that the other bots will fail with their logic.

```
import java.util.Arrays;
import java.util.Collections;

public class Threader {
    public static final int THREAD_COUNT = 10;
    public static final int DOT_COUNT = 100;
    private final Dot[] startDots = new Dot[THREAD_COUNT];
    private final Dot[] endDots = new Dot[THREAD_COUNT];
    private final Dot[][] middleDots = new Dot[THREAD_COUNT][DOT_COUNT/THREAD_COUNT-2];
    private final Worker worker[] = new Worker[THREAD_COUNT];
    private final static long TIME = 59000;

    public static void main(String[] args) {
        Threader threader = new Threader();
        //remove unnecessary player count to make calculation easier
        threader.letWorkersWork(args[0].replaceFirst("^[0-9]{1,3},", "").split(","));
    }

    public void letWorkersWork(String[] args) {
        readArgs(args);
        startWorkers();
        waitForWorkers();
        printOutput();
    }

    private void readArgs(String[] args) {
        final int magigNumber = DOT_COUNT*2/THREAD_COUNT;
        for (int i = 0; i < args.length; i += 2) {
            Dot dot = new Dot(Integer.parseInt(args[i]), Integer.parseInt(args[i + 1]));
            if (i % magigNumber == 0) {
                startDots[i / magigNumber] = dot;
            } else if (i % magigNumber == magigNumber - 2) {
                endDots[i / magigNumber] = dot;
            } else {
                middleDots[i / magigNumber][(i % magigNumber) / 2 - 1] = dot;
            }
        }
    }

    private void startWorkers() {
        for (int i = 0; i < THREAD_COUNT; i++) {
            worker[i] = new Worker(startDots[i], endDots[i], middleDots[i]);
            Thread thread = new Thread(worker[i]);
            thread.setDaemon(true);
            thread.start();
        }
    }

    private void waitForWorkers() {
        try {
            Thread.sleep(TIME);
        } catch (InterruptedException e) {
        }
    }

    private void printOutput() {
        //get results
        Worker.stopWriting = true;
        int workerOfTheYear = 0;
        int bestDiff = 0;
        for (int i = 0; i < THREAD_COUNT; i++) {
            if (worker[i].diff() > bestDiff) {
                bestDiff = worker[i].diff();
                workerOfTheYear = i;
            }
        }
        //build output
        StringBuilder result = new StringBuilder(1000);
        for (int i = 0; i < THREAD_COUNT; i++) {
            result.append(startDots[i]);
            Dot middle[] = middleDots[i];
            if (i == workerOfTheYear) {
                middle = worker[i].bestMiddle;
            }
            for (int j = 0; j < middle.length; j++) {
                result.append(middle[j]);
            }
            result.append(endDots[i]);
        }
        result.replace(0, 1, ""); //replace first comma
        System.out.print(result);
    }

}

class Worker implements Runnable {

    public Dot start;
    public Dot end;
    private Dot[] middle = new Dot[Threader.DOT_COUNT/Threader.THREAD_COUNT-2];
    public Dot[] bestMiddle = new Dot[Threader.DOT_COUNT/Threader.THREAD_COUNT-2];
    public static boolean stopWriting = false;
    private int bestDist = Integer.MAX_VALUE;
    private final int startDist;

    public Worker(Dot start, Dot end, Dot[] middle) {
        this.start = start;
        this.end = end;
        System.arraycopy(middle, 0, this.middle, 0, middle.length);
        System.arraycopy(middle, 0, this.bestMiddle, 0, middle.length);
        startDist = Dot.totalDist(start, middle, end);
    }

    @Override
    public void run() {
        while (true) {
            shuffleArray(middle);
            int newDist = Dot.totalDist(start, middle, end);
            if (!stopWriting && newDist < bestDist) {
                System.arraycopy(middle, 0, bestMiddle, 0, middle.length);
                bestDist = newDist;
            }
        }
    }

    public int diff() {
        return startDist - bestDist;
    }

    private void shuffleArray(Dot[] ar) {
        Collections.shuffle(Arrays.asList(ar));
    }

}

class Dot {

    public final int x;
    public final int y;

    public Dot(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int distTo(Dot other) {
        return Math.abs(x - other.x) + Math.abs(y - other.y);
    }

    public static int totalDist(Dot start, Dot[] dots, Dot end) {
        int distance = end.distTo(start);
        distance += start.distTo(dots[0]);
        distance += end.distTo(dots[dots.length - 1]);
        for (int i = 1; i < dots.length; i++) {
            distance += dots[i].distTo(dots[i - 1]);
        }
        return distance;
    }

    @Override
    public String toString() {
        return "," + x + "," + y;
    }
}

```
> 2 votes

# Answer
# Divide And Conquer + Greedy Bot

**NOTE:** I looked at your code for `Game` which includes the following in Game.parsePath:

```
for(int i=0;i<numPoints;i++){
        test[i] = new Point(Integer.valueOf(tokens[i*2]), Integer.valueOf(tokens[i*2+1]));
        if(test[i].equals(currentPath[i]))
            same++;

```

However, there is no `catch(NumberFormatException)` block, so your program will likely crash when a player program outputs a string (as demonstrated at the end of my program's `main` method). I advise you fix this, because programs could output exceptions, stack traces, or the like. Otherwise, comment out that line in my program before you run it.

## Back to the topic

This implementation (in Java) splits the list of points into chunks of 25, randomly spaced on the list. Then, it creates threads to shorten the path between the points in each chunk (Hence, "Divide and Conquer"). The main thread monitors the others and makes sure to present the shortest solution within the time limit. If a thread dies with or without a solution, it starts another thread off again on a different chunk.

Each thread uses the "greedy" algorithm, which starts off on a random point, goes to the closest point, and repeats until all the points are covered (Hence, "greedy").

### Notes

* This will run through the full 1 minute (I gave 3 seconds for program startup/shutdown and JVM startup - you never know what the JVM startup routines get caught up on next...)
* Even if it has found solutions, it will keep searching and after the 1 minute is up it presents the best solution it found.
* I'm not sure if this implementation is actually any good. I had some fun coding it though :)
* Since a lot of things are random, this may not give the same output for the same input.

Just compile and use `java DivideAndConquer.class` to run.

```
public class DivideAndConquer extends Thread {
    static LinkedList<Point> original;
    static Solution best;
    static LinkedList<DivideAndConquer> bots;
    static final Object _lock=new Object();

    public static void main(String[] args){
        if(args.length != 1) {
            System.err.println("Bad input!");
            System.exit(-1);
        }
        // make sure we don't sleep too long... get the start time
        long startTime = System.currentTimeMillis();
        // parse input
        String[] input=args[0].split(",");
        int numPlayers=Integer.parseInt(input[0]);
        original=new LinkedList<Point>();
        for(int i=1;i<input.length;i+=2){
            original.add(new Point(Integer.parseInt(input[i]), Integer.parseInt(input[i+1])));
        }
        // start threads
        bots=new LinkedList<DivideAndConquer>();
        for(int i=0;i<6;i++)
            bots.add(new DivideAndConquer(i));
        // sleep
        try {
            Thread.sleep(57000 - (System.currentTimeMillis() - startTime));
        } catch(Exception e){} // should never happen, so ignore
        // time to collect the results!
        Solution best=getBestSolution();
        if(best!=null){
            best.apply(original);
            String printStr="";
            for(int i=0;i<original.size();i++){
                Point printPoint=original.get(i);
                printStr+=printPoint.x+","+printPoint.y+",";
            }
            printStr=printStr.substring(0, printStr.length()-1);
            System.out.print(printStr);
        } else {
            System.out.println("Hey, I wonder if the tournament program crashes on NumberFormatExceptions... Anyway, we failed");
        }
    }

    // check the distance
    public static int calculateDistance(List<Point> points){
        int distance = 0;
        for(int i=0;i<points.size();i++){
            int next=i+1;
            if(next>=points.size())next=0;
            distance+=points.get(i).distance(points.get(next));
        }
        return distance;
    }

    public static void solutionFound(Solution s){
        // thanks to Java for having thread safety features built in
        synchronized(_lock){
            // thanks to Java again for short-circuit evaluation
            // saves lazy programmers lines of code all the time
            if(best==null || best.distDifference < s.distDifference){
                best=s;
            }
        }
    }

    public static Solution getBestSolution(){
        // make sure we don't accidentally return
        // the best Solution before it's even
        // done constructing
        synchronized(_lock){
            return best;
        }
    }

    List<Point> myPoints;
    int start;
    int length;
    int id;

    public DivideAndConquer(int id){
        super("DivideAndConquer-Processor-"+(id));
        this.id=id;
        myPoints=new LinkedList<Point>();
        start=(int) (Math.random()*75);
        length=25;
        for(int i=start;i<start+length;i++){
            myPoints.add(original.get(i));
        }
        start();
    }

    public void run(){
        // copy yet again so we can delete from it
        List<Point> copied=new LinkedList<Point>(myPoints);
        int originalDistance=calculateDistance(copied);
        // this is our solution list
        List<Point> solution=new LinkedList<Point>();
        int randomIdx=new Random().nextInt(copied.size());
        Point prev=copied.get(randomIdx);
        copied.remove(randomIdx);
        solution.add(prev);
        while(copied.size()>0){
           int idx=-1;
           int len = -1;
           for(int i=0;i<copied.size();i++){
               Point currentPoint=copied.get(i);
               int dist=prev.distance(currentPoint);
               if(len==-1 || dist<len){
                   len=dist;
                   idx=i;
               }
           }
           prev=copied.get(idx);
           copied.remove(idx);
           solution.add(prev);
        }
        // aaaand check our distance
        int finalDistance=calculateDistance(solution);
        if(finalDistance<originalDistance){
            // yes! solution
            Solution aSolution=new Solution(start, length, solution, originalDistance-finalDistance);
            solutionFound(aSolution);
        }
        // start over regardless
        bots.set(id, new DivideAndConquer(id));
    }

    // represents a solution
    static class Solution {
        int start;
        int length;
        int distDifference;
        List<Point> region;
        public Solution(int start, int length, List<Point> region, int distDifference){
            this.region=new LinkedList<Point>(region);
            this.start=start;
            this.length=length;
            this.distDifference=distDifference;
        }
        public void apply(List<Point> points){
            for(int i=0;i<length;i++){
                points.set(i+start, region.get(i));
            }
        }
    }

    // copied your Point class, sorry but it's useful...
    // just added public to each method for aesthetics
    static class Point{
        int x;
        int y;
        Point(int x, int y){
            this.x = x;
            this.y = y;
        }
        Point(Point other){
            this.x = other.x;
            this.y = other.y;
        }
        public boolean equals(Point other){
            if(this.x==other.x && this.y==other.y)
                return true;
            return false;
        }

        public int distance(Point other){
            return Math.abs(x-other.x) + Math.abs(y-other.y);
        }
    }
}

```
> 1 votes

---
Tags: king-of-the-hill
---


# Question
Title: Write a program that can that can write a program, in the shortest code possible!
As stated, write a program that is capable to, in an automated manner, write more code and another program and execute that program from itself.

In short, you are asked to write a program that can write another self-standing program itself and enable it to execute in any function.

Do this in the shortest amount of code possible, with the one restriction being that it has to be written in one of these languages.

If you need even more specific details, read on:

> You are asked to write a program that will (in an automated manner) write the lines of code needed for another program, and compile that program/execute it from the programmatic structure of the main program itself. The program is not executing the program, but is programmed to write code and then compile/get the OS to execute it while it's still running separately.

# Answer
# C: ~~41~~ 38 characters

Pretty much the most trivial solution possible in C.

```
main(){system("gcc -xc -<<<'main;'");}

```
> 2 votes

---
Tags: code-golf
---