title: Shoot the ASCII Moon

text:
# Question
Title: Shoot the ASCII Moon
(Previously on "Print the \__ without using \__" ... this one and this one)

The game of Hearts has a popular scoring variant called "Shooting the Moon," whereby instead of trying to not acquire penalty cards (and thus penalty points), as is the usual gameplay strategy, if you acquire *all* of the penalty cards you actually score the best that round. We're going to apply that same logic to some code golf.

The ASCII printable characters (plus space) are, in order

```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

```

Let's divide these into three groups:

Alphanumeric:

```
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

```

Symbolic (or non-alphanumeric)

```
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

```

and the space character.

Your task is to use the alphanumeric characters to print the symbolic characters (in any order), with the following restrictions:

* The program/function should take no input and output to STDOUT (or equivalent).
* You can use a symbolic character in your source code for a penalty of +5 per unique character.
* Using the same character more than once does not increase your penalty (e.g., you can use `[` 25 times and only get one +5 penalty)
* Whitespace (including tabs and newlines) in the output or the source code is completely optional. Leading, trailing, inline - no penalties or bonuses. They still count for bytes in source code as usual.
* If you manage to use all 32 symbolic characters in your code, you get a bonus of -100 points for **Shooting the Moon** instead of any penalties.
* If you manage to use all 32 symbolic *and* all 62 alphanumeric characters in your code, you instead get a bonus of -250 points for **Shooting the Sun** instead of any penalties.
* Characters inside literal strings, literal characters, or comments do not count for the bonus or the penalty. (E.g., a Foo program of something like `"!#$%..."` would be allowed, but would not get the bonus or penalty points for the characters inside the literal).
* Literal string or comment *delimiters* do count, however, so something like `// !#$*...` would count the initial `/` for penalty/bonus calculations.
* Yes, this rules out languages like Whitespace or the like, where everything not whitespace is treated as a comment. Bummer.
* Scoring is `bytes of code` \+ `penalty(ies)` \+ `bonus(es)`, lowest score wins. Negative scores are possible.

### Example scores:

50 bytes code + (5 unique symbolic characters)\*5 penalty each = 75 points

200 bytes code + (32 unique symbolic characters)\*0 penalty each + (-250 bonus for shooting the sun) = -50 points

# Answer
> 13 votes
# GolfScript, -153

```
{""''!$%&()*+,-./:;<=>?@[\]^_`|~#
}ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

```

Prints

```
{""''!$%&()*+,-./:;<=>?@[\]^_`|~#
}

```

Score:

* 97 bytes of source code: **+97**
* Shooting the Sun: **-250**

Try it online.

### How it works

Since the code block (lambda, anonymous function)

```
{""''!$%&()*+,-./:;<=>?@[\]^_`|~#
}

```

does not contain any syntax errors, it will be pushed on the stack and printed verbatim if left on it. The linefeed is required to end the comment that `#` started.

Finally, `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789` is an undefined token; it does nothing.

# Answer
> 10 votes
# C++, 310

Well, I started this without realizing that `@` and backticks are totally disallowed in C++ source. Posting it even though it's a very poor entry as it stands, in case anybody knows a way out. Is there a compiler that would allow these characters in symbol names?

```
#include<IOSTREAM>
int main(int bgjkpqvwxyzBCDFGHJKLNPQUVWXYZ$){\
for(char _='!';_<127;++_){_==48?_=58:_==65||_==98-1.?_+=26:!~_^_&_*_%3,""[0];std::cout<<_;}}//

```
* 160 bytes
* 5 * 30 unique symbolic characters = 150 point penalty

---

# Edit: -90

Leaving the above because it's a little more interesting than the following, which uses an unused `#define` to sneak in the missing symbols.

```
#include<IOSTREAM>
#define bgjkpqvwxyzBCDFGHJKLNPQUVWXYZ !"#$%&'*,-./@[\]^`~
int main(){for(char _=33;_<127;++_){_==48?_=58:_==65||_==97?_+=26:_;std::cout<<_;}}

```
* 160 bytes
* Shooting the sun, -250 points

# Answer
> 9 votes
# CJam, -66

```
{'"#$%&()*.+,-/:!;<=>?@[\]^_`|~}""

```

Prints every symbol exactly once, without any extraneous whitespace.

Score:

* 34 bytes of source code: **+34**
* Shooting the Moon: **-100**

Try it online.

### How it works

Since the code block (lambda, anonymous function) `{'"#$%&()*.+,-/:!;<=>?@[\]^_`|~}` does not contain any syntax errors, it will be pushed on the stack and printed verbatim if left on it.

Since `"` only appears in the character literal `'"`, we also push an emoty string as `""`, which won't affect the output.

# Answer
> 5 votes
# Ruby, -148

```
p %w{!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnoqrstuvxyz}[0]

```

Results in:

```
"!\"\#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"

```

Produces an array, takes the special characters and inspects them.

102 (bytes) + 0 (penalty) - 250 (shot the sun) = **-148 points**

# Answer
> 4 votes
# Befunge-93, -125

Since having code that is never reached is OK, this is deemed an allowed answer.

```
p>g1g:,"}"`#@_g1+00p           #
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
23456789ABCDEFGHIJKLMNOPQRSTUVWX
YZabcdefhijklmnoqrstuvwxyz

```

it's 125 - 250, so -125. I tried to avoid reading the characters in string mode as that seems to violate the rules, but I don't see any violation here. I just read what every character is in the 1st row until it's ascii value is \>125. I had to change it a bit to have it run properly in the interpreter

# Answer
> 3 votes
## STATA, -120

```
#d 01256789ABCDEFGHIJKLMNOPQRSTUVWXYZbefgjklmnopqstuvwxyz`!$%&*+,-./:<=>?@[\]^_{|}~'
di "'`!#$%&()*+,-./:;<=>?@[\]^_{|}~"char(34);

```

Abuses the standard STATA interpreter. The `#d` command (short for `#delimit`) changes the delimiter to ; unless whatever follows the command is "cr". But the spec only specifies what happens when what follows is ";" or "cr".

Score:

* 130 bytes of source code: **+130**
* Shooting the Sun: **-250**

# Answer
> 3 votes
# Beam, ~~-34~~ -47

Now that I've fixed my initial misunderstanding, now to try and get some points back:)

```
'''''>`+++++++)--'''''>`@+@+@+vabcdefghi
/+++)++@+@+@+@+@+@\012^   _?Ps)klmopqrtw
+3456789ABv+@+@`<'''++++++++++<!"#$%&*,.
|CDEFGIJKL(     ^Z\''''>`+++++)+\=@[]{}~
\+`<'''''@<MNOQRSTUVWXYH@+@+@+@+/:;xyzj

```

Using the same logic for scoring as the Befunge-93 answer. 216 Bytes - 250 Shooting the Sun. Now to see if I can compact it a bit more and improve my logic.

Brief explanation:

```
var ITERS_PER_SEC = 100000;
var TIMEOUT_SECS = 50;
var ERROR_INTERRUPT = "Interrupted by user";
var ERROR_TIMEOUT = "Maximum iterations exceeded";
var ERROR_LOSTINSPACE = "Beam is lost in space";
var code, store, beam, ip_x, ip_y, dir, input_ptr, mem;
var input, timeout, width, iterations, running;
function clear_output() {
document.getElementById("output").value = "";
document.getElementById("stderr").innerHTML = "";
}
function stop() {
running = false;
document.getElementById("run").disabled = false;
document.getElementById("stop").disabled = true;
document.getElementById("clear").disabled = false;
document.getElementById("timeout").disabled = false;
}
function interrupt() {
error(ERROR_INTERRUPT);
}
function error(msg) {
document.getElementById("stderr").innerHTML = msg;
stop();
}
function run() {
clear_output();
document.getElementById("run").disabled = true;
document.getElementById("stop").disabled = false;
document.getElementById("clear").disabled = true;
document.getElementById("input").disabled = false;
document.getElementById("timeout").disabled = false;
code = document.getElementById("code").value;
input = document.getElementById("input").value;
timeout = document.getElementById("timeout").checked;
code = code.split("\n");
width = 0;
for (var i = 0; i < code.length; ++i){
 if (code[i].length > width){
  width = code[i].length;
 }
}
console.log(code);
console.log(width);
running = true;
dir = 0;
ip_x = 0;
ip_y = 0;
input_ptr = 0;
beam = 0;
store = 0;
mem = [];
input = input.split("").map(function (s) {
  return s.charCodeAt(0);
 });
iterations = 0;
beam_iter();
}
function beam_iter() {
while (running) {
 var inst;
 try {
  inst = code[ip_y][ip_x];
 }
 catch(err) {
  inst = "";
 }
 switch (inst) {
  case ">":
   dir = 0;
   break;
  case "<":
   dir = 1;
   break;
  case "^":
   dir = 2;
   break;
  case "v":
   dir = 3;
   break;
  case "+":
   ++beam;
   break;
  case "-":
   --beam;
   break;
  case "@":
   document.getElementById("output").value += String.fromCharCode(beam);
   break;
  case ":":
   document.getElementById("output").value += beam;
   break;
  case "/":
   dir ^= 2;
   break;
  case "\\":
   dir ^= 3;
   break;
  case "!":
   if (beam != 0) {
    dir ^= 1;
   }
   break;
  case "?":
   if (beam == 0) {
    dir ^= 1;
   }
   break;
  case "_":
   switch (dir) {
   case 2:
    dir = 3;
    break;
   case 3:
    dir = 2;
    break;
   }
   break;
  case "|":
   switch (dir) {
   case 0:
    dir = 1;
    break;
   case 1:
    dir = 0;
    break;
   }
   break;
  case "H":
   stop();
   break;
  case "S":
   store = beam;
   break;
  case "L":
   beam = store;
   break;
  case "s":
   mem[beam] = store;
   break;
  case "g":
   store = mem[beam];
   break;
  case "P":
   mem[store] = beam;
   break;
  case "p":
   beam = mem[store];
   break;
  case "u":
   if (beam != store) {
    dir = 2;
   }
   break;
  case "n":
   if (beam != store) {
    dir = 3;
   }
   break;
  case "`":
   --store;
   break;
  case "'":
   ++store;
   break;
  case ")":
   if (store != 0) {
    dir = 1;
   }
   break;
  case "(":
   if (store != 0) {
    dir = 0;
   }
   break;
  case "r":
   if (input_ptr >= input.length) {
    beam = 0;
   } else {
    beam = input[input_ptr];
    ++input_ptr;
   }
   break;
  }
 // Move instruction pointer
 switch (dir) {
  case 0:
   ip_x++;
   break;
  case 1:
   ip_x--;
   break;
  case 2:
   ip_y--;
   break;
  case 3:
   ip_y++;
   break;
 }
 if (running && (ip_x < 0 || ip_y < 0 || ip_x >= width || ip_y >= code.length)) {
  error(ERROR_LOSTINSPACE);
 }
 ++iterations;
 if (iterations > ITERS_PER_SEC * TIMEOUT_SECS) {
  error(ERROR_TIMEOUT);
 }
}
}
```

```
<div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;">Code:<br><textarea id="code" rows="4" style="overflow:scroll;overflow-x:hidden;width:90%;">'''''>`+++++++)--'''''>`@+@+@+vabcdefghi
/+++)++@+@+@+@+@+@\012^   _?Ps)klmopqrtw
+3456789ABv+@+@`<'''++++++++++<!"#$%&*,.
|CDEFGIJKL(     ^Z\''''>`+++++)+\=@[]{}~
\+`<'''''@<MNOQRSTUVWXYH@+@+@+@+/:;xyzj
</textarea><p>Timeout:<input id="timeout" type="checkbox" checked="checked"> <br><br><input id="run" type="button" value="Run" onclick="run()"><input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="disabled"><input id="clear" type="button" value="Clear" onclick="clear_output()">  <span id="stderr" style="color:red"></span></p>Output:<br><textarea id="output" rows="6" style="overflow:scroll;width:90%;">        </textarea><br>Input:<br><textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;"></textarea></div>
```

# Answer
> 2 votes
# PHP, 154 - 250 = -96

Requires error reporting to be off. I hope I'm not breaking the rules by adding the dead code between `$a=33` and `;$a<65`.

```
<?php #
Z:for($a=33,$ABCDEFGHIJKLMNOPQRSTUVWXYdgijklmnqstuvwxyz_=@``.[!-0/~9%8^3|0&0].''."";$a<65;$a++){echo chr($a+10*($a>47)+26*($a>54)+26*($a>60));}\b;

```

# Answer
> 2 votes
## Tcl, 135-250 = -115

```
set {123456789ABCDEFGHIJKLMNOPQRSTUVXYZbcdhkmqwyz!"#$%&'()*+,-./:;<=>?@[\]^`|~} 0
puts [join [regexp -inline -all {\W+} [info vars]]]_

```

Explanation: Create a variable named `{123456789ABCDEFGHIJKLMNOPQRSTUVXYZbcdhkmqwyz!"#$%&'()*+,-./:;<=>?@[\]^|~}` (basically the entire ASCII sequence minus some alphanumeric characters already in the source) then get the list of all variables in scope (`info vars`) and use regexp to filter out the non-symbols form the resulting list. I believe a variable name qualifies as something that's not a string literal. This is possible because Tcl allows almost any byte sequence for variable and function names (including symbols and even non-printing characters).

Note: Strictly speaking, it's a string literal, which is why it's quoted in `{}` (tcl has two ways of quoting strings: `{}` and `""`). But in tcl, everything is a string literal including the entire program. Tcl is a string-based language after all. So I'm interpreting the "string literal" specification as: "string literal" when used as data.

# Answer
> 2 votes
# Ruby, -126

Nothing in string literals or comments. The output ain't pretty since it's `p`-ing an array of strings, but it's all there.

```
p @bdefgjkoqstuvwyz_BCDHJKLMPQSTUWXYZ=[*32..47,*58..64,*91..96,*123..126].map!{|x|x.chr};+-~0?"":(``%nil<$\>''^ARGF/IO&ENV)#

```

Score:

* Bytes: **+124**
* Shot the sun: **-250**

# Answer
> 2 votes
# FORTH, -118

```
: !#$%&'()*+,-/0123456789=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|} ." !\q#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ " ;

```

Forth names are only delimited by whitespace, so the name is just all the shoot the sun characters minus : ." and ;

* Code: 132
* Shoot the sun: -250

# Answer
> 1 votes
# Batch, -143 bytes

```
@echo !"#$%%&'()*+,-./:;<=>?@[\]^_`{|}~
@goto :a
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZbdfijklmnpqrsuvwxyz
:a

```
* 107 bytes of source code: **+107**
* Shooting the Sun: **-250**

I didn't think this would beat anyone. After all it's batch!

# Answer
> 1 votes
# Haskell, -135

```
main=putStr$!do{(x,y)<-"!:[{"`zip`"/@`~";[x..y]}
veRbOsE#%&*+/:>?@\^|~_0123456789ABCDFGHIJKLMNPQTUVWXYZcfghjklqw'=0

```

Score:

* 115 bytes
* -250 shooting the sun bonus

After re-reading I think dead code was ok so this version is shorter. The main function is borrowed from @xnor's answer to this question. It basically takes the endpoints and zips them pairwise to transforms them into ranges, being equal to

```
putStr(concatMap (\(x,y)->[x..y]) [('!','/'),(':','@'),('[','`'),('{','~')])

```

The other line just defines an unused operator `#%&*+/:>?@\^|~` with long parameter names.

`(),;[]`{}"'_` are the special characters that can't be used in operator names but `_` and `'` can be used variable names. The others are all used in the first line.

Try it online!

# Answer
> 0 votes
# MS-SQL, 133 bytes - 250 bonus = -117

```
create TABLE[!"#$%&'()*+,-./:;<=>?@[\]]^_`{|}~](DdfGgHiJkPpQqUuVvWXYZz0123456789 xml)
SELECT NAME FROM sys.objects where name LIKE'!%'

```

Uses a system view specific to MS SQL, so not guaranteed to work on other platforms.

Creates a table with a name consisting of the 32 symbols in order. This is normally invalid for a SQL identifier, but we can make it work by surrounding it by brackets. This name is then retrieved from system view `sys.objects` (assuming that no other tables start with `!`).

Alphanumerics not used elsewhere make up the (unused) xml field name.

Make sure to clean up the table when you are done! (not included in score):

```
DROP TABLE[!"#$%&'()*+,-./:;<=>?@[\]]^_`{|}~]

```

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


# Question
Title: Print strings without sharing characters
**Edit: Allowed to reuse whitespaces.**

Your task is to write *n* programs (or functions, or bodies of functions without using parameters or the function names) in the same language. The *k*th program should output the (cardinal) number *k* in standard English in lowercase (with an optional trailing newline). So the first program should output `one`, the second should output `two`, etc. For a number having two parts, they should be separated by a hyphen like `twenty-one`.

But no two programs in your submission can share non-whitespace characters or whitespace characters doing useful works. For example, if your first program is just `"one"`, then none of `"` `o` `n` and `e` can be used again in your other programs.

You can use whitespace characters (spaces, newlines and tabs) in two or more programs, if they only serve as separators or indentation and don't do anything by themselves. So you can't reuse them in the Whitespace language, and you can't use them in strings in more than one program.

You can only use printable ASCII characters, tabs, and newlines (including CR and LF). Every program must contain at least 1 character.

Your score is the sum of 1/program size^1.5. Highest score wins. You can use this Stack Snippet (or this CJam code) to calculate your score:

```
function updatescore(a){var l=a.value.split("\n"),s=0;for(var i=0;i<l.length;i++){var t=l[i].length;t-=t&&l[i][t-1]=="\r";if(t)s+=Math.pow(t,-1.5);}document.getElementById('result').textContent=s;}
```

```
<textarea id="input" placeholder="Put your code here, one per line." style="width:100%;height:150px;box-sizing:border-box" oninput="updatescore(this)" onpropertychange="updatescore(this)"></textarea><div>Your score: <span id="result">0</span></div>
```

# Answer
> 6 votes
# gs2, 0.38669200758867045

Remove whitespace from all of these programs but **three**, it's only for *(coughs)* readability. **one** and **six** are gs2 programs that crash (by underflowing the stack), which conveniently makes them quines.

## one (3 bytes)

```
one

```

## two (1384 bytes)

```
A?"A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0
A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0
A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0
A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0
A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0
A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0000000000000
000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000A?"A"0A"0A"0A"0A
"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A
"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A
"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A
"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A
"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A
"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"00000000000000000000
000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000A?"A"0A"0A"0A"0A"0A"
0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"
0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"
0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"
0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"
0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"
0A"0A"0A"0A"000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000
0000

```

## three (92 bytes)

```
0a 21 2c 21 20 21 20 21 20 21 20 21 20 21 20 21
20 21 20 21 20 21 20 21 20 21 20 21 20 21 20 21
20 21 20 2f 20 0a 21 28 3c 0a 21 2c 21 20 21 20
21 20 21 20 2f 20 0a 21 28 3c 45 21 20 21 20 21
2f 20 0a 21 28 3c 0a 21 2c 21 20 2f 20 0a 21 28
3c 0a 21 2c 21 20 2f 20 0a 21 28 3c

```

Lots of significant whitespace so here's a hex dump. It has a single line feed character at the start:

```

!,! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! /
!(<
!,! ! ! ! /
!(<E! ! !/
!(<
!,! /
!(<
!,! /
!(<

```

## four (276 bytes)

```
f$f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$
31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$
31Mf$f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f
$f$31f$f$31Mf$f$f$31f$f$31f$f$31f$f$31f$f$31Mf$f$f$31f$f$31f
$f$31f$f$31f$f$31f$f$31f$f$31f$f$31M

```

## five (178 bytes)

```
hd+++&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&Khd+++&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&Khd+++&&&&&&&&&&&&&&&&&&&&
&&&&&&&Khd+++&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&K

```

## six (3 bytes)

```
six

```

# Answer
> 13 votes
# CJam, 0.24075

### Programs

```
BA1]100cf|
"two"
{hree}`W<7a.-
N)92+_9+_6+_2~+
S(84^I^U$F^X$G^Y$(
's'i'x

```

*Thanks to @user23013 for his suggestion to use `'` for **six**.*

### Output, length, score, used characters

```
one    10  0.03162          01       AB         ]    c f         |
two     5  0.08944  "                                     o  tw
three  13  0.02133        -.     7  <        W     `a e h  r    { }
four   15  0.01721      )+    2 6  9      N       _                ~
five   18  0.01309   $ (       4  8    FGI SU XY ^
six     6  0.06804    '                                  i  s  x

```

Verify the results yourself in the CJam interpreter.

# Answer
> 6 votes
## Insomnia, 0.100688383057110116

Just to get things started. It's very unlikely that this is going to win. Under the current scoring scheme, any language that can print `one` in 5 or less characters has overwhelming advantage.

### one (8 bytes, 0.04419417382415922)

```
uuyp>~p~

```

### two (9 bytes, 0.037037037037037035)

```
oeoojdoLj

```

### three (21 bytes, 0.010391328106475828)

```
*FFFFF
=
=z"
n=nnFzzB

```

### four (23 bytes, 0.009065844089438033)

```
)HGGGkGGGtGkGk<GGh$HGGt

```

# Answer
> 4 votes
# Headsecks, 0.044623631135793776

**Generated here**

This language is a simple BF substitution where the only thing that matters is the character value modulo 8.

Unfortunately, longer programs give a worse score, despite being able to get to **twelve**! (I could get higher if I could use non-printable ASCII, and Unicode.)

### one

```
##%%%%%%%&##$%&#&%&%%%%%%%%%&

```

### two

```
--------+--.+++,-..+++.--------.

```

### three

```
5555555535563334566555555555555633333333336555555555555566

```

### four

```
==;=====>;<=>>;;;;;;;;;>;;;;;;>===>

```

### five

```
EECEEEEEFCDEFFCCCFCEFCCCCCCDEFFCCEFCCCDEFF

```

### six

```
KKMMMMMMMMMNKKLMNKNMMMMMMMMMMNMKMMMNKLMNN

```

### seven

```
SSUUUUUUUUUVSSTUVSVSSSSSUVSSSTUVVSUUUVSTUVUVSSUVSSSTUVVSSSSSSSSSV

```

### eight

```
]][]]]]]^[\]^]^[[[[^]]^[^[[[[[[[[[[[[^

```

### nine

```
cceeeeeeefccdeffeeeeefcccccfeeeeeeeeef

```

### ten

```
mmmmmmmmkmmnkkklmnnkkkkmnkkklmnnkkkkkkkkkn

```

### eleven

```
uusuuuuuvstuvuvsssssssvuuuuuuuvsuuuvstuvuvssuvssstuvvsssssssssv

```

### twelve

```
}}}}}}}}{}}~{{{|}~~{{{~{}~{{{|}~~{{{{{{{~{{{{{{{{{{~{{}~{{{|}~~

```

# Answer
> 2 votes
## ///, 0.19245008972987526

```
one

```

This answer is inspired by @n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳'s answer, in which he said

> Under the current scoring scheme, any language that can print `one` in 5 or less characters has overwhelming advantage.

# Answer
> 0 votes
# SmileBASIC, .10062

### "one"

```
?"one

```

### "two"

```
PRINT MID$(@two,1,3)

```

My other answer is more interesting, but this one gets a higher score.

An important strategy to get the longest chain is to use MORE characters to save on UNIQUE characters (for example, using `x - -x` in program 2 to save `y + y` for program 3)

The problem with the scoring system is that it scores 2 short programs better than 3 long programs, so there is no reason to save characters for later programs if it makes the current program longer.

Also, it values individual short programs higher than a smaller TOTAL size. If I swap `?` and `PRINT` in my answer I can save 1 character, but my score is HALF as much.

I think it would've been better to base it only on *number* of programs, with total size as a tiebreaker.

---
Tags: code-challenge, restricted-source, printable-ascii
---


title: Solve a Rubik's Cube

text:
# Question
Title: Solve a Rubik's Cube
Your challenge is to write a program to solve a 3x3x3 Rubik's Cube. This challenge is based on this one from 2013, rewritten to adhere to current community standards, and reposted with the original author's permission and help on meta.

# Input

The input should represent an unsolved Rubik's Cube. You may read this input via any standard means, and the input can be in any format you choose, except a sequence of moves to get the cube to an unsolved state (or anything similar); that would trivialize this challenge.

That means that the input can look like this:

```
    UUU
    UUU
    UUU
 LLLFFFRRRBBB
 LLLFFFRRRBBB
 LLLFFFRRRBBB
    DDD
    DDD
    DDD

```

`U` representing cubies on the top/upper face, `L` representing the left, etc.

It could also look like a Cubically cube-dump, an array of characters/integers, or the weird format in the original challenge; however you like. You must specify how input should be taken in your answer.

You can translate a cube-dump to an `ULFRBD` scheme here or the other way around here.

# Output

You will output, via any allowed means, the moves that must be performed on the inputted Rubik's Cube to return it to the solved state. You may use any chosen notation or method to describe rotation; please specify what you use in your answer.

I recommend that you use Singmaster's notation as it is the simplest and clearest:

```
R - turn the right face of the cube 90 degrees clockwise
L - turn the left face of the cube 90 degrees clockwise
U - turn the top face of the cube 90 degrees clockwise
D - turn the bottom face of the cube 90 degrees clockwise
F - turn the front face of the cube 90 degrees clockwise
B - turn the back face of the cube 90 degrees clockwise

```

Append `'` to any move to make it counterclockwise and `2` to any move to make it 180 degrees.

If you are unsure of the validity of an I/O method, feel free to comment or ping me in chat.

# Examples

Input is in the format of a cube-dump and a `ULFRBD` layout; output is in Singmaster's notation.

Input -\> `D'U'R'L'R'L2R'F2U'D'U'D'LR'B'F'U'D'L2R'`
Input -\> `RF2U2R2ULB2R2U2R'L'DB2U2D2B'R'F'B2DFU2RU2L'`
Input -\> `L2FL'R'FB'U2D'F'R'LBF2R2L'F2D2BL2F2RU2D'LF'`
Input -\> `B'U'FURD'B'F'RBF2D'F2R2L2FU'R'U'R2L2F'B2R'F`
Input -\> `R2FUF2D'FR'B'D2L2F'URB2R'U'D'R2L'UD'R2B2UD2`

Your program may assume that the given cube is possible to solve; i.e. you do not need to handle the case that the inputted cube is unsolvable.

# Restrictions

Answers like this, while valid/interesting on other challenges, are not welcome here. You may not use an algorithm that iterates through every possible state of the cube and prints the moves as it goes, or anything similar.

To define these restrictions, your program must be able to solve each of the test cases above on TIO. So it must:

* Exit in under 60 seconds.
* Output less than 128KiB.

# Validation

To validate that your program indeed solves the Rubik's Cube, you can obviously use a physical cube or an online cube emulator by mixing it how you like, feeding its state into your program, and then performing the output moves on the cube.

However, if you choose to format your input as the cube dump (or the `ULFRBD` scheme and translate it to a cube dump), you can validate your program via Cubically's online interpreter like so:

1. Go to the online interpreter.
2. Type `rs` into the `Code` section.
3. Paste your unsolved cube-dump into the `Input` section.
4. Run your program with the unsolved cube-dump. Copy the output into the `Footer` section.
5. Click `Run`. If your program is valid, `Solved!` will appear in the `Output` section.

# Winning

As this is , the shortest code in bytes wins!

# Answer
> 7 votes
# Cubically, 3 bytes

```
rp▦

```

Try it online! You can use this to print a random cube.

Explanation:

```
r    read cube from stdin
 p   set PRINTMOVES flag to display moves as they are performed on the cube
  ▦  insert moves to solve the cube at the current point in the program

```

Capitalize the `P` to see prettier output (e.g. `RLD'U2` as opposed to `R1L1D3U2`).

# Answer
> 2 votes
# Python + kociemba, 27 bytes

A non-trivial language, trivially using the kociemba library

```
from kociemba import*
solve

```

Call `solve()` with a cube in the ULFRBD scheme.

Example, solve('DRLUUBFBRBLURRLRUBLRDDFDLFUFUFFDBRDUBRUFLLFDDBFLUBLRBD') returns u"D2 R' D' F2 B D R2 D2 R' F2 D' F2 U' B2 L2 U2 D R2 U"

(PS, this answer isn't any "better" than the Cubically answer)

---
Tags: code-golf, geometry, puzzle-solver, rubiks-cube, restricted-time
---


title: Rounding Numbers

text:
# Question
Title: Rounding Numbers
# Task

Given a number between 0 and 1 and another integer, print the approximated value of the first number rounded off to the specified number of digits given by the second integer. For example, if the input is `0.3212312312 , 2` then the output is:

`0.32`

# Rules

* The number of digits after the dot should always equal the second input integer.
* The input will always be `([)number from 0-1 , integer above 0(])`
* Predefined round functions are allowed.
* The first input number will not have any trailing 0's
* Always use a dot for input and output. Commas are not allowed.
* Fractions are allowed as output with the notation `number/number` but try to just use a decimal notation.

\[Trailing zero rule removed due to that i should have been faster\]

* Rounding should always be done to the closest number so up if above 4 and down if under 5.

# Testcases

Input: 0.31231231231 , 1

Output: 0.3

Input: 0.1, 10

Output: 0.1000000000

Input: 0.01231231231 , 9

Output: 0.012312312

# Scoring:

This is code-golf. Shortest answer in bytes wins.

Suggestion for making this challenge better are appreciated. Have fun golfing!

EDIT: definition of this challenge by Francisco Hahn: `shortest way to round a float X with precision N on each language`

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

```
/* Configuration */

var QUESTION_ID = 166330; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

# Answer
# APL (Dyalog Unicode), 1 byteSBCS

Anonymous tacit infix function (actually just a built-in). Takes number of decimals as left argument and fraction as right argument.

Try it online!

Documentation for dyadic ("Format By Specification").
> 6 votes

# Answer
# JavaScript (Node.js), 18 bytes

```
a=>b=>a.toFixed(b)

```

Try it online!
> 5 votes

# Answer
# Japt, 2 bytes

```
xV

```

Try it online!

**x** is the builtin for rounding to **n** decimals. We pass in **V** (Second input).
> 4 votes

# Answer
# Japt, 2 bytes

Takes input as an array of 2 numbers.

```
rx

```

Try it

`r`educes the array by rounding the first number to the number of decimals specified by the second.
> 4 votes

# Answer
# PHP, ~~47~~ 39 bytes

```
function a($b,$c){return round($b,$c);}

```

Try it online!
> 2 votes

# Answer
# Python 2, 24 bytes

-4 bytes thanks to ovs

```
lambda a,b:"%%0.%sf"%b%a

```

Try it online!
> 2 votes

# Answer
# Python 3 (produces rounded float, no trailing zeroes), 5 bytes

```
round

```

Try it online!

Python's built-in `round` function is defined to do exactly what the OP wants in the summary edited in later "round a float X with precision N", though without appending trailing zeroes (because it's still returning a `float`, and `float`s don't include information about their formatting).

# Python 3 (produces string form), 16 bytes

```
'{:.{}f}'.format

```

Try it online!

Formatting operations can use a nested specifier to allow one argument to define the precision of the other. Doesn't print it, but returns a formatted string with the specified precision.

# Python 3 (prints string), 30 bytes

```
lambda a,b:print(f'{a:.{b}f}')

```

Try it online!

Python 3.6+ f-strings save some characters here (couldn't use them without the wrapping function since we wouldn't know the names to use). Mostly included to demonstrate f-strings (obviously longer than other solutions).
> 2 votes

# Answer
## PHP, 28 Bytes

Try it online

**Code**

```
<?=round($argv[0],$argv[1]);

```
> 1 votes

# Answer
# Forth (gforth), 26 bytes

Assuming decimal is on top of the floating point stack and precision is on the integer stack

```
: f dup 2 + swap 1 f.rdp ;

```

Try it online!

### Explanation

`f.rdp` takes a float and 3 arguments from the integer stack:

1. the width of the output (answer uses `n+2` to account for 0 and decimal point)
2. the number of digits after the decimal (answer uses `n`)
3. the required number of significant figures in the input (answer uses 1, because floats with less significant figures are outputted in exponential notation)

### Code explanation

```
dup 2 + swap 1        \ place n+2 n and 1 on top of the stack
f.rdp                 \ formats output

```
> 1 votes

# Answer
# Stax, 1 bytes

```
j

```

Run and debug it

In stax, `j` is a built-in instruction that performs the required rounding.
> 1 votes

# Answer
# T-SQL, 24 bytes

```
SELECT STR(f,20,d)FROM t

```

Per our input standards, input is taken via pre-existing table **t** with float **f** and integer **d**.

The function `STR()` is shorter and more convenient than either a `CAST` or a `ROUND`.

You didn't specify, so I assumed that 20 digits would be more than sufficient. If not, that hard-coded value can be increased.
> 1 votes

# Answer
# Java (JDK 10), 21 bytes

```
n->d->n.setScale(d,4)

```

Try it online!

I would have loved to have submitted `n->n::setScale` (14 bytes) but alas, there is no default rounding, so we get `ArithmeticException` when rounding is required...
> 1 votes

# Answer
# MATL, 13 bytes

```
i'%.'j'f'hhYD

```

Try it online!

### Explanation:

```
i              % Grab first input: 0.32315
 '%.'j'f'      % Push the literal: ['%.' second input as string 'f'], where the input
               % specifies the number of decimals
         YD    % printf('%.sf',x)  where s is the second input, and x is the first

```
> 1 votes

# Answer
# , ~~40~~ 36 bytes

```
function(x,n)format(round(x,n),ns=n)

```

Try it online!

(-4) thanks to digEmAll
> 1 votes

# Answer
# Julia 0.6, 51 bytes

```
(x,d)->(y=string(round(x, d));y*"0"^(d-endof(y)+2))

```

Try it online!

With trailing zeros as per the questions's "Trailing zeroes should be added with for example 0.1, 10" condition.

Julia's `@printf` can only take constant X values in `%.Xf` format strings (`%.4f`, etc.), so instead this code manually pads the required number of zeros if the rounded value has less than d digits after the decimal place.

First, store the rounded number as a string in `y`. Then, the number of digits after decimal point in `y` is `length(y) - 2` (`- 2` because the inputs are between 0 and 1, so there's one initial digit and then a decimal point to subtract). `endof(y)` is just a shorter way to write `length(y)` (at least for Julia v0.6).

Then, subtract this from the required number of digits `d`. Then, `(d-(endof(y)-2))` (= `(d-endof(y)+2)`) tells you how many digits are missing in the output (if any). Use that in `"0"^(d-endof(y)+2)` to get "0" repeated that many times, and then append that to `y` with the string `*` (concatenate) operator.

---

# Julia 0.6, 5 bytes

```
round

```

Try it online!

Without trailing zeros, conforming to the summary "shortest way to round a float X with precision N on each language".
> 1 votes

# Answer
74 Bytes Python 2.7

```
lambda x,y:str(x)[:y+2]if int(str(x)[y+2])<5else float(str(x)[:y+2])+.1**y

```

Messy but I think it works for all the scenarios.
> 0 votes

# Answer
# Perl 6, 18 bytes

```
{$^a.base(10,$^b)}

```

Try it
> 0 votes

# Answer
# 05AB1E, 10 bytes

```
.ò0¹²g-Ì∍J

```

is the builtin that already gives the answer for most test cases. `0¹²g-Ì∍J` is to correctly append trailing zeroes if necessary.

Try it online.

```
.ò          # Round the second decimal input to the integer first input amount of decimals
            #  i.e. 10 and 0.1 → 0.1
            #  i.e. 1 and 0.67231 → 0.7
0           # Literal '0'
 ¹          # Get the first integer input
  ²g        # Get the length of the second decimal input
    -       # Subtract them from each other
     Ì      # Increase it by 2 for the "0." part
            #  i.e. 10 and 0.1 → 10-3+2 → 9
            #  i.e. 1 and 0.67231 → 1-7+2 → -8
      ∍     # Extend the "0" to a size of that length
            #  i.e. "0" and 9 → "000000000"
            #  i.e. "0" and -8 → ''
       J    # Join everything together
            #  i.e. 0.1 and "000000000" → 0.1000000000
            #  i.e. 0.7 and '' → 0.7

```
> 0 votes

# Answer
# Octave, 28 bytes

```
@(x,y)printf(['%.',y,'f'],x)

```

Try it online!

Takes the first input as a number and the second as a string. Creates a formatting string: `%.yf` by concatenation, where `y` is the input that specifies the number of decimals. `x` is the input number that will be printed.
> 0 votes

# Answer
# , 42 bytes

```
function(x,n)sprintf(paste0("%.",n,"f"),x)

```

Try it online!

Failed attempt at outgolfing DS\_UNI's shorter R answer.

Even worse:

## , 43 bytes

```
function(x,n)sprintf(sprintf("%%.%if",n),x)

```

Try it online!
> 0 votes

# Answer
# Kotlin, 19 bytes

```
"%.${b}f".format(a)

```

Try it online!
> 0 votes

# Answer
# Tcl, 31 bytes

```
proc R x\ n {format %.*f $n $x}

```

Try it online!
> 0 votes

---
Tags: code-golf, approximation
---


title: Generate a Portmantout!

text:
# Question
Title: Generate a Portmantout!
### Background

Three years ago, this guy Tom Murphy got it into his head to extend the idea of a portmanteau to all words in a language and called this a *portmantout* (*portmanteau* plus *tout* \[French for *all*\]). Defining English as a list of 108,709 words, he managed to find a sequence of 611,820 letters with the following two properties:

* Every English word is contained in the string.
* Some neighborhood containing any two adjacent letters in the string is an English word.

Here's a link to a page on which this portmantout can be found (along with a video explanation).

### A portmantout

The first of the two properties of a portmantout is easy to understand. The second may require some explanation.

Basically, words must overlap. "golfcode" will never appear in a portmantout of English, as there is no word there that contains the "fc". However, you might find "codegolf" in a portmantout, for "ego" bridges the gap (and all other pairs of letters are in either "code" or "golf").

### Your task:

Write a program or function that takes a list of strings and returns any portmantout of the list.

This Python 3 code will verify a portmantout.

### Test cases

All lists are unordered; that is,

```
{"code", "ego", "golf"} -> "codegolf"
{"more", "elm", "maniac"} -> "morelmaniac" or "morelmorelmaniac" or "morelmorelmorelmaniac" or...
    Would a morelmaniac be some sort of mycologist?
{"ab", "bc", "cd", "de", "ef", "fg", "gh", "hi", "ij", "jk", "kl", "lm", "mn", "no", "op", "pq", "qr", "rs", "st", "tu", "uv", "vw", "wx", "xy", "yz", "za"} -> "abcdefghijklmnopqrstuvwxyza" or "rstuvwxyzabcdefghijklmnopqrstuvwxyzabcdef" or any 27+ letters in order

```

And why not? The massive one on Murphy's site, if your code executes within reasonable time.

### Rules

* Your code must halt.
* You need not return the same portmantout with each execution.
* You may assume all strings consist of only lowercase letters `a` through `z`.
* If no portmantout is possible, your program may do anything. Ex: `{"most", "short", "lists"}`
* Standard rules for I/O and loopholes apply.

This is , so the shortest solution (in bytes) in each language wins! Happy golfing!

# Answer
> 3 votes
# Python 2, ~~204~~ 202 bytes

```
def f(l,s=''):
 if all(w in s for w in l):return s
 for i,w in enumerate(l):
	a=next((s+w[i:]for i in range(len(w)-1,0,-1)if s[-i:]==w[:i]),0)if s else w;x=a and f(l[:i]+l[i+1:]+[l[i]],a)
	if x:return x

```

Try it online!

---

Saved

* -2 bytes, thanks to recursive

# Answer
> 1 votes
# Pyth, 39 bytes

```
JQW}_1mxbdQ=+J|=b*qKOQ<=T+OP._KOJlKTY)b

```

Try it here

### Explanation

```
JQW}_1mxbdQ=+J|=b*qKOQ<=T+OP._KOJlKTY)b
JQ                                        Get a copy of the input.
  W}_1mxbdQ                          )    While there are words in the input
                                          that aren't in b (initially space)...
                   KOQ    OP._KOJ         ... get a random input word, a random
                                          prefix, and a random joined word...
                       =T+                ... stick them together...
                  q   <          lKT      ... and check if joining them together
                                          is valid...
               =b*                        ... then update b accordingly...
           =+J|                     Y     ... and stick the new word into J.
                                      b   Output the final result.

```

# Answer
> 1 votes
# Stax, ~~39~~ 36 bytes

```
ä▬│•.k=╠lƒ☺╜00║¿~,▓╕╠7ÉΔB<e┼>☼Θ²└ô┴\

```

Run and debug it

Runs all the test cases deterministically in about a second.

This is a recursive algorithm.

* Start with each word of input as a candidate
* At each step, order the words by the number of times they occur as substrings of the candidate.
* For each word that's compatible with the end of the current candidate, join the word to form a new candidate, and make a recursive call.

Here's the program unpacked, ungolfed, and commented.

```
FG              for each word in input, call target block
}               unbalanced closing brace represents call target
  x{[#o         sort input words by their number of occurrences in the current candidate
  Y             store it in register Y
  h[#{,}M       if all of the words occur at least once, pop from input stack
                input stack is empty, so this causes immediate termination,
                followed by implicitly printing the top of the main stack
  yF            for each word in register y, do the following
    [n|]_1T|[|& intersect the suffixes of the candidate with prefixes of the current word
    z]+h        get the first fragment in the intersection, or a blank array
    Y           store it in register Y
    %t+         join the candidate with the current word, eliminating the duplicate fragment
    y{G}M       if the fragment was non-blank, recursively call to the call target
    d           pop the top of stack

```

Run this one

**Edit:** This fails for a class of inputs that has a loop, like `["ab", "ba", "ca"]`, as do most of the other posted answers.

# Answer
> 0 votes
# JavaScript (ES6), ~~138~~ 130 bytes

```
f=a=>a[1]?a.map((c,i)=>a.map((w,j,[...b])=>i!=j&&!/0/.test(m=(c+0+w).split(/(.+)0\1/).join``)?t=f(b,b[i]=m,b.splice(j,1)):0))&&t:a

```

Returns an error for lists that cannot be completely portmantouted.

Ungolfed:

```
f = a =>
  a[1] ?                                        //if more than one element ...
    a.map((c, i)=>                              // for each element
      a.map((w, j, [...b])=>                    //  for each element
        i != j &&                               //   if not the same element
        !/0/.test(m=(c+0+w).split(/(.+)0\1/).join``) &&  //   and the elements overlap
        (t = f(b,                               //   and f recursed is true when
               b[i] = m,    //    replacing the ith element with the 2-element portmanteau
               b.splice(j, 1)                   //    and removing the jth element
              )
        )
      )
    ) &&
    t :                                         //return the recursed function value
    a                                           //else return a

```

```
f=a=>a[1]?a.map((c,i)=>a.map((w,j,[...b])=>i!=j&&!/0/.test(m=(c+0+w).split(/(.+)0\1/).join``)?t=f(b,b[i]=m,b.splice(j,1)):0))&&t:a

console.log(f(["sic", "bar", "rabbits", "cradle"])+'')             // "barabbitsicradle"
console.log(f(["mauve", "elated", "cast", "electric", "tame"])+'') // "mauvelectricastamelated"

console.log(f(["more", "elm", "maniac"])+'')                       // "morelmaniac"
console.log(f(["elm", "more", "maniac"])+'')                       // "morelmaniac"
console.log(f(["more", "maniac", "elm"])+'')                       // "morelmaniac"

console.log(f(["ego", "code", "golf"])+'')                         // "codegolf"
console.log(f(["code", "ego", "golf"])+'')                         // "codegolf"
console.log(f(["golf", "ego", "code"])+'')                         // "codegolf"

console.log(f(['ab', 'bc', 'cd', 'de'])+'');                       // "abcde"
console.log(f(['de', 'bc', 'cd', 'ab'])+'');                       // "abcde"

console.log(f(["ab", "ba", "ca"])+'');                             // "caba"
```

The code is *excruciatingly* slow on the full alphabet example (not included for that reason in the above Snippet).

That is remedied by changing the `map`s to `some`s, for the loss of 2 bytes:

```
f=a=>a[1]?a.some((c,i)=>a.((w,j,[...b])=>i!=j&&!/0/.test(m=(c+0+w).split(/(.+)0\1/).join``)?t=f(b,b[i]=m,b.splice(j,1)):0))&&t:a

```

```
f=a=>a[1]?a.some((c,i)=>a.some((w,j,[...b])=>i!=j&&!/0/.test(m=(c+0+w).split(/(.+)0\1/).join``)?t=f(b,b[i]=m,b.splice(j,1)):0))&&t:a

console.log(f(["ab", "bc", "cd", "de", "ef", "fg", "gh", "hi", "ij", "jk", "kl", "lm", "mn", "no", "op", "pq", "qr", "rs", "st", "tu", "uv", "vw", "wx", "xy", "yz", "za"])+'');

console.log(f(["ab", "ba", "ca"])+'');                             // "caba"
```

---
Tags: code-golf, string, graph-theory
---


# Question
Title: It's getting harder and harder to be composite these days
Given a non-empty list **L** of integers greater than **1**, we define **d(L)** as the smallest positive integer such that **n + d(L)** is composite for each **n** in **L**.

We define the sequence **an** as:

* **a0 = 2**
* **ai+1** is the smallest integer greater than **ai** such that **d(a0, ..., ai, ai+1) \> d(a0, ..., ai)**

## Your task

You may either:

* Take an integer **N** and return the **N-th** term of the sequence (0-indexed or 1-indexed)
* Take an integer **N** and return the first **N** terms of the sequence
* Take no input and print the sequence forever

This is , so the shortest answer in bytes wins!

It's OK if your code is getting slow as **N** gets larger, but it should at least find the 20 first terms in less than 2 minutes.

## First terms

* **a0 = 2** and **d(2) = 2** (we need to add 2 so that 2+2 is composite)
* **a1 = 3** because **d(2, 3) = 6** (we need to add 6 so that 2+6 and 3+6 are composite)
* **a2 = 5** because **d(2, 3, 5) = 7** (we need to add 7 so that 2+7, 3+7 and 5+7 are all composite), whereas **d(2, 3, 4)** is still equal to **6**
* etc.

Below are the 100 first terms of the sequence (unknown on OEIS at the time of posting).

```
  2,   3,   5,   6,  10,  15,  17,  19,  22,  24,
 30,  34,  35,  39,  41,  47,  51,  54,  56,  57,
 70,  79,  80,  82,  92,  98, 100, 103, 106, 111,
113, 116, 135, 151, 158, 162, 165, 179, 183, 186,
191, 192, 200, 210, 217, 223, 226, 228, 235, 240,
243, 260, 266, 274, 277, 284, 285, 289, 298, 307,
309, 317, 318, 329, 341, 349, 356, 361, 374, 377,
378, 382, 386, 394, 397, 405, 409, 414, 417, 425,
443, 454, 473, 492, 494, 502, 512, 514, 519, 527,
528, 560, 572, 577, 579, 598, 605, 621, 632, 642

```

# Answer
# Pyth, 24 bytes

```
Pu+GfP_+Tf!fP_+ZYG)eGQ]2

```

Demonstration

Basically, we start with `[2]`, then add elements 1 at a time by alternately finding `d`, then adding an element, and so forth. Outputs the first `n` elements of the sequence.

Contains a filter inside a first integer filter inside a first integer filter inside an apply repeatedly loop.

**Explanation:**

```
Pu+GfP_+Tf!fP_+ZYG)eGQ]2
 u                   Q]2    Starting with `[2]`, do the following as many times
                            as the input
         f        )         Starting from 1 and counting upward, find d where
          !f     G          None of the elements in the current list
            P_+ZY           plus d give a prime.
    f              eG       Starting from the end of the current list and counting
                            upward, find the first number which
     P_+T                   plus d gives a prime.
  +G                        Append the new number to the current list
P                           Trim the last element of the list

```

There's obvious repeated effort between the two "Add and check if prime" calls, but I'm not sure how to eliminate it.
> 1 votes

# Answer
# Jelly, 31 bytes

```
ṛ,;1+ÆPẸṆʋ1#ⱮẎ</
Ḷß€‘Ṫç1#ƊḢƲ2⁸?

```

Try it online!

Jelly sucks at recurrence sequences. :/
> 1 votes

# Answer
# Retina, 74 bytes

```
K`__;
"$+"{/;(?!(__+)\1+\b)/+`;
;_
.+$
$&¶$&
)/;(__+)\1+$/+`.+$
_$&_
%`\G_

```

Try it online! 0-indexed. Explanation:

```
K`__;

```

Each line `i` in the workarea contains two unary values, `aᵢ;d+aᵢ`. We start with `a₀=2` and `d+a₀=0` (because it's golfier).

```
"$+"{
...
)

```

Repeat the loop `N` times.

```
/;(?!(__+)\1+\b)/+`

```

Repeat while there is at least one non-composite number.

```
;
;_

```

Increment `d`.

```
.+$
$&¶$&

```

Duplicate the last line, copying `aᵢ₋₁` to `aᵢ`.

```
/;(__+)\1+$/+`

```

Repeat while `d+aᵢ` is composite.

```
.+$
_$&_

```

Increment `aᵢ`.

```
%`\G_

```

Convert the results to decimal.
> 1 votes

# Answer
# Clean, ~~138~~ ~~130~~ 128 bytes

```
import StdEnv
$l=until(\v=all(\n=any((<)1o gcd(n+v))[2..n+v-1])l)inc 1

```

#

```
map hd(iterate(\l=hd[[n:l]\\n<-[hd l..]| $[n:l]> $l])[2])

```

Try it online!

***Expanded:***

```
$l=until(\v=all(\n=any((<)1o gcd(n+v))[2..n+v-1])l)inc 1
$l=until(                                         )inc 1  // first value from 1 upwards where _
         \v=all(                                )l        // _ is true for everything in l
                \n=any(              )[2..n+v-1]          // any of [2,3..n+v-1] match _
                             gcd(n+v)                     // the gcd of (n+v) and ^
                           o                              // (composed) ^ is _
                       (<)1                               // greater than 1

```

#

```
map hd(iterate(\l=hd[[n:l]\\n<-[hd l..]| $[n:l]> $l])[2])
map hd(                                                 ) // the first element of each list in _
       iterate(                                     )[2]  // infinite repeated application of _ to [2]
               \l=hd[                              ]      // the head of _
                     [n:l]                                // n prepended to l
                          \\n<-[hd l..]                   // for every integer n greater than the head of l
                                       | $[n:l]> $l       // where d(n0..ni+1) > d(n0..ni)

```
> 1 votes

# Answer
# Julia 0.6, ~~145~~ 130 bytes

```
~L=(x=1;while any(map(m->all(m%i>0 for i=2:m-1),L+x));x+=1;end;x)
!n=n<1?[2]:(P=!(n-1);t=P[end]+1;while ~[P;t]<=~P;t+=1;end;[P;t])

```

Try it online!

*(-15 bytes using my new and improved golfing skills - operator overloads, replacing conditional by ternary and hence removing `return` keyword.)*

**Expanded**:

```
function primecheck(m)
    all(m%i>0 for i∈2:m-1)
end

function d(L)
    x = 1
    while any(map(primecheck, L+x))
        x += 1
    end
    return x
end

function a(n)
    n > 0 || return [2]
    Prev = a(n-1)
    term = Prev[end] + 1
    while d([Prev;term]) ≤ d(Prev)
        term += 1
    end
    return [Prev;term]
end

```
> 1 votes

---
Tags: code-golf, sequence, primes
---


title: Equal Pair sum of 10?

text:
# Question
Title: Equal Pair sum of 10?
# Challenge :

Check :

* if there are exactly `n` exclamation marks `!` between every `pair`
* and whether the sum of **each** pair equals to 10.

---

# Input :

* A string of arbitary length.
* The number of exclamation marks to check for

---

# Output :

if there are exactly `n` exclamation marks between each pair, return truthy value, otherwise falsy value.

---

# Pair :

**Pair** is defined as two digits with **at least** one exclamation mark between them

---

# Note :

* The string may contain
    + lowercase letters
    + digits (1-9)
    + space
    + and obviously exclamation marks (`!`)
* In case no digit pair is found, return a falsy value.
* The exclamation will not appear at start or end of the string

---

# Examples :

```
asas6!!4somevbss5!!asa5 , 2                ---> true
sasdasd3!2ssjdn3! sdf!3 , 1                ---> false
asjsj8sj!!!! 2 sjsadasd9!!!!1 , 4          ---> true
sal7!!3 , 2                                ---> true
nodtejsanhf , 2                            ---> true
2is digit no excla 5 , 8                   ---> true
a!1!9!8!2!a  , 1                           ---> true (thanks @ngn)

```

The last two cases were `false` imo but as suggested by Adam (who has more experience than me and probably knows better :) ), they were made true

---

# Winning criteria :

this is so shortest code in bytes for each language wins.

---

# Don't forget :

You must check whether the sum of the two numbers equals 10 or not too, along with whether each pair is separated via `n` exclamation marks

---

# Credit ? :

@Laikoni found a challenge on coderbyte similar to this : Here. O\_o ? I didn't know that

---

# Some explanation :

@ngn suggested this case `a!!1!2!3a45!6!!a , 1` (return false)

```
a!!      --> ignore this
1        --> here we go start
!        --> sum so far = 1
2        --> sum = 3, and stop

```

Yep the sum of each pair must be 10 and since the sum of the first pair wasn't 10, no need to go on. :)

# Answer
> 1 votes
# APL (Dyalog Unicode), ~~62~~ 48 bytesSBCS

Full program. Prompts stdin for string and then for `n`. Now handles cases like `a!1!9!!8!2!a`. Thanks to ngn for saving a bunch of bytes while pointing out failure of some unlisted test cases. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems.

```
∧/(⎕=¯2+≢¨m),0=10|+/⎕D⍳↑m←'\d!+\d'⎕S'&'⊢⍞∩⎕D,'!'

```

Try it online!

`⎕D,'!'` concatenate the **D**igits and an exclamation point.

`⍞∩` prompt for string and find the intersection with the above (removes all irrelevant chars)

`⊢i←` store in `i` (for **i**nput) and yield that

`'\d!+\d'⎕S'&'` PCRE **S**earch for a digit, a "!" run, a digit

`m←` store in `m` (for **m**atches)

mix the list of strings into a character matrix, padding with spaces

`⎕D⍳` find the **ɩ**ndex of each character in the **D**igits (i.e. "0" → 0, "1" → 1,… "!" and " " → 10)

`+/` sum each row (i.e. each pair)

`10|` division remainder when divided by 10 (non-digits do not affect this result)

`0=` is it 0? (i.e. divisible by ten; max is 18 and min is 2, so no false positives)

`(``),` prepend the following:

`≢¨m` tally (count the length of) each **m**atch

`¯2+` less 2 (for the two digits, i.e. length of the "!" run)

`⎕=` prompt for `n`; is it equal to the lengths?

`∧/` are they all true? (AND reduction)

# Answer
> 0 votes
# Python 2, 94 bytes

```
lambda s,c:all(sum(map(int,r))==10for r in re.findall('(\d).*?%s.*?(\d)'%('!'*c),s))
import re

```

Try it online!

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


title: Do you need a cup holder?

text:
# Question
Title: Do you need a cup holder?
You're going to replicate the 90's cup holder joke software.

Here's what's it did, and you have to do:

* Display the message `Do you need a cup holder?`
* If the user confirms, enter an infinite loop that keeps opening the CDROM drive.
* If the user doesn't confirm, silently exit.

You may display the message using either a console message (confirmation is `y`, decline is `n`), or display a message window with the two options "Yes" and "No". You can assume the default (or most common) CDROM drive (`D:` on Windows, `/cdrom` on linux etc.). Standard loopholes (except built-ins) are forbidden. No additional input nor output may be involved. If your PC has no physical drive, or another "style" of tray, make sure the program is valid.

, so shortest program in bytes wins.

Trivia: The loop is there to prevent anyone from closing the drive. On desktop drives, the re-open command will be sent while the drive is closing, therefore staying open and not "spilling the coffee".

# Answer
# Bash, ~~115~~ ~~69~~ ~~68~~ 66 bytes

This was written on Mac OS X but it should work on other BSD-based systems as well.

```
echo Do you need a cup holder?;sed 1q|grep y&&yes drutil\ eject|sh

```

We `echo` the prompt, get input with `set 1q`, and determine whether the user confirmed with `grep y`. If the user said `y`, we pipe the infinite output of `yes` with the string `drutil eject` to the shell, which will continuously eject the disk tray.

Saved **50 bytes** thanks to Digital Trauma!
> 4 votes

# Answer
# Vitsy + Mac OSX bash, 55 bytes

```
'?redloh puc a deen uoy oD'ZWb2^/([1m]
<,'drutil eject'
```

Expects input as y or n. If it is n, it will execute line 2 (infinite loop with the shell command), otherwise, it will halt.
> 4 votes

# Answer
## Python (3.5) 84 bytes

```
import os
i=input("Do you need a cup holder?")
while i=='y':os.system("eject cdrom")

```

On linux

*edit: fix bytes count ;)*
> 2 votes

# Answer
## AutoIt, 85 bytes

```
If MsgBox(4,0,"Do you need a cup holder?")=7 Then Exit
Do
CDTray("D:","open")
Until 0

```

No one will ever answer anything in AutoIt anyway :)
> 0 votes

# Answer
## Python 3.5 on Windows 7, 135 Bytes

```
import ctypes
r=input('Do you need a cup holder?')
while r=='y':ctypes.windll.WINMM.mciSendStringW('set cdaudio door open',None,0,None)

```
> 0 votes

---
Tags: code-golf, hardware
---


title: Golf A Parentheses Matching Algorithm

text:
# Question
Title: Golf A Parentheses Matching Algorithm
You will be given a string `s`. It is guaranteed that the string has equal and at least one `[`s and `]`s. It is also guaranteed that the brackets are balanced. The string can also have other characters.

The objective is to output/return a list of tuples or a list of lists containing indices of each `[` and `]` pair.

### note: The string is zero-indexed.

Example: `!^45sdfd[hello world[[djfut]%%357]sr[jf]s][srtdg][]` should return

`[(8, 41), (20, 33), (21, 27), (36, 39), (42, 48), (49, 50)]` or something equivalent to this. Tuples are not necessary. Lists can also be used.

Test cases:

```
input:[[asdf][][td([)ty54g% ]hg[[f]u][f[[jhg][gfd]sdf]sdfs]ghd]fr43f]
output:[(0, 62),(1, 6), (7, 8), (9, 56), (13, 22), (25, 30), (26, 28), (31, 52), (33, 47), (34, 38), (39, 43)]
input:[[][][][]][[][][][[[[(]]]]]))
output:[(0, 9), (1, 2), (3, 4), (5, 6), (7, 8), (10,26),(11, 12), (13, 14), (15, 16), (17, 25), (18, 24), (19, 23), (20, 22)]
input:[][][[]]
output:[(0, 1), (2, 3), (4, 7), (5, 6)]
input:[[[[[asd]as]sd]df]fgf][][]
output:[(0, 21), (1, 17), (2, 14), (3, 11), (4, 8), (22, 23), (24, 25)]
input:[]
output:[(0,1)]
input:[[(])]
output:[(0, 5), (1, 3)]

```

This is , so the shortest code in bytes for each programming language wins.

# Answer
# Brain-Flak Classic, 108 bytes

```
{((((((([][][]){}){}){}()){}){}{}[])()()){{}<>{}(<>)}{}((){[](<{}>)}{}){{}<>[({}<[{}]>)](<>)}{}<>(({}()))<>}

```

Try it online!

Stores each opening `[` in the right stack, and outputs whenever we hit a `]`.
> 13 votes

# Answer
# Python 2, 74 bytes

```
s=[];i=0
for c in input():
 if'['==c:s+=i,
 if']'==c:print s.pop(),i
 i+=1

```

Try it online!
> 12 votes

# Answer
# JavaScript, ~~69~~ 62 bytes

A quick bit of golf on the train home. Can probably be improved on.

Takes input as an array of characters and outputs an object with the keys being the indices of the `[`s and their values being the indices of their corresponding `]`s.

```
a=>a.map((x,y)=>x==`]`?o[a.pop()]=y:x==`[`&&a.push(y),o={})&&o

```

Try it online
> 5 votes

# Answer
# Haskell, ~~92~~ 79 bytes

```
g(u:a)n(']':x)=(u,n):g a(n+1)x
g a n(s:x)=g([n|s=='[']++a)(n+1)x
g[]_[]=[]
g[]0

```

Try it online!

## Explanation

We create a function `g` which takes 3 arguments.

* `a`, which is the locations of all unmatched `[`s.
* `n`, which is the number of characters processed
* `x` which is the characters unprocessed.

If our first character is `]` we remove `u` from the front our `a` and return `(u,n)` plus whatever else remains.

```
g(u:a)n(']':x)=(u,n):g a(n+1)x

```

If our first character is not `]`, that is either `[` or something else, we increment `n` and add `[n|s=='[']` to the front of `a`. `[n|s=='[']` will be `[n]` if `s=='['` and `[]` otherwise.

```
g a n(s:x)=g([n|s=='[']++a)(n+1)x

```

If we are out of characters we return the empty list.

```
g[]_[]=[]

```
> 4 votes

# Answer
## QBasic (QB64), ~~137~~ ~~127~~ 112 bytes

```
INPUT a$
for i=0to len(a$)
c$=mid$(a$,i+1,1)
if"["=c$then
b(n)=i
n=n+1
elseif"]"=c$then
n=n-1
?b(n),i
endif
next

```

We need ~~four~~ two bytes because the challenge requires 0-indexing. My first QBasic post, feedback is appreciated.

* 10 bytes thanks to steenbergh
* 3 bytes thanks to Erik the Outgolfer
* 12 bytes by saving in unix file format (`\r\n` -\> `\n`)

Looks like this when executed:
> 4 votes

# Answer
# Java 10, 95 bytes

A void lambda taking the input string as an `int[]` of Unicode code points.

```
s->{int r=0,w=0;for(var c:s){if(c==91)s[w++]=r;if(c==93)System.out.println(s[--w]+","+r);r++;}}

```

Try It Online

## Ungolfed

```
s -> {
    int r = 0, w = 0;
    for (var c : s) {
        if (c == 91)
            s[w++] = r;
        if (c == 93)
            System.out.println(s[--w] + "," + r);
        r++;
    }
}

```

## Acknowledgments

* thanks to Jonathan Frech for the idea of using the input string as a stack (here)
> 4 votes

# Answer
# vim, 89 bytes

```
:s/\(.\)/\1<C-V><C-M>/g|g/^\[/ :norm %mm%:pu! =line('.').','.line(\"'m\")<C-V><C-M><C-X>$<C-X>J
:v/\[/d|%s/\[//g

```

## Annotated

```
:s/\(.\)/\1<C-V><C-M>/g            " one character per line
|g/^\[/                            " for each opening square bracket:
  :norm %mm%                       "   mark the line with the matching bracket
  :pu! =line('.').','.line(\"'m\") "   write the line numbers to preceeding line
  <C-V><C-M><C-X>$<C-X>J           "   convert to 0-based counting and join lines
:v/\[/d                            " remove all non-opening bracket lines
|%s/\[//g                          " remove brackets

```

`<C-V>` is 0x16. `<C-M>` is 0x0d. `<C-X>` is 0x18.

Try it online!
> 4 votes

# Answer
# Pyth, 26 bytes

```
VQIqN\[=+YZ)IqN\],.)YZ)=hZ

```

Try it here

### Explanation

```
VQIqN\[=+YZ)IqN\],.)YZ)=hZ
VQ                     =hZ   For each character in the input (indexed by Z)...
  IqN\[=+YZ)                 ... if the character is [, add the index to Y...
            IqN\],.)YZ)      ... if the character is ], output the previous index
                             and current index.

```
> 3 votes

# Answer
# , ~~141 133 115 112~~ 108 bytes

```
function(y,x=utf8ToInt(y)){for(i in seq(x)){if(x[i]==91)F=c(i,F);if(x[i]==93){T=c(T,F[1],i);F=F[-1]}};T[-1]}

```

Try it online!

Nothing special. 1-indexed, because I said so. R doesn't really have stacks, so I originally used `c`, `head`, and `tail` to get the same literal effect. Ungolfed original version (updates using `utf8ToInt` to remove some bytes, using the start of the vector as the top of the stack, and abusing `T` and `F` builtins to avoid initializing the stacks.):

```
f <- function(y, x=el(strsplit(y,""))) {
  p <- l <- NULL
  for(i in seq_along(x)) {
    if(x[[i]]=='[') {
      p <- c(p, i)
    }
    if(x[[i]]==']') {
      l <- c(l, tail(p, 1), i)
      p <- head(p, -1)
    }
  }
  l # Because I said so. Change to l-1 if you want to check the test cases.
}

```
> 3 votes

# Answer
# Jelly, ~~20~~ 18 bytes

*Saved 1 byte thanks to @user202729 informing me that `µ€` is `)`*

```
ẹⱮØ[µ³ḣċþØ[_/Ụị)Z’

```

Try it online!

After wrestling with this for several hours just to get it working... I'm honestly surprised that it's gotten this short :-)

### Explanation

```
ẹⱮØ[µ³ḣċþØ[_/Ụị)Z’   Main link. Argument: s (string)  '[a[b]c[]][d]'
  Ø[                 Shortcut for the string "[]".
 Ɱ                   For each char in the "[]":
ẹ                      Find the indices of each occurrence in the input.
                     For our example, this gives the array [[1, 3, 7, 10], [5, 8, 9, 12]].

    µ                Begin a new monadic chain, with said array as its argument.
               )     For each of the two sub-arrays q within the array:
                         [[1, 3, 7, 10], [5, 8, 9, 12]]
     ³ḣ                For each item n in q, take the first n chars of the input.
                         [['[',     '[a[',      '[a[b]c[',   '[a[b]c[]]['],
                          ['[a[b]', '[a[b]c[]', '[a[b]c[]]', '[a[b]c[]][d]']]
        þØ[            For each string s in this, and each char c in "[]":
       ċ                 Count the occurrences of c in s.
                         [[[1, 0],  [2, 0],     [3, 1],      [4, 3]],
                          [[2, 1],  [3, 2],     [3, 3],      [4, 4]]]
           _/          Reduce each pair by subtraction. This is the number of open brackets
                         at each position.
                         [[1, 2, 2, 1], [1, 1, 0, 0]]
             U         Sort the indices by their values, using position as a tiebreaker.
                         [[1, 4, 2, 3], [3, 4, 1, 2]]
              ị        Index these values back into q.
                         [[1, 10, 3, 7], [9, 12, 5, 8]]

               )     Start a new monadic chain with the result as its argument.
                Z    Zip; transpose rows and columns.
                         [[1, 9], [10, 12], [3, 5], [7, 8]]
                 ’   Decrement; switch to 0-indexing.
                         [[0, 8], [9, 11], [2, 4], [6, 7]]

```
> 3 votes

# Answer
# Jelly,  ~~22 21 20~~  19 bytes

No doubt it is possible in Jelly in half this byte count :p ...

```
n€Ø[ḅ-µMịÄÐƤi€0ĖƊ’Ä

```

A monadic link accepting a list of characters which returns a list of lists of integers.
As a full program it accepts a string and prints a representation of said list.

**Try it online!**

### How?

```
n€Ø[ḅ-µMịÄÐƤi€0ĖƊ’Ä - Link: list of characters    e.g. "[f[o]o!]"
  Ø[                - list of characters = ['[', ']']
n€                  - not equal? for €ach              [[0,1],[1,1],[0,1],[1,1],[1,0],[1,1],[1,1],[1,0]]
                    -     ...relating to the characters:  [     f     [     o     ]     o     !     ]
    ḅ-              - convert from base -1             [1,0,1,0,-1,0,0,-1]
                    -     ...i.e.: 1 where '['; -1 where ']'; and 0 elsewhere
      µ             - start a new monadic chain with that as the argument, say V
                Ɗ   - last 3 links as a monad (function of V):
          ÐƤ        -   for post-fixes:
         Ä          -     cumulative sum               [[1,1,2,2,1,1,1,0],[0,1,1,0,0,0,-1],[1,1,0,0,0,-1],[0,-1,-1,-1,-2],[-1,-1,-1,-2],[0,0,-1],[0,-1],-1]
            i€0     -   1st index of 0 in €ach (or 0)  [8,1,3,1,0,1,1,0]
               Ė    -   enumerate                      [[1,8],[2,1],[3,3],[4,1],[5,0],[6,1],[7,1],[8,0]]
       M            - maximal indices of V             [1,3]
        ị           - index into                       [[1,8],[3,3]]
                 ’  - decrement                        [[0,7],[2,2]]
                  Ä - cumulative sum (vectorises)      [[0,7],[2,4]]

```
> 2 votes

# Answer
# Forth (gforth), 75 bytes

```
: f 0 do dup i + c@ dup 91 = if i s>f then 93 = if f>s . i . cr then loop ;

```

Try it online!

Abuses the floating-point stack, but allows using a `do loop` since the code doesn't (manually) touch the return stack.

### Explanation

1. Loop through characters in string
2. Check each character
    1. If equal to `[`, put on floating point stack
    2. if equal to `]` pop from floating point stack and output with current position

### Code Explanation

```
0 do                 \ start a loop from 0 to string-length
  dup                \ duplicate the starting address to avoid losing it
  i + c@             \ get the address of the current position and retrieve the character
  dup                \ duplicate the character, to allow checking twice
  91 = if            \ if char = [
    i s>f            \ store the current address on the floating point stack
  then               \ end the if-statement
  93 = if            \ if char = ]
    f>s .            \ pop the starting position from the float-stack and print
    i .              \ print the current position
    cr               \ output a newline
  then               \ end the if-statement
loop                 \ end the loop

```
> 2 votes

# Answer
# Retina, 36 bytes

```
L$v`\[((\[)|(?<-2>])|[^]])*
$.`,$.>`

```

Try it online! Explanation:

```
L

```

Generate a list from the match results.

```
$

```

Use the following substitution to generate the list instead of the matches.

```
v`

```

Allow matches to overlap.

```
\[((\[)|(?<-2>])|[^]])*

```

This is an application of .NET's balancing groups. The `[` is matched literally, then as many characters as possible are consumed. As each subsequent `[` is matched, the match is added to the `$2` stack. If that stack isn't empty, we can then match a `]`, removing the match from the stack. Otherwise, we can match anything that's not a `]` (the `[` was already matched earlier). The match stops when it meets the matching `]` for the `[`, since the `$2` stack is (now) empty at that point.

```
$.`,$.>`

```

The substiution consists of two variables separated by a comma. The `.` indicates that the length of the variable, rather than its value, be used. The `>` indicates that the variable should be evaluated in terms of the right-hand separator rather than the match. The `$`` variable refers to the prefix of the match, which means `$.`` gives the position of the `[`; the `>` modifier alters this to the prefix of the match's right separator, which gives the position of the matching `]`.
> 2 votes

# Answer
# SWI-Prolog 254 bytes

```
d([']'|T],I,[S|Z],M,R):-J is I+1,d(T,J,Z,[',','(',S,',',I,')'|M],R).
d(['['|T],I,S,M,R):-J is I+1,d(T,J,[I|S],M,R).
d([_|T],I,S,M,R):-J is I+1,d(T,J,S,M,R).
d(_,_,_,R,R).
m(X):-atom_chars(X,A),d(A,0,[],[']'],[_|R]),atomic_list_concat(['['|R],S),print(S).

```

Example:

```
?- m('!^45sdfd[hello world[[djfut]%%357]sr[jf]s][srtdg][]').
'[(49,50),(42,48),(8,41),(36,39),(20,33),(21,27)]'
true

```
> 2 votes

# Answer
# K (ngn/k), ~~38~~ 37 bytes

```
{b@0N 2#,/=(|':+\-/a)b:&|/a:"[]"=\:x}

```

Try it online!

`{` `}` function with argument `x`

`"[]"=\:x` two boolean lists for the occurrences of `"["` and `"]"`

`a:` assign to `a`

`|/` boolean "or" of the two lists

`&` where (at which indices) are the brackets?

`b:` assign to `b`

`-/` a list with 1 for `"["`, -1 for `"]"`, and 0 everywhere else

`+\` partial sums

`|':` pairwise maxima (each element max'ed with the previous one, the initial element remains the same)

This represents bracket depth for each character. We index it with `b` (juxtaposition is indexing) and get bracket depth only for the brackets.

`=` "group by" - a dictionary mapping depths to the indices at which they occur

`,/` concatenate the values in the dictionary, ignoring the keys

`0N 2#` reshape to a 2-column matrix (list of lists)

`b@` index `b` with each element of the matrix
> 1 votes

# Answer
# C (gcc), 87 bytes

```
f(char*Z){for(char*z=Z,*q=z;*z;*z++-93||printf("%d,%d;",*--q,z-1-Z))*z-91||(*q++=z-Z);}

```

Try it online!

# Explanation

To keep track of opening bracket's string indices, the input string is overwritten and used as a stack.

```
f(char*Z){          // take mutable input string
 for(char*z=Z,*q=z; // copy pointer to current string index, current stack index
 *z;                // loop through the entire string
 *z++-93||          // if z == ']'
   printf("%d,%d;", // decrement stack pointer,
    *--q,z-1-Z))    //  write bracket pair position
  *z-91||           // if z == '['
   (*q++=z-Z);}     // write bracket position onto stack, increment stack pointer

```

Try it online!
> 1 votes

# Answer
# Jelly, 20 bytes

```
=©ⱮØ[_/aÄ$+®ŻĠḊẎ_2s2

```

Try it online!

It has a side-effect on the register, hope it's allowed to be a function.
> 1 votes

# Answer
# Japt v1.4.5, 23 bytes

```
;Ë¥']?ApENo):D¥'[©NpE
A

```

Try it online!

### Unpacked & How it works

```
;UmDE{D==']?ApENo):D=='[&&NpE
A

;                              Use alternative set of initial variables
                               A = [] is used here
 UmDE{                         Map over each char of input string...
      D==']?                     If the char is closing bracket...
            ApENo)                 Push the current index and N.pop() to A
                  :D=='[&&       Otherwise, if the char is opening bracket...
                          NpE      Push the current index to N

A     Output A

```

The output is a flattened array of `[closing index, opening index]`. If the reversed order is not desired, adding `w` at the end does the job (+1 bytes).
> 1 votes

# Answer
## Common Lisp, 95 bytes

```
(lambda(u &aux s)(dotimes(p(length u))(case(elt u p)(#\[(push p s))(#\](print`(,(pop s),p))))))

```
Long version
```
(defun par (string &aux stack)
  (dotimes (pos (length string))
    (case (char string pos)
      (#\[ (push pos stack))
      (#\] (print (list (pop stack) pos))))))

```
Tests
```
((lambda(u &aux s)(dotimes(p(length u))(case(elt u p)(#\[(push p s))(#\](print`(,(pop s),p))))))
 "!^45sdfd[hello world[[djfut]%%357]sr[jf]s][srtdg][] ")

```

prints:

```
(21 27)
(20 33)
(36 39)
(8 41)
(42 48)
(49 50)

```
> 1 votes

# Answer
# CJam, 25 bytes

```
0q{"[]"#"_ \p_p "S/=~)}/;

```

Surprisingly competitive - loses only to Japt and Jelly \[**Edit**: and Charcoal and Stax :(\]

Try it online!

## Explanation

```
0                          Push 0.
 q                         Push the input.
  {                   }/   For each character in the input:
   "[]"#                     Find index of this character in the string "[]" (or -1 if not found).
                   =         Use this index to choose
        "       "S/            one of the following snippets
                    ~          and execute it:
         _                       If it was 0 ('['), duplicate the number on the stack.
           \p_p                  If it was 1 (']'), print the current number and the one under it.
                                 If it was -1, do nothing.
                     )       Increment the number on top of the stack.
                        ;  Delete the number.

```
> 1 votes

# Answer
# Charcoal, 20 bytes

```
ＦＬθ≡§θι[⊞υι]«Ｉ⊟υ,Ｉι⸿

```

Try it online! Link is to verbose version of code. Explanation:

```
ＦＬθ

```

Loop over the implicit range of the length of the input string.

```
≡§θι

```

Switch on the current character.

```
[⊞υι

```

If it's a `[` then push the current index to the predefined array variable.

```
]«Ｉ⊟υ,Ｉι⸿

```

If it's a `]` then pop the latest index from the array variable and print it and the current index separated by a comma and start a new line. Alternate output formats, if acceptable, would save some bytes: `]Ｉ⟦⊟υιω` saves 2 bytes but prints each index on a separate line, double-spacing the pairs of indexes; `]Ｉ⟦⊟υι` simply prints the indexes on separate lines, making it hard to distinguish them.
> 1 votes

# Answer
# Python 2, 109 bytes

```
def a(s,r=[],i=0):
 o=[]
 while i<len(s):exec["r+=[i]","o+=[(r.pop(),i)]",'']['[]'.find(s[i])];i+=1
 return o

```

Try it online!
> 0 votes

# Answer
# Pyth,  ~~28~~  26 bytes

```
{I#.e,t+lhfSI/LT`Y+._>Qk\]

```

Test suite.

~~At the moment it's longer than Mnemonic's approach~~, but I feel like I can golf this down a little and this fortunately also doesn't use Pythonically-imperative structures like `V`. The initial version was 36 bytes and also had numerous bugs.

### How it works

```
{I#.e,t+lhfSI/LT`Y+._>Qk\] – Full program. Takes a quoted string Q from STDIN.
   .e                      – Enumerated map. k = iteration index, b = current element.
                     >Qk   – Get the elements of Q at indices greater than k.
                   ._      – Generates all the prefixes of this.
                  +     \] – And append an "]" (for handling some edge-cases).
          f                – Filter over this list, with T = current element.
              L `Y             – For each character in str([]), "[]"...
             / T               – ... Count the occurrences of it in T.
           SI                  – And check if the values are sorted increasingly.
         h                 – Head. Retrieve the first element.
       +l                  – Get the length of this + k.
      t                    – Decrement (by 1).
     ,                     – And pair this value with k. Returns [i, k] where i is
                             the index of the corresponding ] and k is that of [.
  #                        – Filter this list by:
{I                             – The pair is invariant over deduplicating.

```
> 0 votes

# Answer
# Perl 5, 53 bytes

```
say"$-[0] ".($+[0]-1)while s/\[[^][]*\]/1x length$&/e

```

Run as `perl -nE '<above code snippet>'`. Takes input through stdin.

As usual, the optimal Perl solution to the problem is a regular expression. We attempt to match any pair of brackets which does not contain any pairs within it using a rather silly-looking character class (`s/\[[^][]*\]/.../`). If the match is successful, we replace the matched text with the digit `1` over and over again so that we don't accidentally match those brackets again, and we print out the indices of the match. Rinse and repeat.
> 0 votes

# Answer
# Stax, 13 bytes

```
é√p(l▓1½\á²ë(

```

Run and debug it

It uses the input stack to track open brace pairs. Here's the program unpacked, ungolfed, and commented.

```
F       iterate over input characters
 .][I   get the index of the character in the string "[]", or -1
 ^|cv   skip the rest of this iteration if index was -1
 i~     push the current iteration index to the input stack
 C      skip the rest of this iteration if index was 0
 \      form a pair with the top two items from the input stack
 JP     join with space, and print

```

Run this one
> 0 votes

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