# Question
Title: The Essential™ (comment-free) Convenient Palindromic Quine Golf
A program is *"conveniently palindromic"* if

> it is equal to the string derived when its reverse has all its parentheses (`()`), brackets (`[]`), and braces (`{}`) flipped. No other characters are special and require flipping. (`<>` are sometimes paired but often not so they are left out.)
>
> copied from this challenge.

Write a conveniently palindromic program that prints its own source.

You must be able to prove that it is impossible to remove one or more byte from the program so that the resulting program, when executed in the same language:

* prints the original source, or
* prints the new modified source

Note that the resulting program won't necessarily be a convenient palindrome. It also means that you cannot use comments or equivalent structures.

## Rules

* Program must be longer than one character
* Reading you own source code (from the file or any other resource) is forbidden.
* Your program must be a proper quine.

# Answer
> 7 votes
# Jelly, 17 bytes

```
ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð

```

Try it online!

### Verfication

A string of length **17** has only **217 = 131,072** subsequences, so this can be done by brute force.

```
$ # Generate all 131,072 subsequences of the source code.
$ jelly eun '“ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð”ṾḊṖŒPY' > subsequences
$ wc -l subsequences
131072 subsequences
$ cat verify.py
import jelly

# Discard extraneous output to STDOUT (just a bunch of 0's and [0]'s).

jelly.print = lambda _, end: None

for line in open('subsequences').readlines():
        line = line.strip()
        try:
                output = jelly.stringify(jelly.jelly_eval(line, []))
        except:
                output = ''
        if output == line or output == 'ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð':
                print(repr(line))

$ time python3 verify.py
'ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð'

real    0m9.678s
user    0m9.653s
sys     0m0.028s

```

### How it works

```
ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð  Main link. No arguments. Implicit left argument: 0

       ø           Make the chain to the right niladic.
        “øḄŒṚṖṾṛð  Yield the string 'øḄŒṚṖṾṛð'.
ð                  Make the chain to the right and up to ø dyadic.
                   The main link is now a monadic 2,0-chain, so the dyadic chain
                   is called with the implicit left argument 0 and right argument
                   'øḄŒṚṖṾṛð'.
 ṛ                 Yield the right argument, i.e., 'øḄŒṚṖṾṛð'.
  Ṿ                Uneval; yield the string representation of the right argument,
                   i.e., '“øḄŒṚṖṾṛð”'.
   Ṗ               Pop; remove the last character, yielding '“øḄŒṚṖṾṛð'.
    Ṛ              Reverse, yielding 'ðṛṾṖṚŒḄø“'.
     ŒḄ            Bounce, yielding 'ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð'.
                   (implicit) Print the last return value.

```

# Answer
> 5 votes
# , 12 bytes

The program is in binary. Here's an `xxd` dump:

```
00000000: 47b6 1818 b647 47b6 1818 b647            G....GG....G

```

This is rather more readable in the alternative octal notation (which isn't a valid answer to the question because changing the encoding changes the boundaries between bits):

```
2173303006133107217330300613310

```

Try it online!

Here's how the octal encoding of one half of the program corresponds to the packed encoding. (The other half is identical, except that it doesn't have a trailing `7` command because trailing `1` bits are treated like trailing whitespace, and ignored.) This is the form in which I actually worked on the problem, because trying to ensure that a program makes sense when viewed as three-bit chunks, but is palindromic when viewed as eight-bit chunks, is really unintuitive.

```
 2  1  7  3  3  0  3  0  0  6  1  3  3  1  0  7
...'''...'''...'''...'''...'''...'''...'''...'''
010001111011011000011000000110001011011001000111
........''''''''........''''''''........''''''''
   47      b6      18      18      b6      47

```

Like most golfed 7 quines, this program consists of two halves, each of which prints the other. Each half is originally passive on the stack, but an active copy is made and executed when the program runs out of commands to run, in reverse order from right to left. Here's how the active copy works (I'm using the escaped representation here because the unescaped representation contains some commands that don't have names, and thus are hard to talk about):

```
2          Copy the top of the stack
173303006  Push "330300" onto the stack
13         Pop the top of the stack
3          Output the copy of the top of the stack, and discard the original
10         Append nothing to the top of stack

```

In other words, each half of the program prints itself (because it's still at the top of the stack; the original wasn't removed when the copy was made), and then throws itself away. So this is effectively just the standard 7 quine `23723` written in a particularly verbose way, to make it palindromic at the byte level.

There's quite a lot of junk code here that doesn't do anything useful, and it could easily be deleted if deletions were at the command level. (As a result, I suspect this can be golfed substantially smaller, but I can't see how.) This might seem to violate the specification; however, the problem defines comment-freedom via deletion at the *byte* level (which makes about as little sense for 7 as requiring the program to be a palindrome at the byte level does), and doing that will typically throw off the boundaries between commands, making the program quite different. The rest of this post, therefore, talks about how I ensured that no deletions could lead to a proper quine.

## Verification

I used the following Perl program to find all 7 quines, and all 7 programs printing the original program, that could be produced via deleting from the existing code (plus the original code itself, as it was easier to disregard that by hand than to write code to ignore it):

```
use 5.010;
use IPC::Run qw/run timeout/;
undef $/;
$| = 1;

my %seen = ();
my $original = <>;
sub check_program {
    my $unprocessed = shift;
    my $processed = shift;
    if ($unprocessed eq '') {
        my ($out, $err);
        $seen{$processed} and return;
        $seen{$processed}++;
        my $binary = unpack "B*", $processed;
        $binary =~ s/1+$//;
        $binary .= 1 while (length $binary) % 3;
        my $program = "";
        $program .= oct "0b$&" while $binary =~ s/^...//;
        print "$program          \r";
        my $ok = "t";
        eval {
            $ok = run [$^X, '7.pl'], '<', \$processed, '>', \$out, '2>', \$err, timeout(1);
            $ok = $ok ? "x" : "e";
        };
        if ($out eq $processed || $out eq $original) {
            $out eq $original and $ok .= "o";
            print "$program $ok\n";
        }
    } else {
        $unprocessed =~ s/^.//;
        check_program($unprocessed, $&.$processed);
        check_program($unprocessed, $processed);
    }
}

check_program($original, "");

```

The program produces quite a bit of output, because there are a number of 7 quines that can be produced like this. However, none are *proper* quines. They fall into three groups, listed here in octal to make it easier to verify that they aren't proper quines:

### Programs which print themselves plus `21`, but crash before it can be output

```
2161403021733030061
2161403055414030555
2161403055414030
2161403055443430555
2161403055443430
2161403055443507061
2161403055533030555
2161403055533030
21614030555
21614030

```

These programs each consist of the escaped representation of a single stack element that starts `721614030`. (Where did the initial `7` come from? Each program starts with two empty elements on the stack, which is equivalent to two implicit `7`s.) When it gets unescaped at runtime, its behaviour breaks down like this:

```
7216    Append "21" to the top of stack
14      Push two empty stack elements beneath the top of stack
0       Escape the top of stack, then append it to the element beneath
3       Output the top of stack, delete the second stack element
0       Crash due to insufficient stack

```

Now, when producing the first output in 7, you have to specify an output format. If the output is in need of escaping, that automatically escapes it and prepends a 7, and the first character output (in this case a 7) selects the format; most 7 quines rely on this. These programs, however, do the escaping manually, meaning that there's no implicitly prepended 7. Rather, the 7 at the start of the escaped representation (`72161403021`, etc.) ends up selecting the format, so it doesn't get escaped explicitly. In other words, the program prints itself plus an appended `21`, then crashes.

The problem, of course, is that we're using packed, not octal, representation, so `21` is only six bits long, i.e. not a byte. As such, it can't (with programs of the lengths shown here) be output immediately, because more bits are needed to determine which byte to output. The `21` would be padded up to a full byte with 1 bits if the program exited normally, but it never gets a chance; it crashes before anything more can be output. When the crash occurs, the interpreter just exits immediately, and never gets the chance to print the incomplete byte.

Of course, this is an improper quine because all the output that's actually produced was produced via literally printing the corresponding characters of the original program.

### Programs that print themself literally

**Programs that crash:**

```
2173303006133107061
217330300613310721614030555
217330300613310721614030

```

**Programs that exit normally:**

```
2173303006133030555
2173303006133030
2173303006133107061333
217330300613310
21733030061333
21733030554434300613310
2173303055443430061333
21733030555330300613310
2173303055533030061333

```

These all follow the same basic principle as the original program, but only have one stack element (either because the `7` that would normally separate stack elements got deleted, or because it's matched by a `6` later in the program, combining the element into one large element). The stack element prints itself literally first, for the same reason that the two elements in the original program each print the other, and then runs some random commands that don't produce output. Because the entire program is basically just a literal that prints itself, this doesn't count as a proper quine

### The null quine

Yes, the null program is a quine in 7, and yes, you can produce it via deleting from the original program. This clearly isn't a proper quine, though.

# Answer
> 2 votes
# RProgN, 3 Bytes.

```
1
1

```

Good luck out golfing this one.

This is a valid quine, as each `1` prints the opposite `1`, which can be proven by the code

```
1
2

```

which prints

```
2
1

```

As for removing characters, `11` prints `11`, although is not a valid quine, as it's a constant. The other options, `1_` and `_1` (where _ is a newline) are also not valid, as they are only constants, and they are missing the white space.

Try it online!

# Answer
> 2 votes
# Befunge-98, 55 or 57 bytes

```
<#0289+*00#p>$$$>:#,_652**,@,**256_,#:>$$$>p#00*+9820#<

```

Try it online!

This solution is dependent on the behaviour of wraparound strings. Most Befunge-98 implementations will push a space onto the stack whenever a string wraps across the edge of the playfield, while the FBBI interpreter (which is what is used by TIO) will not. If you want to test this on other interpreters, you'll most likely need to include an additional `$` (drop) command to get rid of that extra space:

```
<#0289+*00#p>$$$$>:#,_652**,@,**256_,#:>$$$$>p#00*+9820#<

```

In theory it should be possible to make a more portable solution that would work on all interpreters (possibly even Befunge-93), but that would require a good deal more code.

**Proof of validity**

While there are characters in the code that aren't actually executed, they are all used in the construction of the output, and removing any of those characters will result in output that neither matches the original source or the modified source. This is because the output string is built up in reverse, and it is thus imperative that the source be palindromic for the output to match. If you can remove a character and still have it work, you'll just have created a better solution.

**Explanation**

```
<                  Reverse the direction of execution, wrapping to the end of the line.
           0#<     Jump over the zero.
      *+982        Push 34 (a double quote character) onto the stack.
    00             Push two zeros - the coordinates of the first character in the source.
 >p#               Turn around and 'put' the double quote into the source at 0,0.
    00*+982        In reverse, this just pushes some numbers that will be ignored.
           0       This zero will serve as the string terminator though.
            #<     Jump over the left arrow so we can wrap around back to the start.

"#0289+*00...      At this point the first character has been updated to a quote, so
                     we're now going to switch to string mode and push the entire source
                     onto the stack in reverse order. When the end of the line is reached,
                     the string will wrap around to the start and terminate when it
                     encounters the quote again.

#0289+*00#p        Again we've got a sequence pushing values that we don't actually want.
           >$$$    This time we need to get rid of them, with a few drop operations.

>:#,_              A standard output routine, writing out the source from the stack.
     652**,        The last '<' character has to be output manually though.
           @       Then finally we can exit.

```

---
Tags: code-golf, restricted-source, quine, palindrome
---


title: Get a word's individuality!

text:
# Question
Title: Get a word's individuality!
I love `/usr/share/dict/words`; it's so handy! I use it for all my programs, whenever I can! You're going to take advantage of this ever so useful file to use, by testing a word's individuality.

---

**Input**

* A word; defined in this challenge as any string of characters
* `/usr/share/dict/words` in some format; you may hard code it, read from disk, assume it as a second argument, whatever makes the most sense in your challenge

**Output**

* A words individuality (see below)

A word's individuality is derived from the following equation:

```
<the number of words for which it is a substring> / <length of the word>

```

Let's take a look at an example: `hello`. There are 12 words which have the substring `hello` in them, divided by `5` (hello's length), and hello's individuality is `12/5` or `2.4`

---

P.S. This is , so the lower the individuality score, the more individual

Because individuality is a long word, your program must be as short as possible

Good Luck!

---

**Test Cases**

You can use this convenient Node.js script, which fits the challenge requirements to fit your code. It is also how I generated the test cases:

```
var fs = require("fs");
var word = process.argv[2];

process.stdout.write("Reading file...")
fs.readFile("/usr/share/dict/words", function(err, contents) {
  console.log("Done")
  if (err) throw err;

  words = contents.toString().split("\n");

  var substrings = words.filter(w => w.indexOf(word) > -1).length;
  var length     = word.length;

  console.log(`${word} => ${substrings} / ${length} = ${substrings / length}`)
})

```

Test Cases:

```
hello => 12 / 5 = 2.4
individuality => 1 / 13 = 0.07692307692307693
redic => 52 / 5 = 10.4
ulous => 200 / 5 = 40
challen => 15 / 7 = 2.142857142857143
ges => 293 / 3 = 97.66666666666667
hidden => 9 / 6 = 1.5
words => 12 / 5 = 2.4
aside => 8 / 5 = 1.6

```

# Answer
> 1 votes
# 05AB1E, 9 bytes

```
#vy²å}ON/

```

Try it online!

```
#         Separate by newlines or spaces.
 vy       For each entry in the dictionary.
   ²å     1 if the second argument is a substring of the current word, 0 o.w.
     }    End loop.
      O   Sum ones and zeros.
       N  Get list size.
        / Divide.

```

# Answer
> 3 votes
# Bash, ~~41~~, ~~39~~, ~~34~~, ~~33~~, 26 bytes

EDIT:

* Converted from function to a script
* One byte off by removing the *ignore case* flag
* Replaced *wc -l* with *grep -c*, saving 5 bytes. Thanks @Riley !

A rather trivial solution in *bash* \+ *coreutils*

**Golfed**

```
bc -l<<<`grep -c $1`/${#1}

```

**Test**

```
>cat /usr/share/dict/words| ./test ulous
7.60000000000000000000

>grep -i ulous /usr/share/dict/words | wc -l
38

```

# Answer
> 2 votes
# Python 3, ~~52~~ 49 bytes

-3 bytes thanks to Kade, for assuming `w` to be the word list as list:

```
f=lambda s,w:w>[]and(s in w[0])/len(s)+f(s,w[1:])

```

Previous solution:

```
lambda s,w:sum(s in x for x in w.split('\n'))/len(s)

```

Assumes `w` to be the word list. I choose Python 3 because in my word list there are some Non-ASCII chars and Python 2 does not like them.

# Answer
> 2 votes
# Perl 6,  ~~45 36 33~~  32 bytes

wordlist as a filename `f`, **45 bytes**

```
->$w,\f{grep({/:i"$w"/},f.IO.words)/$w.chars}

```

wordlist as a list `l`, **36 bytes**

```
->$w,\l{grep({/:i"$w"/},l)/$w.chars}

```

using placeholder variables, and reverse (`R`) meta-operator, **33 bytes**

```
{$^w.chars R/grep {/:i"$w"/},$^z}

```

using `.comb` to get a list of characters, rather than `.chars` to get a count, **32 bytes**

```
{$^w.comb R/grep {/:i"$w"/},$^z}

```

## Expanded:

```
{             # block lambda with placeholder parameters ｢$w｣ ｢$z｣

  $^w         # declare first parameter ( word to search for )
  .comb       # list of characters ( turns into count in numeric context )

  R[/]        # division operator with parameters reversed

  grep        # list the values that match ( turns into count in numeric context )

    {         # lambda with implicit parameter ｢$_｣
      /       # match against ｢$_｣
        :i    # ignorecase
        "$w"  # the word as a simple string
      /
    },

    $^z       # declare the wordlist to search through
              #( using a later letter in the alphabet
              #  so it is the second argument )
}

```

# Answer
> 1 votes
## awk: 31 bytes

Passing the word as the `w` variable to the `awk` command, and the file in `<stdin>`:

```
$0~w{N++}END{print N/length(w)}

```

Sample output:

```
 $ awk -vw=hello '$0~w{N++}END{print N/length(w)}' /usr/share/dict/words
 2.4

```

# Answer
> 1 votes
# PHP, 54 bytes

Assumes the word list in `$w`.

```
<?=count(preg_grep("/$argv[1]/",$w))/strlen($argv[1]);

```

# Answer
> 0 votes
## Clojure, 53 bytes

Not that exciting :/

```
#(/(count(filter(fn[w](.contains w %))W))(count %)1.)

```

That `1.` is there to convert a rational into a float. I pre-loaded words into `W` as such:

```
(def W (map clojure.string/lower-case (clojure.string/split (slurp "/usr/share/dict/words") #"\n")))

```

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


title: Die Hard 3 Water Jugs Problem

text:
# Question
Title: Die Hard 3 Water Jugs Problem
# Introduction

The well-known "Die Hard with a Vengeance" water jugs puzzle challenges the two heroes to get 4L of water in a 5L container, provided an unlimited supply of water and another container of 3L. This problem has a solution because `4` is less or equal than the largest container and is a multiple of the `gcd(5, 3) = 1` as per number theory. The same goes for other combinations of container sizes as long as the Greatest Common Divisor (GCD) requirements are satisfied for a target value.

# Task

In one sentence, the task is to brute-force **two solutions** by filling and emptying two containers as well as transferring amounts between one another for any given container sizes and target value. The brute-force lies on repeatedly transferring amounts from one container to another, refilling the first when it runs out and emptying the second when it fills up, until any of them contain the target value.

The program should make two runs to respectively find two solutions by swapping container positions (*i.e.*, the container receiving water from the other swaps with that one). The container states should be printed throughout all steps (refilling or emptying and transferring water).

This is code golf, so lowest byte count wins.

# Examples

Examples follow below for `(5, 3, 4)` and `(17, 5, 7)` with `4` and `7` being the target values. Comments added for description purposes.

```
5 3 4
[5, 0] # initial state
[2, 3] # transferring
[2, 0] # emptying
[0, 2] # transferring
[5, 2] # refilling
[4, 3] # transferring, solution found
3 5 4
[3, 0]
[0, 3]
[3, 3]
[1, 5]
[1, 0]
[0, 1]
[3, 1]
[0, 4]

17 5 7
[17, 0] # initial state
[12, 5] # transferring
[12, 0] # emptying
[7, 5]  # transferring, solution found
5 17 7
[5, 0]
[0, 5]
[5, 5]
[0, 10]
[5, 10]
[0, 15]
[5, 15]
[3, 17]
[3, 0]
[0, 3]
[5, 3]
[0, 8]
[5, 8]
[0, 13]
[5, 13]
[1, 17]
[1, 0]
[0, 1]
[5, 1]
[0, 6]
[5, 6]
[0, 11]
[5, 11]
[0, 16]
[5, 16]
[4, 17]
[4, 0]
[0, 4]
[5, 4]
[0, 9]
[5, 9]
[0, 14]
[5, 14]
[2, 17]
[2, 0]
[0, 2]
[5, 2]
[0, 7]

```

# Answer
> 2 votes
## Batch, 218 bytes

```
@echo off
set/al=r=0
:l
echo %l% %r%
set/at=r+l
if %l% neq %3 if %r% neq %3 ((if %r%==%2 (set r=0)else if %l%==0 (set l=%1)else if %t% leq %2 (set/ar=t,l=0)else set/ar=%2,l=t-%2)&goto l)
if "%4"=="" %0 %2 %1 %3 .

```

Putting everything into one big `if` statement saves 11 bytes. `%4` is just used to make the file loop twice with the arguments exchanged.

# Answer
> 2 votes
# Python 2 - ~~222/384~~, ~~190~~ 174/~~360 352~~ 336 Bytes

This version that only outputs the solution is **174 bytes**.

```
a,b,c=input()
d,e=0,0
for i in range(2):
 while d!=c and e!=c:
   if e<b:
     if d>0:
       if e+d<=b:e+=d;d=0
       else:n=d+e-b;e=b;d=n
     else:d=a
   else:e=0
 print d,e
 b,a,d,e=a,b,0,0

```

Try it here!

**Example Output:**

**Explanation:**

```
a,b,c=input()                      # Value of jug 1, jug 2, target value
d,e=0,0                            # Water held in each jug
for i in range(2):                 # Loop twice
  while d!=c and e!=c:             # While no solution
    if e<b:                        # If jug 2 can hold more water
      if d!=0:                     # If jug 1 has water
        if e+d<=b:e+=d;d=0         # If no overfill, pour all of jug 1 into 2
        else:n=d+e-b;e=b;d=n       # Else fill up as much as possible
      else:d=a                     # Else jug 1 has no water, fill it
    else:e=0                       # Else jug 2 is full, empty it
  print d,e                        # Print solution
  b,a,d,e=a,b,0,0                  # Switch the two jugs' values, empty all jugs

```

It implements this algorithm. With the new edit, the code becomes **326 bytes**:

```
a,b,c=input(),input(),input()
d,e=0,0
g=[d,e]
for i in"xx":
 while d!=c and e!=c:
   g=[d,e]
   if e<b:
     if d!=0:
       if e+d<=b:e+=d;d=0;print"Transferring Water"
       else:n=d+e-b;e=b;d=n;print"Transferring Water"
     else:d=a;print"Filling Water"
   else:e=0;print"Emptying Water"
   print g
 print[d,e],"Solution Found"
 b,a,d,e=a,b,0,0;print"Resetting"

```

Try this version here

**Explanation and Output**

Explanation is the same except with text and `g` is used to output the values of the two jugs and final solution. Output:

---
Tags: code-golf
---


# Question
Title: Generate the python dictionary of phone keypresses for any letter
In the fewest bytes, generate the dictionary of keypresses for any letter (as described in https://code.google.com/codejam/contest/351101/dashboard#s=p2)

In Python, the dictionary literal itself:

```
{'a':2,'c':222,'b':22,'e':33,'d':3,'g':4,'f':333,'i':444,'h':44,'k':55,'j':5,'m':6,'l':555,'o':666,'n':66,'q':77,'p':7,'s':7777,'r':777,'u':88,'t':8,'w':9,'v':888,'y':999,'x':99,'z':9999}

```

is 187 bytes so it needs to be less than that. (The values can be strings or ints, ie you can have 'a':'2' or 'a':2 it's up to you)

NOTE: This is not asking you to solve the referenced GCJ problem, it's just asking you to generate a particular dictionary which is related to that problem.

EDIT: You may solve this in any language which has a dictionary-like type (ie hashmap, associative array etc.)

# Answer
> 6 votes
# perl, 49 48 bytes

Using a different algorithm than my previous answer, we can lose another 12 bytes. The basic idea is that you usually just add the digit from the last letter's solution over again. We handle the other cases (detected by a short regex) by starting with a single instance of the last digit + 1.

```
{map{$d++,$t=""if/[dgjmptw]/;$_,$t.=$d||=2}a..z}

```

With output:

```
ski@anito:~/src$ perl -MData::Dumper  -e '$Data::Dumper::Sortkeys=1; $d=2;print Dumper {map{$d++,$t=""if/[dgjmptw]/;$_,$t.=$d}a..z}'
$VAR1 = {
      'a' => '2',
      'b' => '22',
      'c' => '222',
      'd' => '3',
      'e' => '33',
      'f' => '333',
      'g' => '4',
      'h' => '44',
      'i' => '444',
      'j' => '5',
      'k' => '55',
      'l' => '555',
      'm' => '6',
      'n' => '66',
      'o' => '666',
      'p' => '7',
      'q' => '77',
      'r' => '777',
      's' => '7777',
      't' => '8',
      'u' => '88',
      'v' => '888',
      'w' => '9',
      'x' => '99',
      'y' => '999',
      'z' => '9999'
};

```

# Answer
> 3 votes
# Python (83)(87)

```
c,d=97,{}
for i in range(2,10):
 for j in range(1,4+(i>6)*i%2):d[chr(c)],c=j*str(i),c+1

```

The dictionary is stored in `d`. The condition check `(i>6)*i%2` saves two chars from `(i in[7,9])`.

## Edit:

```
c=97;d={}
for i in range(8):
 for j in range(1,4+(i|2>6)):d[chr(c)]=j*str(i+2);c+=1

```

Shaved 4 characters. With `i` shifted down by 2, we recognize the special cases of 7 and 9 by checking if `i` is 5 or 7 using `i|2>6`.

# Answer
> 3 votes
# Golfscript, 68 characters

```
"{'"26,{.[.",'"''if\97+"':"]''+\..11-
7/.0>*-.3/2[+]\3%)@18=+*}/"9}"

```

What's this, you say? It outputs the correct Python dict literal:

```
{'a':2,'b':22,'c':222,'d':3,'e':33,'f':333,'g':4,'h':44,'i':444,'j':5,'k':55,'l':555,'m':6,'n':66,'o':666,'p':7,'q':77,'r':777,'s':7777,'t':8,'u':88,'v':888,'w':9,'x':99,'y':999,'z':9999}

```

That is,

```
$ echo print `ruby golfscript.rb phonetyp.gs` | python
{'a': 2, 'c': 222, 'b': 22, 'e': 33, 'd': 3, 'g': 4, 'f': 333, 'i': 444, 'h': 44, 'k': 55, 'j': 5, 'm': 6, 'l': 555, 'o': 666, 'n': 66, 'q': 77, 'p': 7, 's': 7777, 'r': 777, 'u': 88, 't': 8, 'w': 9, 'v': 888, 'y': 999, 'x': 99, 'z': 9999}

```

# Answer
> 2 votes
# Python, 86 characters

Alternate Python solution:

```
d={}
for a in range(26):n=a-max(0,(a-11)/7);d[chr(a+97)]=`n/3+2`*(n%3+1+(a in(18,25)))

```

# Answer
> 1 votes
# JavaScript (*ES5*) 88 86 85 bytes

```
for(o={},a=c=2,b=96;a-10;a=a<(c%9%7?b:1e3)?a+[c]:++c)o[String.fromCharCode(++b)]=+a;o

```

**Result:**

```
{"a":2,"b":22,"c":222,"d":3,"e":33,"f":333,"g":4,"h":44,"i":444,"j":5,"k":55,"l":555,"m":6,"n":66,"o":666,"p":7,"q":77,"r":777,"s":7777,"t":8,"u":88,"v":888,"w":9,"x":99,"y":999,"z":9999}

```

If mixed types are allowed, it can be reduced by 1 byte.

# 86 84 bytes:

```
for(o={},a=c=2,b=96;a-10;a=a<(c%9%7?b:1e3)?a+[c]:++c)o[String.fromCharCode(++b)]=a;o

```

**Result:**

```
{"a":2,"b":"22","c":"222","d":3,"e":"33","f":"333","g":4,"h":"44","i":"444","j":5,"k":"55","l":"555","m":6,"n":"66","o":"666","p":7,"q":"77","r":"777","s":"7777","t":8,"u":"88","v":"888","w":9,"x":"99","y":"999","z":"9999"}

```

# Answer
> 1 votes
# perl, 61 bytes

Examine the mod3 and div3 of a counter $t to determine the base digit and number of repetitions. Handle the special cases of s and z separately.

```
$t=5;{map{$b=++$t%3+1;$b=4,--$t if/s|z/;$_,int($t/3)x$b}a..z}

```

With string output:

```
perl -MData::Dumper -e '$Data::Dumper::Sortkeys=1; $t=5;print Dumper {map{$b=++$t%3+1;$b=4,--$t if/s|z/;$_,int($t/3)x$b}a..z}'
$VAR1 = {
      'a' => '2',
      'b' => '22',
      'c' => '222',
      'd' => '3',
      'e' => '33',
      'f' => '333',
      'g' => '4',
      'h' => '44',
      'i' => '444',
      'j' => '5',
      'k' => '55',
      'l' => '555',
      'm' => '6',
      'n' => '66',
      'o' => '666',
      'p' => '7',
      'q' => '77',
      'r' => '777',
      's' => '7777',
      't' => '8',
      'u' => '88',
      'v' => '888',
      'w' => '9',
      'x' => '99',
      'y' => '999',
      'z' => '9999'
    };

```

And here's a more readable version of the code:

```
{
  map {
    my $reps = (++$pos % 3) + 1;
    if($_ =~ /s|z/) {
      --$pos;
      $reps=4;
    }
    my $digit = int( $pos/3 );
    $_ => $digit x $reps
  } ('a'..'z')
}

```

We start with $pos = 5 so that int(++$pos/3) starts off at 2.

We handle the case of s and z separately since they are the only exceptions to the modulo 3 rule.

# Answer
> 1 votes
# J - 57 char

The closest analogue to the dictionary datatype in J is a table of boxes: each row is an entry, containing the key on the left and the data on the right. It's not really unordered, but whenever you need a dictionary type of record, you would use something like this.

```
_2]\;n(;&.><\)/@|:/.n,.~u:97+i.#n=.,":"0(#~3+e.&7 9)2+i.8

```

`n` is the string `'22233344455566677778889999'`, which we create by taking the list `2 3 4 5 6 7 8 9` and taking three of 4 of each element, depending on whether the element is 7 or 9. Then we just convert each item to a string and run them together into a single string.

Then we make the alphabet, attach the digits to the alphabet with `,.~`, and then group them by the digits (this is `/.` at work). Within each group, we pair off the letter with the corresponding prefix of the string of same digits.

Finally, we run things together: `;` to take off the effects of the earlier grouping and `_2]\` to put it into the proper table shape.

```
   _2]\;n(;&.><\)/@|:/.n,.~u:97+i.#n=.,":"0(#~3+e.&7 9)2+i.8
+-+----+
|a|2   |
+-+----+
|b|22  |
+-+----+
|c|222 |
+-+----+
|d|3   |
+-+----+
|e|33  |
+-+----+
|f|333 |
+-+----+
|g|4   |
+-+----+
|h|44  |
+-+----+
|i|444 |
+-+----+
|j|5   |
+-+----+
|k|55  |
+-+----+
|l|555 |
+-+----+
|m|6   |
+-+----+
|n|66  |
+-+----+
|o|666 |
+-+----+
|p|7   |
+-+----+
|q|77  |
+-+----+
|r|777 |
+-+----+
|s|7777|
+-+----+
|t|8   |
+-+----+
|u|88  |
+-+----+
|v|888 |
+-+----+
|w|9   |
+-+----+
|x|99  |
+-+----+
|y|999 |
+-+----+
|z|9999|
+-+----+

```

# Answer
> 1 votes
# Mathematica, 168

This is the longest answer here... I'm sure there's a better way to do this.

```
(k=#2[[1]]+1;Append[{},{#->StringJoin@ConstantArray[ToString@k,#2]}]&~MapIndexed~#)&~MapIndexed~Characters@{"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}~Flatten~3

```

Output:

```
{"a" -> "2", "b" -> "22", "c" -> "222", "d" -> "3", "e" -> "33",
"f" -> "333", "g" -> "4", "h" -> "44", "i" -> "444", "j" -> "5",
"k" -> "55", "l" -> "555", "m" -> "6", "n" -> "66", "o" -> "666",
"p" -> "7", "q" -> "77", "r" -> "777", "s" -> "7777", "t" -> "8",
"u" -> "88", "v" -> "888", "w" -> "9", "x" -> "99", "y" -> "999",
"z" -> "9999"}

```

# Answer
> 0 votes
# Bash + coreutils, 91 bytes

```
p="printf %s\n"
paste <($p {a..z}) <($p {2..9} {22..99..11} {222..999..111} 7777 9999|sort)

```

Generates a tab-delimited table, which is a natural structure for a shell script - not sure if that meets the specs or not:

```
a   2
b   22
c   222
d   3
...
r   777
s   7777
t   8
u   88
v   888
w   9
x   99
y   999
z   9999

```

---

# Pure Bash, 137 bytes

Not very good.

```
declare -A a
b=({X..z})
for n in {9..33};do
c=${b[n]}
((n>26?n--:n))
printf -vk %$[n%3+1]s
a[$c]=${k// /$[n/3-1]}
done
a[s]+=7
a[z]=9999

```

This populates a bash associative array.

Crudely display it as follows:

```
$ for c in ${!a[@]}; do echo -n $c:${a[$c]},;done; echo
a:2,b:22,c:222,d:3,e:33,f:333,g:4,h:44,i:444,j:5,k:55,l:555,m:6,n:66,o:666,p:7,q:77,r:777,s:7777,t:8,u:88,v:888,w:9,x:99,y:999,z:9999,
$

```

# Answer
> 0 votes
# Python 2 (97)

I used a single dictionary comprehension:

```
{zip(*[(chr(i)for i in range(65,91))]*3)[i][k]:str(i+2)*(k+1)for k in range(3)for i in range(8)}

```

Unfortunately it's missing the `z` because on number 9 there are 4 letters.

# Answer
> 0 votes
## Clojure, 91 bytes

```
(zipmap(map char(range 97 123))(for[i(range 2 10)r(range 1(get{7 5 9 5}i 4))](repeat r i)))

```

`for` is ideal for generating these kinds of sequences. Output looks like this:

```
{\a (2), \b (2 2), \c (2 2 2), \d (3), ...

```

---
Tags: code-golf, data-structures
---


# Question
Title: Find the smallest positive integer which has all integers from 1 to n as factors
The question's pretty much described by the title: write a program or function that takes a positive integer *n* as input, and returns the smallest positive output which has all integers from 1 to *n* as factors. (Another way of looking at this is that you're looking for the least common multiple of the integers from 1 to *n*.)

This is a challenge, so the shortest entry in bytes wins.

Inspired by this challenge. (This challenge is basically the inverse of that one.)

## Test cases

* **Input:** 1; **Output**: 1
* **Input:** 6; **Output**: 60
* **Input:** 19; **Output**: 232792560
* **Input:** 22; **Output**: 232792560

You don't need to worry about integer precision issues (unless your language has integers so small that this would trivialise the problem). If your language does have bignums, though, you might also want to test your program on this case, just for fun:

* **Input:** 128; **Output**: 13353756090997411579403749204440236542538872688049072000

# Answer
> 27 votes
## Python, 46 bytes

```
g=lambda n,c=0:n<1or(c%n<1)*c or g(n,c+g(n-1))

```

Take that, past xnor!

---

**50 bytes:**

```
g=lambda n,i=1:n<1or(i*n%g(n-1)<1)*i*n or g(n,i+1)

```

I apparently golfed this problem 5 months ago, and I don't remember how this code works or why I golfed it. I think I have a golfing problem.

(Edit: It's from this answer. Thanks to Dennis for inspiring the solution and saving 4 bytes.)

Apparently, this code recursively finds `lcm(1..n)` as `lcm(lcm(1..n-1),n)`. So, the function `g` expresses `g(n)` as the smallest positive multiple `i*n` of `n` that's also a multiple of `g(n-1)`. (It could instead search multiples of `g(n-1)` for multiples of `n`, but this is golfier because `g(n-1)` only needs to be referenced once. Thanks to Dennis for this improvement.)

Here's the rest of the file, full of other golfing attempts:

```
f=lambda a,b:a and f(b%a,a)or b
g=lambda n:reduce(lambda a,b:a*b/f(a,b),range(1,n+1))

f=lambda a,b:a and f(b%a,a)or b
g=lambda n:n==1 or n*g(n-1)/f(n,g(n-1))

import math
g=lambda n:n==1 or n*g(n-1)/math.gcd(n,g(n-1))

g=lambda n,k=1:k*all(k%~i==0for i in range(n))or g(n,k+1)
g=lambda n,k=1:min(k%~i for i in range(n))and g(n,k+1)or k

l=lambda a,b:a%b and l(b,a%b)*a/(a%b)or a
g=lambda n:n<1or l(n,g(n-1))

g=lambda n,i=1:n==0 or (g(n-1)*i if g(n-1)*i%n==0 else g(n,i+1))

g=lambda n,i=1:n<1or g(n-1)*i*(g(n-1)*i%n<1)or g(n,i+1)

g=lambda n,i=1:n<1or(i*g(n-1)%n<1)*i*g(n-1)or g(n,i+1)

g=lambda n,r=1,c=1:r if n<2 else (g(n-1,r,r)if r%n==0 else g(n,r+c,c))

g=lambda n,r=1,c=1:r*(n<1)or r%n and g(n,r+c,c)or g(n-1,r,r)

g=lambda n,i=1:n<1or(i*g(n-1)%n or i)*g(n-1)or g(n,i+1)

def g(n):
 if n==0:return 1
 a=b=g(n-1)
 while b%n:b+=a
 return b

g=lambda n,i=1:n<1or g(n-1)*i%n and g(n,i+1)or g(n-1)*i

g=lambda n:n<1or min(range(n,3**n,n),key=g(n-1).__rmod__)

g=lambda n,i=1:n<1or(i*n%g(n-1)<1)*i*n or g(n,i+1)

r=n=input()
while n:
 c=r
 while r%n:r+=c
 n-=1
print r

r=n=input()
while n:
 c=r
 while r%n:r+=c
 n-=1
print r

r=1
for n in range(input()):
 c=r
 while r%~n:r+=c
print r

r=n=input()
while n:
 exec"r+=c*(r%n>0);"*n
 n-=1;c=r
print r

r=n=input();exec("r+=r%n and c;"*n+"n-=1;c=r;")*n;print r

```

It's eerie looking at my own past work. In trying to golf it, I keep thinking "maybe I can save some bytes by ..." and then seeing there's already a piece of code that attempted to do just that.

You think you've thought of everything, past xnor? Well, I'll show you!

# Answer
> 10 votes
# 05AB1E, 3 bytes

```
L.¿

```

Try it online!

**Explanation**

```
L     # range [1 ... input]
 .¿   # least common multiple

```

# Answer
> 8 votes
# julia, 11 bytes

```
n->lcm(1:n)

```

# Answer
> 6 votes
# Wolfram Language, ~~20~~ 13 bytes

```
LCM@@Range@#&

```

Applies a range from 1 to x, then applies it to LCM. To run this, append `[<input>]`.

7 bytes (!) shaved off by Martin.

# Answer
> 5 votes
## JavaScript (ES6), ~~54~~ 50 bytes

```
f=(n,L=1,a=L,b=n)=>n?b?f(n,L,b,a%b):f(n-1,n*L/a):L

```

### Test cases

```
f=(n,L=1,a=L,b=n)=>n?b?f(n,L,b,a%b):f(n-1,n*L/a):L

console.log( 1, f( 1));
console.log( 6, f( 6));
console.log(19, f(19));
console.log(22, f(22));
```

# Answer
> 5 votes
# PHP, ~~61~~ ~~52~~ 48 bytes

saved 9 bytes thanks to @user59178, 4 bytes by merging the loops to one.

Recursion in PHP is bulky due to the `function` key word; so I use iteration.
And with a "small" trick, I now even beat JS.

```
while(++$k%++$i?$i>$argv[1]?0:$i=1:$k--);echo$k;

```

takes input from command line argument. Run with `-r`.

**breakdown**

```
while(++$k%++$i?    # loop $i up; if it does not divide $k
    $i>$argv[1]?0       # break when $i is larger than input
    :$i=1               # while not, reset $i and continue loop with incremented $k
    :$k--);         # undo increment while $i divides $k
echo$k;         # print $k

```

**ungolfed**

That´s actually two loops in one:

```
while($i<=$argv[1])     # break when $i (the lowest non-divisor of $k) is >input
    for($k++,           # loop $k up from 1
        $i=0;$k%++$i<1;);   # loop $i up from 1 while it divides $k
echo$k;                 # print $k

```

# Answer
> 3 votes
# Perl 6, 13 bytes

```
{[lcm] 1..$_}

```

Try it

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣

  [lcm]      # reduce using ｢&infix:<lcm>｣

    1 .. $_  # a Range from 1 to the input ( inclusive )
}

```

# Answer
> 2 votes
## Perl, 32 bytes

31 bytes of code + `-p` flag.

```
$.++while grep$.%$_,2..$_;$_=$.

```

Try it online!

The code test every number (starting from 1 and incrementing by 1 each time) to find a common multiple. So it's rather slow even for not so large numbers.

`grep$.%$_,2..$_` returns an array of the elements of the range `2..$_` (where `$_` is the input) that satisfy `$.%$_!=0` (`$.` is the number we're trying), ie. an array of the elements that aren't a divisor of `$.`. While this array isn't empty, `$.++` is incremented. At the end, `$_` is set tp `$.` and implicitly print thanks to `-p` flag.

# Answer
> 2 votes
# Jelly, 4 bytes

```
Ræl/

```

Try it online!

When I posted the question, I thought Jelly didn't have a built-in for this. We were discussing the problem in chat, though, and someone pointed out that it does, so I decided I might as well write the obvious solution using it. (That said, 4 bytes is quite a lot for a challenge that's mostly solved via a built-in! It may well be possible to beat this in some other language, or even in Jelly itself. **Update:** I see 05AB1E beat this while I was writing out the entry.)

Ideally, this answer shouldn't be voted on either way, in order to let answers which require more skill shine; it's not wrong, but it's also not all that interesting. As the community advert says:

**Know how to vote****Byte count isn't everything****Support clever golfing!**

## Explanation

```
Ræl/
R    All numbers from 1 to the input
   / Reduce by
 æl  lowest common multiple

```

# Answer
> 2 votes
## Sage, ~~33~~ 28 bytes

No golfing tricks here, but somehow I had an urge to post this xP

```
l=lambda n:lcm(range(2,n+1))

```

~~Too bad Sage's `lcm` only takes 2 arguments, unlike Octave's variadic one.~~
*It can actually take a list as input.*

# Answer
> 2 votes
## GAP, 14 bytes

```
n->Lcm([1..n])

```

Checking the test cases:

```
gap> List([1,6,19,22,128], n->Lcm([1..n]) );
[ 1, 60, 232792560, 232792560,
  13353756090997411579403749204440236542538872688049072000 ]

```

# Answer
> 1 votes
# Octave, 25 bytes

```
@(n)lcm(num2cell(1:n){:})

```

# Answer
> 0 votes
# Maxima, 29 bytes

```
f(n):=lcm(makelist(x,x,1,n));

```

# Answer
> 0 votes
## Ruby, 22 bytes

```
->n{(1..n).reduce:lcm}

```

# Answer
> 0 votes
# REXX, 61 bytes

```
arg a
do m=1 until a<n
  do n=1 to a until m//n>0
  end
end
say m

```

(Indented for readability)

---
Tags: code-golf, math, number-theory
---


title: Braincopterify an image

text:
# Question
Title: Braincopterify an image
## Introduction

Braincopter is an esoteric Brainf\*** derivative that encodes a Brainf\*** program as an image. As a 2D language, it uses two additional commands; they rotate the instruction pointer (initially pointing right) clockwise and counterclockwise. Braincopter is very similar to Brainloller, except that instead of using distinct colours as different commands, it instead calculates the command based on the RGB value of each pixel.

Braincopter calculates the command for each pixel based on the formula `N = (65536 * R + 256 * G + B) % 11`, where `N` is the command number. The mapping from command numbers to Brainf\*** commands is as follows:

```
0  >
1  <
2  +
3  -
4  .
5  ,
6  [
7  ]
8  rotate instruction pointer to the right (clockwise)
9  rotate instruction pointer to the left (counterclockwise)
10 NOP

```

Braincopter is useful for steganography, or the hiding of secret messages in something else, as the colour of each pixel in any given photo can be changed just slightly to give the desired operation. Such changed pictures are often indistinguishable from the originals.

## Challenge

Write a program or function that takes an image and a string of brainf\*** code as input and produces the original image with the brainf\*** code encoded in it.

To do this, take each pixel in the original image and replace it with the RGB value closest to the colour of the original pixel that evaluates to the correct Braincopter instruction. Colour difference for the purposes of this challenge is defined as `abs(R1 - R2) + abs(G1 - G2) + abs(B1 - B2)`. In the case of a tie in which two colours resolving to the same Braincopter command are equally close to the original colour, either can be chosen.

For example, if the original colour is `#FF8040` and needs to be modified to produce a '1' instruction in Braincopter, `#FF7F40` should be chosen.

Braincopter will exit when the instruction pointer runs off the edge of the image, so we'll keep it on the image by using the 8 and 9 commands (rotate instruction pointer clockwise and counterclockwise respectively). It's easiest to explain the format of the encoding with an example.

For the input `+[[->]-[-<]>-]>.>>>>.<<<<-.>>-.>.<<.>>>>-.<<<<<++.>>++.` and an 8x9 image, the instructions will be laid out like this (using Brainf\*** commands instead of the Braincopter equivalents, and unicode representations of the turns ):

```
+ [ [ - > ] - ↲
↳ - > ] < - [ ↲
↳ ] > . > > > ↲
↳ < < < < . > ↲
↳ - . > > - . ↲
↳ > . < < . > ↲
↳ > > > - . < ↲
↳ + + < < < < ↲
↳ . > > + + . N

```

(Where N is a NOP.) As you can see, control flow travels from left to right until it hits the first set of clockwise turns, then travels right to left across the second row, et cetera. Your program *must* use this control flow. The brainf\*** input will always be able to fit in the image; however, you may not assume it will always fit the image exactly. If it's too small, pad it with NOPs; the Braincopter code must still have the clockwise/counterclockwise turns on either side, though.

You may assume that the Brainf\*** input will contain only the eight characters `><+-,.[]`.

Use the official Braincopter interpreter to test the outputs of your program or function.

## Test cases

Input:

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

```

Example output:

Braincopter output:

```
Hello World!

```

Input:

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

```

Output:

Braincopter output:

```
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17...

```

Input:

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

```

Output:

Braincopter output:

This is a Brainf\*** self-interpreter. It separates code from input by `!`; for example, the input `,[.,]!Hello, World!\0` will output `Hello, World!`, assuming the `\0` was replaced by a null byte.

## Scoring

This is , so the shortest answer wins. Happy golfing!

# Answer
> 1 votes
# Python, ~~664~~ 656

usage : `python snippet.py image.png <bf script>`

```
R=range;_=R(256);a=abs
def C(c):R,G,B=c;return'><+-.,[]RLN'[(65536*R+256*G+B)%11]
def D(c,d):R,G,B=c;F,V,H=d;return a(R-F)+a(G-V)+a(B-H)
def E(c1,i):return min([(c,D(c1,c))for c in[(r,g,b)for r in _ for g in _ for b in _]if C(c)==i],key=lambda x:x[1])[0]
def B(b,w,h):
 x,y,d=0,0,1
 for c in(b[0]+'R'.join(['L'+s for s in[s[::-1]if i%2 else s for i,s in enumerate([(b[1:]+'N'*w*h)[q:q+w-2]for q in R(0,w*h,w-2)])]])[1:])[:w*h][:-1]+'N':
  yield c,(a(x),y)
  x+=d
  if c=='R':x=0;y+=1;d*=-1
import sys
from PIL import Image
I=Image.open(sys.argv[1]).convert('RGB')
W,H=I.size
P=I.load()
for i,p in B(sys.argv[2],W,H):P[p]=E(P[p],i)
I.save(sys.stdout,"PNG")

```

explanations to come ...

---
Tags: code-golf, image-processing, brainfuck, encoding, steganography
---


title: Sprunge this! Sprunge that!

text:
# Question
Title: Sprunge this! Sprunge that!
Your task is to create a program or function that creates a paste on sprunge.us. Your program/function must receive the text to *sprunge* from your language's usual input mechanism, such as standard in; or in the case of a function, it can be a string or whatever makes the most sense to you. Your program will POST the text from input to `http://sprunge.us/` as `multipart/form-data` with the form field name of `sprunge`. Finally, your program will output/return the URL sent back in the reply from the POST.

This is a code golf, so shortest answer (in bytes) wins.

Here is an example solution using `bash` and `curl` taken directly from the sprunge.us website. Feel free to use it in your own golf:

```
curl -F 'sprunge=<-' http://sprunge.us

```

Which returns the URL to the paste, which looks like `http://sprunge.us/aXZI`, where the `aXZI` is the ID of the sprunge.

*This is my first code golfing challenge, please let me know if this is too easy or not creative enough*

# Answer
> 1 votes
# Bash, 29 25 bytes

```
curl -F sprunge{=\<-,.us}

```

Thanks to @Score\_Under for providing this awesome solution!

Old solution:

```
curl -Fsprunge=\<- sprunge.us

```

Quotes around 'sprunge=\<-' are unnecessary, as long as the `<` is escaped.

EDIT: Interestingly, this alternative way has the exact same length:

```
a=sprunge
curl -F$a=\<- $a.us

```

# Answer
> 2 votes
# Bash, 30 bytes

```
curl -F'sprunge=<-' sprunge.us

```

Just removed the unneeded space in `-F 'sprunge=<-'` and the `http://` from the `sprunge.us` url. OP gave me explicit permission to golf his reference solution.

# Answer
> 2 votes
# HTML, 88 bytes

```
<form action="http:sprunge.us" method="POST"><textarea></textarea><button type="submit">

```

To test this easily, prepend `data:text/html,` to the code and paste it into your address bar (works for me on chrome).

Full (easily) testable code:

```
data:text/html,<form action="http:sprunge.us" method="POST"><textarea></textarea><button type="submit">

```

---
Tags: code-golf, internet
---


title: Compose a Song!

text:
# Question
Title: Compose a Song!
**Preface**

The available keys are the keys of the A through G and A minor through G minor.

**The Challenge**

Create a program that creates and saves to a playable audio file a "song" of using (uniformly distributed) random chords. The song must be of length `n` and in key `k`. The chords in each "song" must conform to the key. If you don't know what belongs in a particular key, the image below may help.

**Rules and Guidelines**

* Must conform to key
* Chords must be chosen randomly with even distribution
* Assume each chord is held for 1 beat in 4:4 time at 120 bpm, therefore each chord lasts .5 seconds
* The same chord is allowed to be selected multiple times in a row, though it must be randomly
* The program should theoretically be able to generate a "song" of any positive time value
* Assume `n > 1` in all cases
* Input will be a length n (in seconds) and a key k as a major or minor key `A, Amin, B, Bmin, etc`
* Output must be in the form of a playable audio file

### Examples (as strings)

```
[key], [length] -> [output]

C, 1 -> Dmin, F

B, 6 -> D# min, C# min, F#, G# min, E, B, F#, C# min, C# min, D# min, E, G# min

```

# Answer
> 1 votes
# JavaScript (ES6) + synth-js, 303 bytes

```
k=>l=>eval("for(m=/(.)(#?)(m?)/.exec(k),W=synth.WAV,w=new W,g=m[3]?[2,1,2,2,1,3,1]:[2,2,1,2,2,2,1],s=W.semitone(m[1]+4+m[2]),n=0;n<l*2;n++)for(r=Math.random()*7|0,c=i=g.reduce((u,h,j)=>u+(j<r)*h,0);c-i<12;c+=g[r++%7]+g[r++%7])w.writeNote({note:W.note(s+c),time:.5,amplitude:.25},[],1,c-i<9);w.toBlob()")

```

### De-obfuscated:

```
(key) => (length) => {
  let match = /(.)(#?)(m?)/.exec(key),
      W = synth.WAV,
      wav = new W,
      // if minor, use minor gaps else major gaps
      gaps = match[3] ? [2, 1, 2, 2, 1, 3, 1] : [2, 2, 1, 2, 2, 2, 1],
      // get semitone index of scale root
      semitone = W.semitone(match[1] + 4 + match[2]);

  // 2 notes per second
  for (let note = 0; note < length * 2; note++) {

        // choose 1 of 7 random chords
    let random = Math.random() * 7 | 0,
        // get number of half steps from scale root to chord root
        initial = gaps.reduce(
          (sum, half, index) => sum + (index < random) * half,
        0);

    // of every tetrad, maximum of 11 half steps from root to 4th is possible
    // tetrads composed of thirds, so add two gaps for every increment
    for (let current = initial; current - initial < 12; current += gaps[random++ % 7] + gaps[random++ % 7]) {

      // write note data as binary
      wav.writeNote({note: W.note(semitone + current), time: .5, amplitude: .25}, [], 1, current - initial < 9);
    }
  }

  // return blob of wav binary data
  return wav.toBlob();
}

```

For those of you who might ask *"Why isn't* `new Audio(URL.createObjectURL(...))` *part of your byte-count?"*, according to MDN:

> A `Blob` object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The `File` interface is based on `Blob`, inheriting blob functionality and expanding it to support files on the user's system.

Since this function returns a `Blob` with MIME-type `audio/wav`, it qualifies as a "playable audio file" as requested in the specification for the challenge.

## Demo:

```
f=
k=>l=>eval("for(m=/(.)(#?)(m?)/.exec(k),W=synth.WAV,w=new W,g=m[3]?[2,1,2,2,1,3,1]:[2,2,1,2,2,2,1],s=W.semitone(m[1]+4+m[2]),n=0;n<l*2;n++)for(r=Math.random()*7|0,c=i=g.reduce((u,h,j)=>u+(j<r)*h,0);c-i<12;c+=g[r++%7]+g[r++%7])w.writeNote({note:W.note(s+c),time:.5,amplitude:.25},[],1,c-i<9);w.toBlob()")

h=
()=>new Audio(URL.createObjectURL(f(k.value)(l.value))).play()
```

```
<script src=//unpkg.com/synth-js/dst/synth.min.js></script>
<input id=k value=B>
<input id=l value=1>
<button type=button onclick=h()>Play</button>
```

If you want to verify that all chords which can be randomly chosen are correct, here is a table of all possible chords below, given valid input:

```
function markup(key) {
  let match = /(.)(#?)(m?)/.exec(key),
      numerals = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII'],
      gaps = match[3] ? [2,1,2,2,1,3,1] : [2,2,1,2,2,2,1],
      semitone = synth.WAV.semitone(match[1] + 4 + match[2]),
      string = '  ' + key + ':\n';

  for (let root = 0; root < 7; root++) {

    let initial = gaps.reduce(
          (sum, half, index) => sum + (index < root) * half,
        0),
        index = root;

    string += '    ' + numerals[root] + ': ';

    for (let current = initial; current - initial < 12; current += gaps[index++ % 7] + gaps[index++ % 7]) {

      string += synth.WAV.note(semitone + current) + ' ';
    }

    string += '\n';
  }

  string += '\n';

  return string;
}

let keys = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
let html = '<pre>';

html += 'Major Scales:\n';

keys.forEach(key => {
  html += markup(key);
});

html += 'Minor Scales:\n';

keys.forEach(key => {
  html += markup(key + 'm');
});

html += '</pre>';

document.write(html);
```

```
<script src=//unpkg.com/synth-js/dst/synth.min.js></script>
```

---
Tags: code-golf, random, music
---


# Question
Title: Error (or warning) quine that's also a regular quine
(Inspired by this comment on an old question.)

## Background

An error quine (also known as a "Kimian quine") is a program which, when compiled or run, causes the compiler/interpreter/runtime to print an error message that has identical text to the program itself, and nothing else. For the purposes of this challenge, we're defining "error" broadly, to include warnings too.

## Task

In this challenge, we're looking for a which is *also* an error quine. When executed, the program must print its own source code normally (i.e. not as an error/warning message); this must be a proper quine (i.e. some part of the program must encode a different part of the output). Additionally, compiling and executing the program must *also* cause the program's source code – and nothing else – to be printed as error or warning messages by the implementation. (Note that this means that you will not be able to use compile-time errors, in languages where those prevent the program from executing normally.) So in other words, the program's source code will be printed twice, once via each method.

## Clarifications

* In most cases, it'll be obvious what is and isn't an error/warning message; we aren't distinguishing between the two here. In ambiguous cases, define an error/warning message as any text that's output by the implementation either: 1. as a consequence of something other than executing a command (or whatever the closest equivalent is in the language); or 2. that wasn't part of the input to the command that produced it as output.
* The error/warning part of the quine doesn't need to be a proper quine (although in most cases it will be by chance, as most error and warning messages contain considerable amounts of fixed text).
* It's acceptable for the program to output multiple errors/warnings, which form the program's source when concatenated together. It's not acceptable to output errors/warnings that don't appear in the source.
* Unlike in many challenges, the switches given to the compiler, and the program filename, are likely to be highly relevant in this challenge. Given that the challenge may not be possible otherwise, I'm willing to be flexible here, although if you run the implementation in an unusual way, remember that PPCG rules charge a byte penalty for doing so (equal to the number of additional characters that you'd need to add on the command line over the shortest "normal" way to run a program), and thus you'll need to specify the size of the penalty in your post. (For example, if the interpreter you're using reads the program from a file, and has no particular restrictions on the filename, the shortest normal way to run the program would be from a file with a 1-character filename; thus, if you need a 100-character filename to make your program work, you'd incur a byte penalty of +99.)
* The compiler/interpreter version you use may well be relevant, so as part of your submission, please state a specific compiler or interpreter on which your program works, and which version is required. (For example, a C submission might state "C (gcc 6.2.0)" in the header.)
* Note that this task may not be possible in all languages. In the languages where it is, the easiest method will likely be to find an error or warning message for which it's possible to customize some subset of the text (via changing the name of something that gets quoted in the message; filenames are a common choice here, but not the only one). I'll be particularly impressed (and surprised) if someone finds a way to do this using *only* error and warning messages whose text is fixed.

## Victory condition

This is a challenge, so an entry is considered to be better if it has a smaller byte count. As such, once you've got your program working at all, you want to optimize it to bring the number of bytes down as far as possible. (However, don't be discouraged if there's already a shorter entry, especially if it's in a different language; what we're really looking for here is to shorten a particular algorithm or idea behind a program as much as possible, but seeing multiple solutions in different languages or that rely on different principles is always worthwhile.)

# Answer
> 9 votes
# JavaScript (Firefox 50), 153 bytes

```
Error: "Error: 1.replace(/.+/,x=>{alert(x=x.replace(1,uneval(x)));throw x.slice(7)})".replace(/.+/,x=>{alert(x=x.replace(1,uneval(x)));throw x.slice(7)})

```

### Explanation

The idea here was to start with the most easily modifiable JS quine I've found yet:

```
".replace(/.+/,x=>alert(uneval(x)+x))".replace(/.+/,x=>alert(uneval(x)+x))

```

The `throw` keyword is a simple way to make it throw its own code as well:

```
".replace(/.+/,x=>{alert(x=uneval(x)+x);throw x})".replace(/.+/,x=>{alert(x=uneval(x)+x);throw x})

```

However, there's a slight problem: Firefox prepends the thrown message with `Error:`. Fortunately, `Error: mycode` is actually valid JavaScript! (To learn more about this, visit MDN.)

```
Error: ".replace(/.+/,x=>{alert(x=uneval(x)+x);throw x})Error: ".replace(/.+/,x=>{alert(x=uneval(x)+x);throw x})

```

Oops, this alerts the wrong thing:

```
".replace(/.+/,x=>{alert(x=uneval(x)+x);throw x})Error: ".replace(/.+/,x=>{alert(x=uneval(x)+x);throw x})Error:

```

Since the quotation mark is no longer at the start of the code, `uneval(x)+x` won't give us the correct result. The best way to fix this is to add a placeholder in place of the nested string:

```
Error: "Error: 1.replace(/.+/,x=>{alert(x=x.replace(1,uneval(x)));throw x})".replace(/.+/,x=>{alert(x=x.replace(1,uneval(x)));throw x})

```

Uh-oh, now there's an extra `Error:` in the error message. Let's fix that by slicing the string:

```
Error: "Error: 1.replace(/.+/,x=>{alert(x=x.replace(1,uneval(x)));throw x.slice(7)})".replace(/.+/,x=>{alert(x=x.replace(1,uneval(x)));throw x.slice(7)})

```

And finally, both the output and the error message are identical to the code! I'd add a Stack Snippet, but it doesn't seem to work in a snippet in any browser.

# Answer
> 5 votes
# Python 2, ~~217~~ ~~80~~ 51 bytes

The trailing linefeed is required.

```
s='s=%r;print s%%s;exit(s%%s)';print s%s;exit(s%s)

```

**Try it online**

I started with a simple quine:

```
s='s=%r;print s%%s';print s%s

```

Then I added `raise` on the end to throw an `IOError`.

```
s='s=%r;print s%%s;raise IOError(s%%s)';print s%s;raise IOError(s%s)

```

Unfortunately, the traceback was causing problems (I couldn't make it go away completely), and the name of the exception was always printed in front like `IOError: <code here>`, even if I removed the traceback.

Then I found this helpful SO answer and modified it for my purposes.

Then I found that I can skip creating my own class and can just use `sys.exit`, making my code much shorter.

---
Tags: code-golf, quine
---


title: Longest domino chain

text:
# Question
Title: Longest domino chain
# Challenge description

**Dominoes** is a game played with tiles with two values on it - one on the left, one on the right, for example `[2|4]` or `[4|5]`. Two tiles can be joined together if they contain a common value. The two tiles above can be joined like this:

`[2|4][4|5]`

We'll call a sequence of `n` joined tiles a **chain** of length n. Of course, tiles can be rotated, so tiles `[1|2]`, `[1|3]` and `[5|3]` can be rearranged into a chain `[2|1][1|3][3|5]` of length 3.

Given a list of pairs of integers, determine the length of the longest chain that can be formed using these tiles. If the list is empty, the correct answer is `0` (note that you can always form a chain of length `1` from a non-empty list of tiles).

# Sample input / output

```
[(0, -1), (1, -1), (0, 3), (3, 0), (3, 1), (-2, -1), (0, -1), (2, -2), (-1, 2), (3, -3)] -> 10
([-1|0][0|-1][-1|2][2|-2][-2|-1][-1|1][1|3][3|0][0|3][3|-3])

[(17, -7), (4, -9), (12, -3), (-17, -17), (14, -10), (-6, 17), (-16, 5), (-3, -16), (-16, 19), (12, -8)] -> 4
([5|-16][-16|-3][-3|12][12|-8])

[(1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1)] -> 7
([1|1][1|1][1|1][1|1][1|1][1|1][1|1])

[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)] -> 1
(any chain of length 1)

[] -> 0
(no chain can be formed)

```

# Answer
# Brachylog, 23 bytes

```
s:papcb~k~c:{#=l2}al|,0

```

Try it online!

## Explanation

```
s:papcb~k~c:{#=l2}al|,0
s                         Check subsets of the input (longest first).
 :pa                      Check all permutations inside the input's elements
    p                     and all permutations /of/ the input's elements.
     c                    Flatten the result;
      b                   delete the first element;
       ~k                 find something that can be appended to the end so that
         ~c               the result can be unflattened into
           :{    }a       a list whose elements each have the property:
             #=             all the elements are equal
               l2           and the list has two elements.
                   l      If you can, return that list's length.
                    |,0   If all else fails, return 0.

```

So in other words, for input like `[[1:2]:[1:3]:[5:3]]`, we try to rearrange it into a valid chain `[[2:1]:[1:3]:[3:5]]`, then flatten/behead/unkknife to produce `[1:1:3:3:5:_]` (where `_` represents an unknown). The combination of `~c` and `:{…l2}a` effectively splits this into groups of 2 elements, and we ensure that all the groups are equal. As we flattened (doubling the length), removed one element from the start and added one at the end (no change), and grouped into pairs (halving the length), this will have the same length as the original chain of dominoes.

The "behead" instruction will fail if there are no dominoes in the input (actually, IIRC the `:pa` will also fail; `a` dislikes empty lists), so we need a special case for 0. (One big reason we have the asymmetry between `b` and `~k` is so that we don't also need a special case for 1.)
> 5 votes

# Answer
# Brachylog, 29 bytes

```
v0|sp:{|r}aLcbk@b:{l:2%0}a,Ll

```

Try it online!

Pretty sure this is awfully long, but whatever. This is also awfully slow.

### Explanation

```
v0                               Input = [], Output = 0
  |                              Or
   sp:{|r}aL                     L (a correct chain) must be a permutation of a subset of the
                                   Input with each tile being left as-is or reversed
           Lcbk                  Concatenate L into a single list and remove the first and
                                   last elements (the two end values don't matter)
               @b                Create a list of sublists which when concatenated results in
                                   L, and where each sublist's elements are identical
                 :{     }a,      Apply this to each sublist:
                   l:2%0           It has even length
                           Ll    Output = length(L)

```

The reason this will find the biggest one is because `s - subset` generates choice points from the biggest to the smallest subset.
> 4 votes

# Answer
# Mathematica, 191 bytes

```
If[#=={},0,Max[Length/@Select[Flatten[Rest@Permutations[#,∞]&/@Flatten[#,Depth[#]-4]&@Outer[List,##,1]&@@({#,Reverse@#}&/@#),1],MatchQ[Differences/@Partition[Rest@Flatten@#,2],{{0}...}]&]]]&

```

Can be golfed a fair bit, I'm sure. But basically the same algorithm as in Fatalize's Brachylog answer, with a slightly different test at the end.
> 4 votes

# Answer
# Haskell, ~~180 134~~ ~~131~~ 117 bytes

```
p d=maximum$0:(f[]0d=<<d)
f u n[]c=[n]
f u n(e@(c,d):r)a@(_,b)=f(e:u)n r a++(f[](n+1)(r++u)=<<[e|b==c]++[(d,c)|b==d])

```

Try it online! New approach turned out to be both shorter and more efficient. Instead of all possible permutations only all valid chains are build.

*Edit:* The 117 byte version is much slower again, but still faster than the brute-force.

---

Old brute-force method:

```
p(t@(a,b):r)=[i[]t,i[](b,a)]>>=(=<<p r)
p e=[e]
i h x[]=[h++[x]]
i h x(y:t)=(h++x:y:t):i(h++[y])x t
c%[]=[0]
c%((_,a):r@((b,_):_))|a/=b=1%r|c<-c+1=c:c%r
c%e=[c]
maximum.(>>=(1%)).p

```

This is a brute-force implementation which tries all possible permutations (The number of possible permutations seems to be given by A000165, the "***double** factorial of even numbers*"). Try it online barely manages inputs up to length 7 (which is kind of impressive as 7 corresponds to *645120* permutations).

**Usage:**

```
Prelude> maximum.(>>=(1%)).p $ [(1,2),(3,2),(4,5),(6,7),(5,5),(4,2),(0,0)]
4

```
> 2 votes

# Answer
## JavaScript (Firefox 30-57), 92 bytes

```
(a,l)=>Math.max(0,...(for(d of a)for(n of d)if(!(l-n))1+f(a.filter(e=>e!=d),d[0]+d[1]-n)))

```
* `l` is the last value, or `undefined` for the initial invocation. `l-n` is therefore a falsy value if the domino can be played.
* `d` is the domino under consideration.
* `n` is the end of the domino under consideration for chaining to the previous domino. The other end may readily be calculated as `d[0]+d[1]-n`.
* `0,` simply handles the base case of no playable dominoes.
> 2 votes

# Answer
# Python 2, 279 bytes

Golfed:

```
l=input()
m=0
def f(a,b):
 global m
 l=len(b)
 if l>m:m=l
 for i in a:
  k=a.index(i)
  d=a[:k]+a[k+1:]
  e=[i[::-1]]
  if not b:f(d,[i])
  elif i[0]==b[-1][1]:f(d,b+[i])
  elif i[0]==b[0][0]:f(d,e+b)
  elif i[1]==b[0][0]:f(d,[i]+b)
  elif i[1]==b[-1][1]:f(d,b+e)
f(l,[])
print m

```

Try it online!

Same thing with some comments:

```
l=input()
m=0
def f(a,b):
 global m
 l=len(b)
 if l>m:m=l                      # if there is a larger chain
 for i in a:
  k=a.index(i)
  d=a[:k]+a[k+1:]                # list excluding i
  e=[i[::-1]]                    # reverse i
  if not b:f(d,[i])              # if b is empty
                                 # ways the domino can be placed:
  elif i[0]==b[-1][1]:f(d,b+[i]) # left side on the right
  elif i[0]==b[0][0]:f(d,e+b)    # (reversed) left side on the left
  elif i[1]==b[0][0]:f(d,[i]+b)  # right side on left
  elif i[1]==b[-1][1]:f(d,b+e)   # (reversed) right side on the right
f(l,[])
print m

```

I'm posting because I didn't see any python answers...someone will see my answer and, in disgust, be forced to post something much shorter and efficient.
> 1 votes

# Answer
## Clojure, ~~198~~ 183 bytes

Update: Better handling of "maximum of possibly empty sequence"

```
(defn F[a C](remove(fn[i](identical? i a))C))(defn M[C](apply max 0 C))(defn L([P](M(for[p P l p](L l(F p P)))))([l R](+(M(for[r R[i j][[0 1][1 0]]:when(=(r i)l)](L(r j)(F r R))))1)))

```

Earlier version:

```
(defn F[a C](remove(fn[i](identical? i a))C))(defn M[C](apply max 1 C))(defn L([P](if(empty? P)0(M(for[p P l p](L l(F p P))))))([l R](M(for[r R[i j][[0 1][1 0]]:when(=(r i)l)](+(L(r j)(F r R))1)))))

```

Calling convention and test cases:

```
(L [])
(L [[2 4] [3 2] [1 4]])
(L [[3, 1] [0, 3], [1, 1]])
(L [[17 -7] [4 -9] [12 -3] [-17 -17] [14 -10] [-6 17] [-16 5] [-3 -16] [-16 19] [12 -8]])
(L [[0 -1] [1 -1] [0 3] [3 0] [3 1] [-2 -1] [0 -1] [2 -2] [-1 2] [3 -3]])
(L [[1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1]])

```

`F` returns elements of list `C` without the element `a`, `M` returns the max of input ingerers or 1.

`L` is the main function, when called with a single argument it generates all possible starting pieces and finds the max length for each of them. When called with two arguments the `l` is the first element of the sequence to which the next piece must match and `R` is rest of the pieces.

Generating permutations and "choose one element and split to rest" were quite tricky to implement succinctly.
> 0 votes

---
Tags: code-golf, combinatorics, path-finding, dominoes
---


# Question
Title: Shortest program that displays a red 3D cube
Write the shortest program you can that displays a red 3D cube.

Rules:

* The cube must be red, have 6 rendered sides, and be displayed in 3D.
* Your program cannot load any textures.
* More than 1 side must be visible.
* The result does not need to be rotatable.

# Answer
> 29 votes
## T-SQL, 168 chars (but no OpenGL)

Decidedly *not* using OpenGL or Direct3D because there is absolutely no way to do that in SQL. I think I have a pretty nice little cube, anyway.

```
RAISERROR('
      @@@
   @@@@@@@@@
@@@@@@@@@@@@@@@
x@@@@@@@@@@@@&&
xxx@@@@@@@@&&&&
xxxxx@@@&&&&&&&
xxxxxx&&&&&&&&&
 xxxxx&&&&&&&
   xxx&&&&
     x&&
',15,1)

```

Exploiting the fact that errors of high severity are raised in red:

# Answer
> 13 votes
## Mathematica 25

```
Graphics3D@{Red,Cuboid[]}

```

Instructions for testing this answer without Mathematica installed:

1. Download http://pastebin.com/3dnGNHCP and save it as \*.CDF
2. Dowload the free CDF environment from Wolfram Research at https://www.wolfram.com/cdf-player/ (not a small file)
3. The cube can be "dragged" to rotate it!

# Answer
> 10 votes
# TXT, 12 bytes

This is a TXT file with ANSI escape codes and UTF-8 characters. I can show its contents as a C string:

```
"\033[31m\xe2\xac\xa2\033[m\n"

```

or as a hexdump:

```
0000000: 1b5b 3331 6de2 aca2 1b5b 6d0a            .[31m....[m.

```

This is the result when it is "executed" with `cat` on a terminal.

You can see the small cube, solid red, with 3 visible faces and no texture loaded:

# Answer
> 7 votes
May i be the first to...

# Processing, ~~513~~ 110

```
void setup(){size(640,360,P3D);}void draw(){fill(255,0,0);translate(width/2,height/2,0);rotateX(0.7);box(99);}

```

# Answer
> 6 votes
# Sage, 17

*Note: after some research I realised that this does not use OpenGL.*

```
cube(color='red')

```

Output:

I can finally beat Mathematica!

It uses Jmol (which comes with the Sage installation) to show the cube, which allows rotation by dragging.

# Answer
> 3 votes
# Processing, 68 Chars

Ultra-golf version of @TheDoctor 's answer, using tips from @Ace, plus one of my own (rotation.)

```
void setup(){size(99,99,P3D);fill(#FF0000);translate(9,9,0);box(9);}

```

Produces a pathetically small cube of just 9 units per side (image at left.) Changing the `9`'s to `25`'s we get a larger cube (image at right.)

By keeping the cube far from the centre of the window, we can see the bottom and right hand side without needing to rotate (if it was in the centre of the window, they would be hidden.

# Answer
> 3 votes
# Mathematica 9, 21

```
Image3D@{{{{3,0,0}}}}

```

---

# Mathematica 10, 17

```
Image3D@{{{Red}}}

```

# Answer
> 2 votes
# Windows Batch, 51 chars

```
@echo off
color 0c
echo   _
echo /!_!
echo |/_/

```

I know this is cheating, but at least I get bronze (at the time this was posted). Partially inspired by Jonathan van Matre's answer.

# Answer
> 1 votes
## JAVASCRIPT - TQUERY (108 chars)

```
w=tQuery.createWorld().boilerplate().start();tQuery.createCube().addTo(w).setBasicMaterial().color(0xff0000)
```

```
<script src="https://jeromeetienne.github.io/tquery/build/tquery-bundle.js"></script>
```

http://jsfiddle.net/Gy4w7/335/

# Answer
> 1 votes
# Postscript 920

Requires mat.ps.

```
/olddiv/div load def/div{dup 0 eq{pop pop
100000}{olddiv}ifelse}def(mat.ps)run/disp<</cam[0
0 10]/theta[0 0 0]/eye[0 0 20]/Rot 3 ident>>def/makerot{theta
0 get roty theta 1 get rotx matmul theta 2 get rotz matmul}def/proj{DICT
begin cam{sub}vop Rot matmul 0 get aload pop eye aload pop 4 3 roll div
exch neg 4 3 roll add 1 index mul 4 1 roll 3 1 roll sub mul exch end}dup
0 disp put def/v[[1 1 -1][-1 1 -1][-1 -1 -1][1 -1 -1][1 1 1][-1 1 1][-1 -1 1][1 -1 1]]def
/fv[[0 1 2 3][0 4 5 1][1 5 6 2][2 6 7 3][3 7 4 0][4 7 6 5]]def/R 20 def/H -3 def/ang 0 def
{300 700 translate 1 70 dup dup scale div setlinewidth
disp begin/cam[ang sin R mul H ang cos R mul]def/theta[ang H R atan 0]def/Rot makerot def end
fv{{v exch get proj}forall moveto lineto lineto lineto closepath 1 0 0 setrgbcolor fill}forall
fv{{v exch get proj} forall moveto lineto lineto lineto closepath 0 setgray stroke}forall
showpage/ang ang 3 add def}loop

```

Ungolfed and commented.

```
%!
/olddiv/div load def
/div{dup 0 eq{pop pop 100000}{olddiv}ifelse}def
(mat.ps)run

/disp <<
    /cam [ 0 0 10 ] % Camera position
    /theta [ 0 0 0 ] % Rotation sequence
    /eye [ 0 0 20 ] % Eye relative to image surface
    /Rot 3 ident
>> def

/makerot {
    theta 0 get roty
    theta 1 get rotx matmul
    theta 2 get rotz matmul
} def

% Ax Ay Az
/proj { DICT begin
    %3 array astore
    %dup == flush
    cam {sub}vop %Camera translation
    %pstack()=
    Rot matmul %Camera rotation
    0 get aload pop % Dx Dy Dz
    eye aload pop % Dx Dy Dz Ex Ey Ez
    %pstack()=
    4 3 roll div % Dx Dy Ex Ey Ez/Dz
    exch neg % Dx Dy Ex Ez/Dz -Ey
    4 3 roll add % Dx Ex Ez/Dz Dy-Ey
    1 index mul % Dx Ex Ez/Dz Ez(Dy-Ey)/Dz
    4 1 roll 3 1 roll % Ez(Dy-Ey)/Dz Ez/Dz Dx Ex
    sub mul exch % Ez(Dx-Ex)/Dz Ez(Dy-Ey)/Dz
    %pstack ()=
end } dup 0 disp put def

/v [[  1  1  -1 ] %cube vertices
    [ -1  1  -1 ]
    [ -1 -1  -1 ]
    [  1 -1  -1 ]
    [  1  1   1 ]
    [ -1  1   1 ]
    [ -1 -1   1 ]
    [  1 -1   1 ]] def
/fv [[ 0 1 2 3 ] %cube faces out of vertices
     [ 0 4 5 1 ]
     [ 1 5 6 2 ]
     [ 2 6 7 3 ]
     [ 3 7 4 0 ]
     [ 4 7 6 5 ]
     ] def

/R 20 def
/H -3 def
/ang 0 def

{
    300 700 translate
    1 70 dup dup scale div setlinewidth

    disp begin
        /cam [ ang sin R mul  H  ang cos R mul ] def
        /theta [ ang  H R atan  0 ] def
        /Rot makerot def
    end

    fv {
        { v exch get proj } forall
        moveto lineto lineto lineto closepath
        1 0 0 setrgbcolor fill
    } forall

    fv {
        { v exch get proj } forall
        moveto lineto lineto lineto closepath
        0 setgray stroke
    } forall

    showpage
    /ang ang 3 add def
} loop

```

# Answer
> 0 votes
## RBX.Lua, 83 bytes

```
s=Instance.new("Part",workspace)s.BrickColor=BrickColor.new(21)s.Size=Vector3.new()

```

Result:

Explanation:

```
s=Instance.new("Part",workspace)  Instances a new Brick in the world.
s.BrickColor=BrickColor.new(21)   Makes it red. 21 is the color code for "Bright red".
s.Size=                           We have to set the size, because a brick isn't cubic.
Vector3.new()                     Initiates a [0, 0, 0] size. The brick rounds this up
                                  to the minimum size.

```

---
Tags: code-golf
---


# Question
Title: Bridges are metaphors for everything in ASCII Art
*(with apologies to Jim West for the title, and randomly inspired by Cisco's textual representation of their logo:* `.:|:.:|:.` *for the concept)*

Given an input integer `1 <= n <= 255`, output an ASCII art representation of a suspension bridge of distance `n` following the below construction rules:

* The start and end of the bridge (not counted in the `n` distance) are always `-|` and `|-`, so the bridge can appropriately connect to the highways next to it.
* The bridge doesn't extend downward (the roadway level, composed of the `-` row, is the bottom row).
* There can be at most two roadway pieces `--` in a row, any longer span requires suspension cables for support.
* The suspension cables `\` extend from the roadway up to the towers `|` in straight lines.
* The towers `|` must be tall enough to support the adjacent suspension cables, but no taller.
* The bridge must be balanced left-to-right about the middle point, favoring the center sections whenever possible.
* All of the above should result in a minimization of the cables, but just to be clear, the number of suspension cables must be minimized while still following the above rules.

To provide a visual representation, here are the expected outputs for `n = 1, 2, 3, ... 15` --

```
1
-|-|-

2
-|--|-

3
-|\-/|-

4
-|\--/|-

5
 |\   /|
-|-\-/-|-

6
 |\    /|
-|-\--/-|-

7
 |\     /|
 | \   / |
-|--\-/--|-

8
 |\      /|
 | \    / |
-|--\--/--|-

9
 |\       /|
 | \     / |
 |  \   /  |
-|\--\-/--/|-

10
 |\        /|
 | \      / |
 |  \    /  |
-|\--\--/--/|-

11
 |\         /|
 | \       / |
 |  \     /  |
 |\  \   /  /|
-|-\--\-/--/-|-

12
 |\          /|
 | \        / |
 |  \      /  |
 |\  \    /  /|
-|-\--\--/--/-|-

13
 |\           /|
 | \         / |
 |  \       /  |
 |\  \     /  /|
 | \  \   /  / |
-|--\--\-/--/--|-

14
 |\            /|
 | \          / |
 |  \        /  |
 |\  \      /  /|
 | \  \    /  / |
-|--\--\--/--/--|-

15
 |\             /|
 | \           / |
 |  \         /  |
 |\  \       /  /|
 | \  \     /  / |
 |  \  \   /  /  |
-|\--\--\-/--/--/|-

```

### Input

A single positive integer in any convenient format, `n > 9`.

### Output

The ASCII-art bridge following the above construction technique.

### Rules

* Leading or trailing newlines or whitespace are all optional, so long as the bridge characters themselves line up correctly.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 3 votes
# 05AB1E, ~~79~~ ~~59~~ 58 bytes

```
"\  "×¹<;£R.sð«¹3‹ið}.BvyD¹Éi¨}R„\/„/\‡«'|.øð.ø}ð'-‡¹2›i»}

```

Try it online!.

Explanation:

```
"\  "×                                                     # Push n copies of "\  ".
      ¹<;£                                                 # Push a[0:(n-1)/2]
          R.s                                              # Reverse, get substrings.
             ð«                                            # Append a space.
               ¹3‹ið}                                      # If n < 3, push a space.
                     .B                                    # Boxify.
                       vy                      }           # For each...
                         D¹Éi¨}R                           # Dupe, if n is odd, a[0:-1].
                                „\/„/\‡                    # Reverse the slashes.
                                       «'|.øð.ø            # Surround with | and a space.
                                                ð'-‡       # Replace spaces with "-".
                                                    ¹2›i } # If it's more than 2...
                                                        »  # Join stack by newlines.

```

Found the better solution, the key was to return the following arrays for each number as follows:

```
1=[" "]
2=["  "]
3=["\"]
4=["\ "]
5=["\"," \"]
6=["\"," \ "]
7=["\"," \","  \"]
8=["\"," \","  \ "]
Etc...

```

# Answer
> 4 votes
## Python 2 , 173 bytes

```
i=input()
f=lambda b:'-|'+b[::-1].replace('/','\\')+-~(~i%2)*'-'+b+'|-'
b=(i*'/--')[:~-i/2]
for x in range(1,~-i/2):print f((len(b)-x)*'-'+b[:x]).replace('-',' ')
print f(b)

```

Mirror the value of b and add the central "-"
`f=lambda b:'-|'+b[::-1].replace('/','\\')+-~(~i%2)*'-'+b+'|-'`
Base pattern (right half of the bottom line)
`b=(i*'/--')[:~-i/2]`
Loop for non-bottom layers
`for x in range(1,~-i/2):`
Get the first x characters of the base pattern and complete with "-"
`(len(b)-x)*'-'+b[:x]`
Replace all - with spaces to print all the layers (except bottom)
`print f().replace('-',' ')`
Print bottom layer
`print f(b)`

# Answer
> 4 votes
# Befunge, 150 bytes

```
45&3+:00p4+2/:10p`-v
*\00g1-\`*2*+\1-!+v>1+:20p55+00g>::::00g1--!\:20g+00g-:0`\3%!
`1\*!%3\`0:-\g02:\<^_@#-g01<:,$_^#`\0:-1,g3+**4!-g01g02!:+*3*
 |\/-

```

Try it online!

I've also provided an ungolfed version of the code which better demonstrates the architecture used in the construction of the bridge.

```
        >4                                         5v
        v+3                                       <&<
        >:00                                     p4+v
        v-`p0                                   1:/2<
*+\1-!+v>1+:20p55+00g>::::00g1--!\:20g+00g-:0`\3%!*\00g1-\`*2
-\g02:\<^_@#-g01<:,$_^#`\0:-1,g6+7+**4!-g01g02!:>#+<v*!%3\`0:
        |\/->3#*                             *#`^#1\<

```

Try it online!

The towers handle the input and parameter initialisation. The deck is made up two loops calculating the parts of the bridge that need to be output for each x,y coordinate. And the foundation holds the character table for the those bridge parts, as well as some other completely unrelated code.

**Detailed Explanation**

We start by calculating the width and height of the output area that will need to be iterated in order to render the bridge.

```
w  = n + 3                (stored at 0,0)
h  = (w + 4)/2            (stored at 1,0)

```

Note that the *y* range is not zero-based. The initial value is `5 - (h<5)` and is iterated up to *h* (the current value is stored at 2,0). The *x* value is iterated from *w* down to 0 and is stored on the stack.

The inner loop is just a series of boolean conditions determining whether a particular *x*,*y* coordinate matches any of the locations that require a non-space character. These calculations are based on two sliding offsets that follow the path of the suspension cables.

```
loff = y + x - w
roff = y - x

```

The various conditions are then determined as follows:

```
left_tower       = (x == w-1)
left_suspension  = (loff > 0) and (loff%3 == 0) and (x < w-1)
right_tower      = (x == 1)
right_suspension = (roff > 0) and (roff%3 == 0) and (x > 1)
bridge_deck      = (y == h)

```

To translate these conditions into the correct character offset, we just need to multiply each of them by an appropriate offset and sum the result. This calculation is performed as the conditions are evaluated. So it looks something like this:

```
char_offset =  left_tower
char_offset += left_suspension * 2
char_offset += right_tower
char_offset += right_suspension * 3
char_offset += !char_offset * bridge_deck * 4

```

Note that the *bridge\_deck* value is merged in based on whether any of the other conditions have been met, since a suspension or tower character will take precedence over the deck.

The end result is an offset into the character table on the last line of the playfield. We simply output that character and repeat the loop.

# Answer
> 3 votes
## Batch, 241 bytes

```
@echo off
set t=set s=
%t%
for /l %%i in (1,1,%1)do call %t% %%s%%
%t% !%s%!
for /l %%i in (5,2,%1)do call:l 0
:l
%t%%s:\ = \%
%t%%s: /=/ %
%t%%s:!   =!\  %
%t%%s:   !=  /!%
%t%%s:\  !=\ /!%
if %1 gtr 0 %t%%s: =-%
echo %s:!=^|%

```

Note: Trailing space on line 5. Starts by building up a row of spaces, then adding cables as necessary, repeating to build towers to the desired height, ending by replacing any remaining spaces with road.

# Answer
> 3 votes
# WinDbg, 312 bytes

```
r$t4=@$t0+4;.block{j3>@$t0'r$t5=1';r$t5=(@$t0-1)/2};f8<<16 L@$t4*@$t5 2d;f8<<16 L@$t4*(@$t5-1) 20;.for(r$t1=0;@$t1<@$t5;r$t1=@$t1+1){eb2000001+@$t4*@$t1 7c;e1fffffe+@$t4*(1+@$t1) 7c;j2<@$t0'.for(r$t2=@$t1;@$t2>=0;r$t2=@$t2-3){e2000002+@$t4*@$t1+@$t2 5c;e1fffffd+@$t4*(1+@$t1)-@$t2 2f}'};da/c@$t4 8<<16 L@$t4*@$t5

```

Input is done by setting the pseudo-register `$t0`.

I feel like there should be a way to combine the two `for` loops into one... maybe some other golfing opportunities too...

This one works by filling the entire area with road, then replacing all but the last row with space, and finally building the columns and cables.

```
r$t4 = @$t0+4;                                * Set width to input+4
.block                                        * Code block, needed for some reason...
{                                             * and .block+j is shorter than .if/.else
    j 3>@$t0                                  * If input is less than 3...
    '
        r$t5 = 1                              * ...set height to 1
    ';                                        * Implicit else...
        r$t5 = (@$t0-1)/2                     * ...set height to (input-1)/2
};
f 8<<16 L@$t4*@$t5 2d;                        * Fill area with -
f 8<<16 L@$t4*(@$t5-1) 20;                    * Fill all but last row with space
.for(r$t1=0; @$t1<@$t5; r$t1=@$t1+1)          * For each row
{
    eb 2000001+@$t4*@$t1 7c;                  * Build the left column with |
    e 1fffffe+@$t4*(1+@$t1) 7c;               * Build the right column (e is the same as last e* call, ie- eb)
    j 2<@$t0                                  * If input is more than 2...
    '
        .for(r$t2=@$t1; @$t2>=0; r$t2=@$t2-3) * ...Enumerate from counter back to 0
        {
            e 2000002+@$t4*@$t1+@$t2 5c;      * Build left cables with \
            e 1fffffd+@$t4*(1+@$t1)-@$t2 2f   * Build right cables with /
        }
    '
};
da /c@$t4 8<<16 L@$t4*@$t5                    * Print the string in lines of length width

```

Sample output of 1-15:

```
0:000> .for(r$t0=1;@$t0<10;r$t0=@$t0+1){.printf"%d\n",@$t0;r$t4=@$t0+4;.block{j3>@$t0'r$t5=1';r$t5=(@$t0-1)/2};f8<<16 L@$t4*@$t5 2d;f8<<16 L@$t4*(@$t5-1) 20;.for(r$t1=0;@$t1<@$t5;r$t1=@$t1+1){eb2000001+@$t4*@$t1 7c;e1fffffe+@$t4*(1+@$t1) 7c;j2<@$t0'.for(r$t2=@$t1;@$t2>=0;r$t2=@$t2-3){e2000002+@$t4*@$t1+@$t2 5c;e1fffffd+@$t4*(1+@$t1)-@$t2 2f}'};da/c@$t4 8<<16 L@$t4*@$t5}
1
Filled 0x5 bytes
Filled 0x0 bytes
02000000  "-|-|-"
2
Filled 0x6 bytes
Filled 0x0 bytes
02000000  "-|--|-"
3
Filled 0x7 bytes
Filled 0x0 bytes
02000000  "-|\-/|-"
4
Filled 0x8 bytes
Filled 0x0 bytes
02000000  "-|\--/|-"
5
Filled 0x12 bytes
Filled 0x9 bytes
02000000  " |\   /| "
02000009  "-|-\-/-|-"
6
Filled 0x14 bytes
Filled 0xa bytes
02000000  " |\    /| "
0200000a  "-|-\--/-|-"
7
Filled 0x21 bytes
Filled 0x16 bytes
02000000  " |\     /| "
0200000b  " | \   / | "
02000016  "-|--\-/--|-"
8
Filled 0x24 bytes
Filled 0x18 bytes
02000000  " |\      /| "
0200000c  " | \    / | "
02000018  "-|--\--/--|-"
9
Filled 0x34 bytes
Filled 0x27 bytes
02000000  " |\       /| "
0200000d  " | \     / | "
0200001a  " |  \   /  | "
02000027  "-|\--\-/--/|-"
10
Filled 0x38 bytes
Filled 0x2a bytes
02000000  " |\        /| "
0200000e  " | \      / | "
0200001c  " |  \    /  | "
0200002a  "-|\--\--/--/|-"
11
Filled 0x4b bytes
Filled 0x3c bytes
02000000  " |\         /| "
0200000f  " | \       / | "
0200001e  " |  \     /  | "
0200002d  " |\  \   /  /| "
0200003c  "-|-\--\-/--/-|-"
12
Filled 0x50 bytes
Filled 0x40 bytes
02000000  " |\          /| "
02000010  " | \        / | "
02000020  " |  \      /  | "
02000030  " |\  \    /  /| "
02000040  "-|-\--\--/--/-|-"
13
Filled 0x66 bytes
Filled 0x55 bytes
02000000  " |\           /| "
02000011  " | \         / | "
02000022  " |  \       /  | "
02000033  " |\  \     /  /| "
02000044  " | \  \   /  / | "
02000055  "-|--\--\-/--/--|-"
14
Filled 0x6c bytes
Filled 0x5a bytes
02000000  " |\            /| "
02000012  " | \          / | "
02000024  " |  \        /  | "
02000036  " |\  \      /  /| "
02000048  " | \  \    /  / | "
0200005a  "-|--\--\--/--/--|-"
15
Filled 0x85 bytes
Filled 0x72 bytes
02000000  " |\             /| "
02000013  " | \           / | "
02000026  " |  \         /  | "
02000039  " |\  \       /  /| "
0200004c  " | \  \     /  / | "
0200005f  " |  \  \   /  /  | "
02000072  "-|\--\--\-/--/--/|-"

```

# Answer
> 2 votes
# Java 8, 423, 412 bytes

11 bytes saved thanks to Kritixi Lithos

golfed:

```
void f(int n){int i,j,k,t=n/2+n%2,u=t-2,q;char v=45;char[][]a=new char[t-1][n+4];for(char[]c:a)Arrays.fill(c,' ');a[u][0]=v;a[u][n+3]=v;for(q=0;q<t-1;q++){a[q][1]='|';a[q][n+2]='|';}for(i=t+1;i>1;i--){if((t-i)%3==0){k=u;for(j=i;j>1;j--)a[k--][j]='\\';}else a[u][i]=v;}for(i=n/2+2;i<n+2;i++){if((i-n/2-3)%3==0){k=u;for(j=i;j<n+2;j++)a[k--][j]='/';}else a[u][i]=v;}for(char[]w:a)System.out.println(new String(w));}

```

ungolfed:

```
void f(int n){
    int i,j,k,t=n/2+n%2,u=t-2;
    char v=45;
    char[][] a=new char[t-1][n+4];
    for (char[]c : a) Arrays.fill(c,' ');
    a[u][0]=v;
    a[u][n+3]=v;

    // left and right columns
    for (int q=0;q<t-1;q++){
        a[q][1]='|';
        a[q][n+2]='|';
    }
    // left part of base
    for (i=t+1;i>1;i--){
        if ((t-i)%3==0){
            k=u;
            for (j=i;j>1;j--)
                a[k--][j]='\\';
        }
        else a[u][i]=v;
    }
    // right part of base
    for (i=n/2+2;i<n+2;i++){
        if ((i-n/2-3)%3==0){
            k=u;
            for (j=i;j<n+2;j++)
                a[k--][j]='/';
        }
        else a[u][i]=v;
    }
    for (char[]w : a) System.out.println(new String(w));
}

```

---
Tags: code-golf, ascii-art
---