title: Print 1 to 15, using different printers

text:
# Question
Title: Print 1 to 15, using different printers
Making a versatile integer printer is nice and all, but writing a single code that prints a lot of different numbers is cumbersome. Wouldn't it be easier to make a script that outputs a number, but also gives you a new script to get the next number?

**Challenge:**

Write a code that outputs a single integer `N` and an executable code. The next code should output `N+1` and a code that can output `N+2`. Continue this path until you reach `N = 15`. (The last printed number should be 15).

**Rules:**

* No input (assume the input is empty).
* Full program or function or other convenient formats are allowed.
* The first code should output `1`.
* You can't output leading zeros. I.e. you can't print `01` for `1`.
* The output must be on the format `N, Code_for_N+1`. Note that the output is separated by a comma and a single space. The code for `N+1` has no surrounding quotation marks. `N , Code_for_N+1` is not accepted (space in front of the comma). Trailing newlines are OK.
* The first character(s) of the output must be the number. (No leading spaces, or `ans = N`).
* The printed number should not be part of the next code (the code can contain this number, but you can't take the output number as part of the code)
    + Example: The output for `N=2` can be: `2, printer 2`. In this case, `printer 2` is the code for `N=3`. You can't use the entire output: `2, printer 2` as code for `N=3`.
* The scripts may be in different languages
* The datatypes are irrelevant (the number can be a string), but it can't be surrounded by anything (quotation marks, parentheses etc).
* If there is a code outputted for `N=15` then it must either print `STOP!` (see bonus), or don't print anything at all (not even a space or newline).
    + The code for `N=15` can not crash (but outputting to STDERR is OK).
    + You are disqualified if the output code for `N=15` prints `16` or anything else (except the bonus case).
* Built in quine operators are not allowed.
* Accessing the source file through the file system is not allowed.

**Bonus:**

-10 bytes if the code that prints 15 also produces a code that prints "`STOP!`"

**Examples using Python syntax:** (obviously, these will only work for the selected integers, not from 1 to 15.)

```
N = 1
print "1, print 2"
1, print 2

---
N = 15
print 15
15

---
N = 15   (Qualifies for the -10 bytes bonus)
print "15, print 'STOP!'"
15, print 'STOP!'

print 'STOP!'
STOP!

----

N = 15   (Qualifies for the -10 bytes bonus)
print "15, disp('STOP!')"
15, disp('STOP!')        (disp('STOP!') outputs STOP! in MATLAB)

----
N = 15   (This one is not OK. The submission is disqualified)
print "15, print 16"
15, print 16

```

Standard golfing rules apply! Smallest code (for N=1) in bytes win!

# Answer
> 39 votes
## Pyth + ///, 15 bytes - 10 = 5

```
pPt`S15", STOP!

```

This prints `1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, STOP!` in Pyth, by taking `range(1,15+1)` and stripping off the start and end brackets, and printing it immediately followed by ", STOP!".

The next fourteen programs are in ///, which directly outputs all programs that don't contain `/` or `\`. So the second program

```
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15

```

gives `2` and the third program `3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15`. The penultimate program, `15, STOP!`, prints `15, STOP!`, so the last program is just `STOP!`.

# Answer
> 31 votes
# JavaScript, 131238 - 10 = 131228 bytes

The naive approach turned out worse than expected. In hindsight I should have expected it. But I thought I'd share it anyway. Full code here.

Idea: Iteratively escaping and adding the `N-1, ...`

```
alert("14,alert(\"15, alert(\\\"STOP!\\\")\")")

```

# Answer
> 8 votes
## CJam, ~~26~~ ~~25~~ 24 bytes

```
1{", "2$)@"_~"](_F<@*}_~

```

Try it online.

The subsequent programs simply have the first number incremented. This runs the program 16 times.

---

Or with bonus for the same score:

```
1{", "\2$)_G<\@`+"_~"+"STOP!"`?}_~

```

Try it online.

The subsequent programs simply have the first number incremented. This runs the program 16 times.

Alternative solution for the bonus:

```
1{", "\2$)Gmd@`+"_~"+"STOP!"`\?}_~

```

# Answer
> 7 votes
# JavaScript (ES6), ~~62~~ 61 bytes - 10 bonus = 51 score

```
_=>"1, "+(f=n=>`_=>"`+(n<16?n+`, "+(${f(n+1)})`:`STOP!"`))(2)

```

## Explanation

A solution which does not read it's own source code and is also not ridiculously long.

The first program constructs all 15 other programs and nests them inside each other using a recursive function. I get around the backslash issue by nesting the functions themselves (which are then cast to strings during output) rather than strings.

```
_=>
  "1, "                // print the first number
  +(f=n=>`_=>"`+(      // f = recursive function for printing program N
    n<16?              // for programs 2 - 15:
      n+`, "+(${       // add N to the output of the nested function
        f(n+1)         // nest the code of program N + 1
      })`
    :`STOP!"`          // program 16 just outputs "STOP!" for the bonus
  ))(2)                // start from program 2

```

## Test

```
var nextProgram = '_=>"1, "+(f=n=>`_=>"`+(n<16?n+`, "+(${f(n+1)})`:`STOP!"`))(2)',
    n = 1;
while(nextProgram) {
  result.textContent += "Program " + n++ + ": " + nextProgram + "\n";
  var output = eval("(" + nextProgram + ")()");
  result.textContent += "   Output: " + output + "\n\n";
  var index = output.indexOf(",");
  nextProgram = index > 0 ? output.substr(index + 2) : null;
}
```

```
<pre id="result"></pre>
```

# Answer
> 5 votes
## JavaScript, ~~50~~ ~~47~~ ~~44~~ ~~42~~ 44* bytes

```
a=_=>(x=1)+(x<15?", a="+a:"").replace(x,x+1)

```

It's a function which extracts its own body (just `a`) and makes replacements in it. Getting the function body a built-in feature of JavaScript, though not being explicitly a quine operator (if it's invalid, will remove the answer).

```
a=_=>(x=1)+(x<15?", a="+a:"").replace(x,x+1);
alert(a());
```

In case it doesn't work properly embedded there (because for me it doesn't), you can see an example there.

---

* - looks like the snippet produces the result without `a=`, making further calls impossible

# Answer
> 5 votes
# Matlab, ~~226~~ 212 - 10 = 202 bytes

Thanks to @StewieGriffin for a few bytes=)

```
'awFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)

```

The first part is a string that represents the second line (below), the actual code (just shifted by 9). In Matlab, strings are matrices filled with characters, so you can easily perform the shifts by just adding/substracting a scalar. So the program just prints out the same string\* again, plus the same string but shifted which results in the code.

\*Not quite: The first byte is the counter which needs to be increased in each iteration.

The quine trick with the string was shamelessly stolen from here.

```
'awFjw|Dro)w1:26B?G:>DwF0\}xy*0Dnu|nDwFdw~v;|}{1w1:26B?2505)05<B5w1:24:5w1;Cnwm25<B5>B5w1;Cnwm26B500fDnwmDmr|y1w2';
n=ans;if n(1)-96>15;n='Stop!';else;n=[num2str(n(1)-96),', ',39,n(1)+1,n(2:end),39,59,n(2:end)-9,''];end;disp(n)

```

Here the last few lines of the sequence copied from the console:

```
>> 'mwFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)
13, 'nwFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)
>> 'nwFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)
14, 'owFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)
>> 'owFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)
15, 'pwFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)
>> 'pwFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)
STOP!

```

# Answer
> 5 votes
# Python 2.7.10, ~~196~~ 92 - 10 = 82 bytes

Whee!!! This was fun. Much shorter now. :P

```
n=1;a='n=%d;a=%r;print n,a%%(n+1,a)if n!=15else"STOP!"';print n,a%(n+1,a)if n!=15else"STOP!"

```

---

### Explanation:

I started with this:

```
a='a=%r;print a%%a';print a%a

```

That is just a simple quine. This is that with a counter added:

```
n=1;a='n=%d;a=%r;print n,a%%(n+1,a)';print n,a%(n+1,a)

```

`n` is a counter variable that is printed at the beginning. Then when its prints the `n=` part, it substitutes `n+1` for the `%d`. So from here it will count up infinitely.

And here is the final version. It adds an if clause to stop at 15, and prints "STOP!" as well.

```
n=1;a='n=%d;a=%r;print n,a%%(n+1,a)if n!=15else"STOP!"';print n,a%(n+1,a)if n!=15else"STOP!"

```

Old code:

```
a= ['if num==15:print"STOP!!!";exit()','print num','print"a=",a','print"num=",num+1', 'for s in a:print s']
num= 1
print num
if num==15:print"STOP!!!";exit()
print"a=",a
print"num=",num+1
for s in a:print s

```

~~Never going to win, but fun. :P~~ Much shorter now, though I still don't stand a chance. :P

# Answer
> 3 votes
## PowerShell, ~~(215-10)=205~~ ~~197~~ ~~167~~ ~~106~~ ~~104~~ 103 bytes

```
$d='$c=(,1*{2}).count;$d={0}{1}{0};(("$c, $d"-f[char]39,$d,($c+1)),$c)[$c-eq15]';"1, $d"-f[char]39,$d,2

```

(If your only tool is PowerShell, every problem looks like a nail. Wait...)

Essentially, we start with setting `$d` equal to a big-ole-lengthy string of an almost-quine of the original code. It outputs `1` and then `$d` with the format operator `-f` to correctly populate the `{0}`,`{1}`,`{2}` stand-ins, incrementing the `{2}` number in the `,1*{2}` section by one each time.

The `,x*y` operation in PowerShell creates a new array of `y` items, each of which is equal to `x`. For example, `,2*3` is equivalent to `@(2,2,2)`.

This means, the first output will be `1, $c=(,1*2).length;$d=(etc...)`, so when the second code is executed, `$c` will equal the count of the array `@(1,1)`, or `2`, etc. Note that `$c` isn't used as a variable in the original code, just in subsequent runs.

Stops when it prints 15 by simply calculating whether `$c` equals `15` and then indexing into an array, the 0th element is `$c, $d` as described above, the other is just `15`. Thus, when `$c` is 15, it'll output `15` and nothing else. Doesn't qualify for the bonus, because `"15, {0}STOP!{0}"` is 5 characters too long for the -10 to be worthwhile.

Requires a PowerShell terminal of width \> ~150. Or for you to manually remove the extra linebreak (that the terminal *helpfully* inserts on output wrap) when copy-pasting the code. Or for you to capture output into a variable and then re-execute that variable. Etc.

Edit 1 -- Saved some bytes by removing the "STOP!" wording.
Edit 2 -- Durr, don't use .length each time, just call it once
Edit 3 -- Doesn't need to be a quine, so the initial run can be a lot shorter
Edit 4 -- Changed from using strings to arrays to calculate `$c`, which saved two bytes. I'm pretty sure this is almost optimal for this approach.
Edit 5 -- Saved another byte by directly counting equality rather than modding

# Answer
> 2 votes
# Befunge, 57 - 10 = 47 bytes

```
1:'!`'#*j:.',,1+:9`''*'0++,1#;:0g:48*`j@,1+;"!POTS",,,,,@

```

This one is awesome. Try it here.

# Answer
> 2 votes
## JavaScript, 79 - 10 = 69 bytes

```
s='STOP!';for(i=15;i;){s=i--+',alert("'+s.replace(/[\\"]/g,"\\$&")+'")'};alert(s)

```

Without using `Function.prototype.toString` in any way at all.

# Answer
> 2 votes
## SMBF, 28 bytes

`\x10` represents a literal byte (decimal value 16). The integer is output as an integer (byte). So the first *character* output is `\x01`. The program then prints ", ". When printing its own source, it prints an extra `+` at the beginning.

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

```

Explanation:

```
+.                                  Increment number and print
  <-                                Pre-decrement loop counter
    <<.>.>                          Print comma and space from own source
          [             ]           Only execute if loop counter != 0
           [<]>.                    Move to left of source, then print `+`
                [.>]                Print entire source.
                    <[-]            Zero out the loop counter so this program halts.
                         , \x10     The comma, space, and loop counter used earlier.
                                    Input is empty, so `,` doesn't do anything.

```

Note that you cannot run this in a standard interpreter because it requires a hex literal in the input. You also need a special terminal for hex output to work properly.

# Answer
> 2 votes
## Batch, 73 + 5 - 10 = 68 bytes

```
@set a=STOP!
@for /l %%a in (15,-1,1)do @set a=%%a, @echo !a!
@echo %a%

```

Requires `CMD /V:ON` so I added 5 bytes for that.

# Answer
> 2 votes
## Python 2.7, 107 characters

By using recursion and *not* writing a quine, I thought I could save a lot, which is true, but not good enough. Although not a winner, I think the approach is fun to share.

I started by making up a string for N=4, escaping the `\` and `"` characters.

```
print "1, print \"2, print \\\"3, print \\\\\\\"4, print \\\\\\\\\\\\\\\"STOP!\\\\\\\\\\\\\\\"\\\\\\\"\\\"\""

```

Then I created a lambda function that creates this string, based on a start index and a stop index, using recursion. This is it:

```
l=lambda n,m:str(n)+", print "+"\\"*(2**(n-1)-1)+"\""+l(n+1,m)+"\\"*(2**(n-1)-1)+"\"" if n<m else "STOP!"

```

Use it like this:

```
print l(1,15)

```

Output: *\[32902 characters, too long to handle\]*

So, it seems that my kolmogorov complexity approach isn't that successful ;-)

# Answer
> 1 votes
# , 30 chars / 47 bytes (non-competitive)

```
⟮a=1)+(a<ḏ?⬬+ⒸⅩ222+ᶈ0:⬯)ē(a,⧺a

```

`Try it here (Firefox only).`

Finally found a good ol' true quine for .

# Explanation

Here's the true quine that I used: `⟮ⒸⅩ222+ᶈ0`

You see it in my answer? Hopefully, y'all will be able to expand from there.

# Answer
> 1 votes
# Bash, ~~78~~ ~~74~~ 73 - 10 = 63 bytes (Example, can't win)

```
p='if(($((++a>15))));then unset a p;fi;echo ${a-STOP\!}${p+, $p}';eval $p

```

Coming in late, but saw bash hadn't been tried so gave it a go. First gulf challenge and quine-like puzzle. They're fun!

### Explanation:

This works because `a` steps from 1 to 15 and is then `unset` along with `p`. The script (stored in `p`) prints them both out if they're `set` and "STOP!" otherwise. The initially `unset` `a` is `set` to 0 because it appears in an arithmetic expansion.

# Answer
> 1 votes
## Keg+PHP, 19-10=10 bytes

```
ï_(. \,,,)\!POTS(,

```

Counts from 1 to 15 and then stops. TIO

## Keg, 13 bytes

```
ï_(. \,,,).

```

# Answer
> 1 votes
# Python 2, 68 (-10) bytes, Python 3, 69 (-10) bytes

My previous answers were incorrect. That's now fixed :)

## Python 2 (68 bytes, 58 points)

```
a,b="print'%d, a,b=%r,%d;exec a'%(b,a,b+1)*(b<16)or'STOP!'",1;exec a

```

Try it online!

## Python 3 (69 bytes, 59 points)

```
a,b="print(f'{b}, a,b=%r,{b+1};exec(a)'%a*(b<16)or'STOP!')",1;exec(a)

```

Try it online!

## How it works:

* I started from the quine `a="print("a=%r;exec(a)"%a);exec(a)"`
* I assign `b` to the value to be printed
* Then I print `b,`  and the quine replacing `b` by `b+1`
* If `b` is equal to `16`, I print `STOP!` intead

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


# Question
Title: Rewrite strings without changing their order
## Lexicographic Ordering

For this challenge we will be talking about the lexicographic ordering of strings. If you know how to put words in alphabetical order you already understand the basic idea of lexicographic ordering.

Lexicographic ordering is a way of ordering strings of characters.

When comparing two strings lexicographically, you look at the first character of each string. If one of the strings is empty and has no first character that string is smaller. If the first characters are different then the string with the smaller first character is smaller. If the characters are equal we remove them from the strings and compare the rest of the strings

Here is a Haskell program that implements this comparison

```
compare :: Ord a => [a] -> [a] -> Ordering
compare [] [] =
  EQ
compare [] (y : ys) =
  LT
compare (x : xs) [] =
  GT
compare (x : xs) (y : ys) =
  if
    x == y
  then
    compare xs ys
  else
    compare x y

```

Lexicograpic ordering has some interesting properties. Just like integers, every string has a next biggest string. For example after `[1,0,1,0]` there is `[1,0,1,0,0]`, and there is nothing in between. But unlike integers there are strings which have an infinite number of strings between each other. For example `[0]` and `[1]`, all strings of more than 1 `0` are greater than `[0]` but less than `[1]`.

## Challenge

In this challenge you will write a program or function (from now on just called "function"), which maps binary strings (that is, strings made of an alphabet of two symbols) to ternary strings (strings made of an alphabet of three symbols).

Your function should be *bijective*, meaning that every string gives a unique output, and every ternary string is the output for some input.

Your function should also be *monotonic*, meaning that it preserves comparisons when applied

$$ x \< y \iff f(x) \< f(y) $$

Where \\$\<\\$ is the lexicographic ordering of the strings.

## Scoring

This is so answers will be scored in bytes with fewer being better.

## IO

You may take input and produce output as a string with chosen characters for the sets of 2 and 3 symbols, or as a list / array / vector of integers.

## Testing

It's rather hard to make test cases for this. However it should be noted that when given a string of only `0`s your code must give back the same string. So I can give the following test cases

```
[] -> []
[0] -> [0]
[0, 0, 0] -> [0, 0, 0]

```

However this doesn't go very far in terms of testing.

So I recommend you also run a random battery of strings checking that

* The monotonicity property holds
* Your function preserves the number of `0`s on the end

# Answer
> 8 votes
# Haskell, 41 bytes

```
f x|sum x<1=x
f(0:y:x)=y:f x
f(1:x)=2:f x

```

Try it online!

Here's a solution. Just to show that this is possible and give a potential starting point for others.

## Explanation

The first thing we can notice is that any valid \\$f\\$ must preserve the number of zeros at the end of the input in the output.

The proof of this is pretty simple. Lets say we have some string \\$x\\$. We know that there are no strings between \\$x\\$ and \\$x\mathbin{|}0\\$ (here \\$\mathbin{|}\\$ represents appending a character to a string). Thus there can be no strings between \\$f(x)\\$ and \\$f(x\mathbin{|}0)\\$. If there were some string \\$y\\$ such that \\$f(x) \< f(y) \< f(x\mathbin{|}0)\\$, then it would have to be that \\$x \< y \< x \mathbin{|} 0\\$. So since there are no strings between \\$f(x)\\$ and \\$f(x\mathbin{|}0)\\$, then \\$f(x\mathbin{|}0) = f(x)\mathbin{|}0\\$.

So this allows us to write the first line of our program

```
f x|sum x<1=x

```

Which says if we get a list of only \\$0\\$s then output that list intact.

It might be tempting to say that *all* zeros should be preserved in the output, not just trailing ones. However this ends up not being possible, I will leave the proof of this as an exercise for the reader.

Now the task is to translate strings with no trailing zeros, while preserving order. The way I chose to do this is pretty simple. We go left to right replacing certain sequences with the correct symbols. If we see a zero we replace read it as the next symbol (and skip over that symbol), there must be a next symbol since otherwise there would be a trailing \\$0\\$.

```
f(0:y:x)=y:f x

```

If the symbol is \\$1\\$ we read it as \\$2\\$.

```
f(1:x)=2:f x

```

# Haskell, ~~52~~ 48 bytes

*4 bytes saved by ovs*

```
f(0:x)=0:f x
f(1:x)|sum x>0,z:y<-x=1+z:f y
f x=x

```

Try it online!

This is a different bijection discovered by a friend of mine and golfed by me.

# Answer
> 4 votes
# Jelly, 10 bytes

```
2ḢḢ?;ßƊ¹Ẹ?

```

A monadic Link that accepts a list (of \\$\\{0,1\\}\\$) and yields a list (of \\$\\{0,1,2\\}\\$).

**Try it online!**

### How?

Results in the same mapping as used by Wheat Wizard.

```
2ḢḢ?;ßƊ¹Ẹ? - Link: list, A
        Ẹ? - if: any?
      Ɗ    - then: last three links as a monad - f(A):
  Ḣ?       -   if: head (leftmost element of A (or 0 if empty);
                         changes A in place)
2          -   then: literal two
 Ḣ         -   else: head (leftmost element of augmented A (or 0 if empty);
                           changes A in place again)
     ß     -   call this Link again -> f(augmented A)
    ;      -   concatenate
       ¹   - else: identity (yield A)

```

# Answer
> 2 votes
# JavaScript (Node.js), 34 bytes

```
s=>s.replace(/0(?=.*2)./g,t=>t/2);

```

Try it online!

Wheat Wizard♦'s idea using the allowance of custom char

# Answer
> 1 votes
# Retina, 20 bytes

```
/0*$/%`1(.)
$.($1*__

```

Try it online! Explanation: Uses @WheatWizard's friend's mapping.

```
/0*$/%`

```

Match trailing zeros and temporarily exclude them from the following substitution.

```
1(.)
$.($1*__

```

Match a `1` followed by a digit and replace it with 1 more than the digit, i.e. `11` becomes `2`, `10` (in the middle) becomes `1`, but other digits are unaffected.

# Answer
> 1 votes
# Charcoal, 20 bytes

```
≔Ｉ⪪⮌Ｓ¹υＷΣυ¿⊟υ2Ｉ⊟υＦυ0

```

Try it online! Link is to verbose version of code. Explanation: Uses @WheatWizard's mapping.

```
≔Ｉ⪪⮌Ｓ¹υ

```

Reverse the input, split it into digits, and cast the digits to integer.

```
ＷΣυ

```

Repeat while there are still `1`s left in the input...

```
¿⊟υ2

```

... if the current digit is a `1` then print a `2`...

```
Ｉ⊟υ

```

... otherwise print the next digit.

```
Ｆυ0

```

Print any trailing zeros.

---
Tags: code-golf, string, math, open-ended-function
---


title: I'm Lazy: Close my Superparens

text:
# Question
Title: I'm Lazy: Close my Superparens
Picolisp has a feature called "super parentheses":

> Brackets ('\[' and '\]') can be used as super parentheses. A closing bracket will match \[all parentheses to and including\] the innermost opening bracket, or \[if there are no unmatched opening brackets\] all currently open parentheses. src

Taking a string containing only the characters `[]()` (and newline if your language requires it), remove all closing brackets `[]` and replace them with the corresponding parentheses. A `[` is replaced with a `(`, but your program will not have to handle a `[` or `(` without a matching `]` or `)`. Output may contain trailing newlines.

`]` matches as many open parens as possible until it hits a `[` at which point it has to stop --DJMcMayhem

## Examples

```
((((] -> (((())))
(([()(()])) -> (((()(()))))
) or ( or ] or [) or ([(]  -> invalid, do not need to handle
(] -> ()
((](] -> (())()
[] -> ()
[(] -> (())
[[()(]] -> ((()()))
((][(] -> (())(())
(([((](] -> ((((()))()))

```

---

This is , shortest code per language wins.

# Answer
# Python 3,  ~~117~~  115 bytes

-2 thanks to ovs (use mod 8 in place of mod 6 allowing the bitwise-OR in place of exponentiation; remove a space from `5!=x or` with `x!=5or`.)

My golf of hyper-neutrino's Python 3 answer.

```
k=[0]
o=""
for c in input():x=ord(c)%8;o+="() ( )"[x]*(x<5or k.pop());k=[0]+k+[1]*(x==3);k[-1]+=x<3and-x|1
print(o)

```

**Try it online!**

Remaps `'(', ')', '[', ']'` to the integers `0, 1, 3, 5` (`x`) with `x=ord(c)%8` then uses this for the decision making process to save quotes.

Inlines all the decision-making to avoid newlines, tabs and `if-elif-else` syntax.

Gets the character to output for the current input character by using `x` to index into `"() ( )"`.

When the current character is one of `"()"` we need to add or subtract one, respectively, from the last entry in the counts list, `k`. To do so we check if the character is one of `"()"` we use `x<3` (`False`, the value for `'['` and `']'` is equivalent to `0`) and logical-AND that with `-x` bitwise-OR with `1` (`-x|1`) translating the `0` of `(` to `1` and the `1` if `)` to `-1`. Thus we can add `x<3and-x|1`.
> 9 votes

# Answer
# Charcoal, 26 bytes

```
ＦＳ≡ι)⊟υ]Ｗ∧υ⊟υκ«(Ｆ⁼ι[⊞υω⊞υ)

```

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

```
ＦＳ≡ι

```

Switch over each character of the input.

```
)⊟υ

```

If it's a `)` then pop and print the top of the stack (which should always be a `)` at this point).

```
]Ｗ∧υ⊟υκ

```

If it's a `]` then pop and print the top of the stack until it becomes empty or an empty string was popped.

```
«(Ｆ⁼ι[⊞υω⊞υ)

```

Otherwise, print a `(`, push an empty string to the stack if it was a `[`, and push a `)` to the stack.
> 9 votes

# Answer
# PicoLisp, 211 bytes

```
(de f(x k)[or k(set'k(0][set'a(car x][set'b(cdr x](if x(cond[(="("a)(prin a)(f b(cons(+(car k)1)(cdr k][(=")"a)(prin a)(f b(cons(-(car k)1)(cdr k][(="["a)(prin"(")(f b(cons 1 k](1[prin(need(car k)")"](f b(cdr k]

```

Try it online!

-1 byte thanks to Wzl

First time using picolisp, so it's probably very badly golfed.
> 8 votes

# Answer
# Python 3, 139 bytes

```
o=""
k=[0]
for c in input():
	if"["<c:o+=")"*k.pop();k=[0]+k
	elif"Z"<c:k+=[1];o+="("
	elif")">c:k[-1]+=1;o+=c
	else:k[-1]-=1;o+=c
print(o)

```

Try it online!

-4 bytes thanks to caird coinheringaahing
bugfix thanks to Jonathan Allan

trivial attempt, will try to golf it down more later
> 5 votes

# Answer
# JavaScript (ES6),  ~~96~~  94 bytes

Expects an array of characters. Returns a string.

```
a=>a.map(c=>c>{}?')'.repeat(b.pop()):b.push(-~(c>')'?c='(':b.pop()-2*(c>'(')))&&c,b=[]).join``

```

Try it online!

### Commented

```
a =>                // a[] = input
a.map(c =>          // for each character c in a[]:
  c > {} ?          //   if c is ']':
    ')'             //     use ')'
    .repeat(        //     and repeat it as many times as
      b.pop()       //     recorded in the last slot,
    )               //     which is removed from b[]
  :                 //   else:
    b.push(         //     push in b[]:
      -~(           //
        c > ')' ?   //       if c is '[':
          c = '('   //         update c to '(' and push 1 (a new slot)
        :           //       else
          b.pop()   //         update the last slot (it may be undefined):
          - 2 *     //           increment it if c is '('
          (c > '(') //           decrement it if c is ')'
      )             //
    )               //     end of push()
    && c,           //     yield c
  b = []            //   start with b[] = empty array
).join``            // end of map(); join everything

```
> 5 votes

# Answer
# Retina 0.8.2, 49 bytes

```
+`(^|\[)(((\()|(?<-4>\)))*)]
$.1$*($2$#4$*)$.1$*)

```

Try it online! Link includes test cases. Explanation:

```
+`

```

Repeat until no more replacements can be made.

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

```

Starting at the beginning of the string or at a `[`, start counting `(`s, but subtract 1 for every `)`, until a `]` is reached.

```
$.1$*($2$#4$*)$.1$*)

```

Append `)`s according to the count of remaining `(`s, and if we started at a `[` then wrap the whole thing in `)`s (because the count of `(`s doesn't include the initial `[`).
> 4 votes

# Answer
# JavaScript (ES6), 96 bytes

```
f=s=>s>(s=s.replace(/.([()]*)]/,(_,m)=>'('+m+')'.repeat(3+m.length-2*m.split`)`.length)))?f(s):s

```

Try it online!
> 3 votes

# Answer
# Pip, 46 bytes

```
L#aaR:`((\[|^)[()]*)]`{b.')X#b-2*(')Nb)R'['(}a

```

Try it online!

Algorithm:

* Find the first pair of square brackets with only parentheses between them (the opening bracket is optional if we're at the beginning of the string) using regex.
* Call the regex match minus the final bracket `b`. Replace the match (including the bracket) with:
    + `b`,
    + concatenated to a number of `)` equal to the length of `b` minus two times the number of closing parens in `b`,
    + with `[` replaced with `(`
* Do that as many times as there are characters in the input (overkill, but gets the job done).
* Print the result.

---

Different algorithm, **also 46 bytes**:

```
Fca{l|:^0cLT0?@l+:v**A OccQ'[?lPU1&O'(O')XPOl}

```

Try it online!

Treating the list `l` as a stack, loop over each character in the input:

* If the stack is empty, put a 0 on it.
* If the character is a parenthesis, output it and increment/decrement the top of stack.
* If the character is an open square bracket, push a 1 to the stack and output an open parenthesis.
* If the character is a close bracket, pop the stack and output that many close parentheses.
> 3 votes

# Answer
# Red, ~~131~~ 119 bytes

-12 bytes thanks to @9214

```
func[a][do{s:[""""]}parse a[any["("(insert s/1")")|")"(take s/1)|
change"[""("(insert s copy")")| change"]"(take s)]]a]

```

Try it online!
> 3 votes

# Answer
# Ruby 3.0.1, ~~123~~ ~~93~~ 92 bytes

Expects an array of characters and returns an array of characters

```
->x{*a=0
x.map{|c|c<?*?a[-1]+=(c<?)?1:-1):c<?]?(a<<0;c=?():c=?)*a.pop+(a[0]??):c*(*a=0));c}}

```

Old explanation:

```
-> x {
  a=[0] # this is the "stack"
  x.map do |c| # for each character `c` in input
    case c
    when ?( # ? creates a one-character string. Shorter than '('
      a[-1] += 1 # increment the top of the stack
    when ?)
      a[-1] -= 1 # decrement the top of the stack
    when ?[
      a << 0 # push a new element, 0, onto the stack
      c = ?( # 'output' an open paren in place of this character
    when ?]
      c = ?) * a.pop + # remove the last element of the array, and print that many closing parens.
      # however, we need to print another closing paren iff the stack isn't empty after we popped it.
        ( a[0] ? # ternary. a[0] is nil(falsy) if the array is empty, but 0 is truthy
          ?) : # if the array isn't empty, add another close parent
          # if the array is empty, we need to add nothing, but also add a 0 onto the array.
          # `a<<0` is shorter, but evaluates to the array `a`.
          # `a[0]=0` evaluates to 0.
          # any string * 0 is the empty string, so we use `c` since it's shorter than `""`
          c*(a[0]=0)
        )
    end
    c #last value evaluated is implicitly returned
  }
}

```
> 2 votes

# Answer
# Vyxal `ṠJs`, 32 bytes

```
0⅛ƛk(nc[k)k-ĿI¼+⅛|\[=[1⅛\(|\)¼⌊*

```

Try it Online! (Try all testcases!)

```
0⅛ƛk(nc[k)k-ĿI¼+⅛|\[=[1⅛\(|\)¼⌊*

0⅛                    Set the global array to [0]
  ƛ                     For each char n in input:
       [         |        If...
   k(nc                   n is in "()":
            Ŀ               Transliterate...
        k)                  n's index in ")("...
          k-                into [-1, 1]
             I              Cast to integer
              ¼+⅛           Add to top of global stack

|                         Otherwise...
    [    |                If...
 \[=                      n is '[':
     1⅛                     Push 1 to the global array
       \(                   Push "(" for output
         |                Otherwise:
              *             Repeat...
          \)                the string ")"...
            ¼⌊              pop(global_array) times

```
* \- treat `[]` as the string ``[]``, not an empty array
* `Js` \- output properly
> 1 votes

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


title: Draw an ASCII house

text:
# Question
Title: Draw an ASCII house
This is a window:

```
---
| |
---

```

Let's add some walls `|`. Put two spaces on either side of it so that the window has plenty of room.

```
|  ---  |
|  | |  |
|  ---  |

```

Now let's add a roof and a ceiling. To keep the window in the middle of the room, let's add one more row above it and below it.

```
---------
|       |
|  ---  |
|  | |  |
|  ---  |
|       |
---------

```

Now, just add a roof. Put a slash as far left as possible, and a backslash as far right as possible, and we have this:

```
/       \
---------
|       |
|  ---  |
|  | |  |
|  ---  |
|       |
---------

```

Then move the slash up one and right one. Move the backslash up one and left one:

```
 /     \
/       \
---------
|       |
|  ---  |
|  | |  |
|  ---  |
|       |
---------

```

Repeat until the two slashes meet, then add an asterisk where they meet:

```
    *
   / \
  /   \
 /     \
/       \
---------
|       |
|  ---  |
|  | |  |
|  ---  |
|       |
---------

```

And you're done! This is a 1x1 house. a 2x2 house would look like this:

```
        *
       / \
      /   \
     /     \
    /       \
   /         \
  /           \
 /             \
/               \
-----------------
|       |       |
|  ---  |  ---  |
|  | |  |  | |  |
|  ---  |  ---  |
|       |       |
|-------|-------|
|       |       |
|  ---  |  ---  |
|  | |  |  | |  |
|  ---  |  ---  |
|       |       |
-----------------

```

and a 3x2 house:

```
            *
           / \
          /   \
         /     \
        /       \
       /         \
      /           \
     /             \
    /               \
   /                 \
  /                   \
 /                     \
/                       \
-------------------------
|       |       |       |
|  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |
|       |       |       |
|-------|-------|-------|
|       |       |       |
|  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |
|       |       |       |
-------------------------

```

# The challenge

You must write a full program that takes two integers, x and y, and prints a house that is *X* rooms wide and *Y* rooms tall. Your program should be able to handle houses up to 10x10. IO can be in any reasonable format. Trailing spaces on each line are allowed, and one trailing newline is allowed.

Shortest answer in bytes wins.

# Answer
# Vim ~~122~~, 89 Keystrokes

```
"aDJ"bD9i-<esc>Y2pVr <C-v>jr|$.Y4p3l<C-v>jljlr-jR| |<esc>{l<C-v>}d@apjdG@bp}Vr-{YPVr r/$r\qqYPllxx|P@qq@qddr*

```

Try it online!

I've improved my vim-golfing skills significantly since I posted this answer, so I decided to go back and write this whole thing from scratch. Saved thirty-three bytes in the process!

Input is assumed to be on two separate lines, so that the buffer looks like this before you start typing:

```
3
4

```

I had a very detailed explanation, but I don't feel like writing it all over again from the beginning... \>\_\< Check out the revision history if you still want to see it.
> 12 votes

# Answer
## Python 3.6 (pre-release), ~~221~~ ~~210~~ 203 bytes

```
x,y=eval(input())
w=8*x+1;p='-'*w+'\n'
for v in['*',*[f'/{" "*i}\\'for i in range(1,w-1,2)],p+p.join([''.join(f'{"".join([f"|{(a*3)[:3]:^7}"]*x)}|\n'for a in(*' -','| |',*'- '))]*y)+p]:print(v.center(w))

```

Reads 2 integers (separated by comma) from stdin, prints the house to stdout.

Readable version:

```
x, y = eval(input())
w = 8 * x + 1 # total width (in characters)
p = '-' * w + '\n' # floors
for v in [
    '*', # asterisk
    *[f'/{" "*i}\\' for i in range(1, w-1, 2)], # roof
    p + p.join([''.join(f'{"".join([f"|{(a*3)[:3]:^7}"]*x)}|\n' for a in (*' -','| |',*'- '))]*y) + p # rooms
]:
    print(v.center(w))

```
> 8 votes

# Answer
## Python 2, ~~190~~ 181 bytes

```
w,h=input();W=w*4
for i in range(~W,h*6+1):print['-'[i%(h*6):]*(W-~W)or['  %s  '%' -|-  - -  -|- '[~i%6::5],'-'*7][i%6<1].join('|'*-~w),' '*~i+['/%*c'%(w*8-~i*2,92),'*'][W<-i]][i<0]

```

Pretty sure there's much to golf, especially the windows, but here's something for now. Input width and height comma-separated, e.g. `1,2`.

Quick and rough explanation:

```
                *          <--- i = ~W = -w*4 - 1.    <---\
               / \         <--\ i = -W = -w*4             | Preceding spaces
              /   \           |                           | are calculated
             /     \          |                           | the same way
            /       \      <--/ i = -1                <---/
   /--->    ---------      <--- i = 0
   |        |       |      <--\ i = 1                 <---\
Check       |  ---  |         |                           | Calculate inner string
i%(h*6)     |  | |  |         |                           | and use to join '|'s
is zero     |  ---  |         |                           | (ditto with |-------|)
   |        |       |      <--/ i = h*6 - 1           <---/
   \--->    ---------      <--- i = h*6

            ^       ^
            \-------/

          W-~W = w*8 + 1

```
> 6 votes

# Answer
# JavaScript (ES6), ~~292~~ ~~270~~ ~~238~~ ~~215~~ 200 bytes

*Thanks @Neil for helping trim this down!*

```
a=>b=>[(p=(c,d=' ')=>d.repeat(c))(m=4*a)+'*',...[...Array(m)].map((c,i)=>p(--m)+`/${p(i*2+1)}\\`),y=p(8*a+1,'-')].join`
`+p(b,`
`+[x=p(a,'|'+p(7)),w=p(a,'|  ---  '),p(a,'|  | |  '),w,x,y].join`|
`)

```

Call as: `F(a)(b)`

Builds the roof, then assembles the core house with layered string repeats.
> 3 votes

# Answer
# Ruby, Rev B 165 bytes

```
w=1-2*r=-4*x=gets.to_i
puts (r-1..h=6*gets.to_i).map{|n|n<0?(n<r ??*:?/+' '*(w+n*2)+?\\).center(w):n%h<1?(?-*w):'|CCBABCC'.tr('CBA','   | \-'[1222>>n%6*2&6,3])*x+?|}

```

uses a single loop and several other golfing tricks.

# Ruby, Rev A 179 bytes

```
w=1+8*x=gets.to_i
y=gets.to_i
b=(0..x*4).map{|n|(n<1??*:?/+' '*(n*2-1)+?\\).center(w)}
a=(2..y*6).map{|n|('|CCBABCC'.tr('CBA','   | \\-'[4888>>n%6*2&6,3]))*x+?|}
puts b,s=?-*w,a,s

```

**Ungolfed**

```
  x=gets.to_i
  y=gets.to_i

  w=x*8+1                                  #calculate width of house

  b=(0..x*4).map{|n|                       #design a roof line by line
    (n<1??*:?/+' '*(n*2-1)+?\\).center(w)  #first line is *, second line is /[spaces]\
  }                                        #centre correctly to the width of the house by padding

  a=(2..y*6).map{|n|                       #design a front facade line by line
    ('|CCBABCC'.                           #template for each row
      tr('CBA','   | \\-'[4888>>n%6*2&6,3])#substitute CBA for 3 characters from the string according to magic number 4888
    )*x+?|                                 #we need x copies, finishing with a |
  }

  puts b,s=?-*w,a,s                        #print a roof, a line of -, a facade and another line of -

```
> 2 votes

# Answer
# C++, 258 Bytes Test Here

```
#include<cstdio>
int main(){for(int r=10,c=10,x,y,q,u,h=c*4,w=h*2,i=0;i<h+r*8+2;i++)for(q=0;q<w+2;q++)x=q%8,y=i%8,u=(i-(h+1))%8,putchar(q==w+1?10:i<=h?!i&&q==h?42:i==h-q?47:i==q-h?92:32:!u||(u==3||u==5)&&x>2&&x<6?45:!x||u==4&&(x==3||x==5)?124:32);return 0;}

```

Result:

```
                                        *
                                       / \
                                      /   \
                                     /     \
                                    /       \
                                   /         \
                                  /           \
                                 /             \
                                /               \
                               /                 \
                              /                   \
                             /                     \
                            /                       \
                           /                         \
                          /                           \
                         /                             \
                        /                               \
                       /                                 \
                      /                                   \
                     /                                     \
                    /                                       \
                   /                                         \
                  /                                           \
                 /                                             \
                /                                               \
               /                                                 \
              /                                                   \
             /                                                     \
            /                                                       \
           /                                                         \
          /                                                           \
         /                                                             \
        /                                                               \
       /                                                                 \
      /                                                                   \
     /                                                                     \
    /                                                                       \
   /                                                                         \
  /                                                                           \
 /                                                                             \
/                                                                               \
---------------------------------------------------------------------------------
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
---------------------------------------------------------------------------------
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
---------------------------------------------------------------------------------
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
---------------------------------------------------------------------------------
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
---------------------------------------------------------------------------------
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
---------------------------------------------------------------------------------
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
---------------------------------------------------------------------------------
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
---------------------------------------------------------------------------------
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
---------------------------------------------------------------------------------
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
---------------------------------------------------------------------------------
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |       |       |
|       |       |       |       |       |       |       |       |       |       |
---------------------------------------------------------------------------------

```
> 2 votes

# Answer
# C++, 282 bytes, fixes the problems with the previous entry:

```
#include<cstdio>
int main(){for(int r=2,c=2,x,y,q,u,h=c*4,w=h*2,i=0;i<h+r*6+2;i++)for(q=0;q<w+2;q++)x=q%8,y=i%8,u=(i-h-1)%6,putchar(q==w+1?10:i<=h?!i&&q==h?42:i==h-q?47:i==q-h?92:32:!u&&x||!u&&(i<h+2||i==h+r*6+1)||(u==2||u==4)&&x>2&&x<6?45:!x||u==3&&(x==3||x==5)?124:32);return 0;}

```

Output:

```
        *
       / \
      /   \
     /     \
    /       \
   /         \
  /           \
 /             \
/               \
-----------------
|       |       |
|  ---  |  ---  |
|  | |  |  | |  |
|  ---  |  ---  |
|       |       |
|-------|-------|
|       |       |
|  ---  |  ---  |
|  | |  |  | |  |
|  ---  |  ---  |
|       |       |
-----------------

```
> 2 votes

# Answer
# C#, 361 353 bytes

```
string b(int w,int h){string m="",s,f,o=m,x,y,n="\n",p="|",q=" ";int i=0,v=w*4;Func<int,string,string>r=(j,c)=>{for(s="";j-->0;)s+=c;return s;};m+=r(v,q)+"*\n";for(;i<v;)m+=r(v-i-1,q)+'/'+r(i++*2+1,q)+"\\\n";f=r(w*8+1,"-");m+=f;x=n+r(w,p+r(7,q))+p;y=n+r(w,"|  ---  ")+p;o=x+y+n+r(w,"|  | |  ")+p+y+x;for(i=1;i++<h;)m+=o+x.Replace(q,'-');return m+o+n+f;}

```

### Full Program:

```
using System;
class House
{
    static int Main()
    {
        var x = new House();
        Console.WriteLine(x.b(1,1));
        Console.WriteLine();
        Console.WriteLine(x.b(2,2));
        Console.WriteLine();
        Console.WriteLine(x.b(2,3));
        Console.WriteLine();
        Console.WriteLine(x.b(9,9));
        Console.WriteLine();
        Console.Read();
        Console.WriteLine(x.b(10, 10)); // Looks broken because Bash to small
        Console.Read();
        return 0;
    }

    string b(int w,int h){string m="",s,f,o=m,x,y,n="\n",p="|",q=" ";int i=0,v=w*4;Func<int,string,string>r=(j,c)=>{for(s="";j-->0;)s+=c;return s;};m+=r(v,q)+"*\n";for(;i<v;)m+=r(v-i-1,q)+'/'+r(i++*2+1,q)+"\\\n";f=r(w*8+1,"-");m+=f;x=n+r(w,p+r(7,q))+p;y=n+r(w,"|  ---  ")+p;o=x+y+n+r(w,"|  | |  ")+p+y+x;for(i=1;i++<h;)m+=o+x.Replace(q,'-');return m+o+n+f;}

    // Without extra vars
    string b1(int w, int h)
    {
        string m = "", s, f, o = m, x, y;
        int i = 0, v = w*4;
        Func<int,string,string> r = (j,c) => {
            for(s = ""; j-->0;) s += c;
            return s;
        };
        /// Roof
        m += r(v, " ") + "*\n";
        for (; i < v;) m += r(v - i - 1, " ") + '/' + r(i++ * 2 + 1, " ") + "\\\n";
        /// Ceiling
        f = r(w * 8 + 1, "-");
        m += f;
        /// Room
        x = "\n" + r(w, "|" + r(7, " ")) + "|";
        y = "\n" + r(w, "|  ---  ") + "|";
        o = x + y + "\n" + r(w, "|  | |  ") + "|" + y + x;
        for (i = 1; i++ < h;) m += o + x.Replace(' ','-');
        /// Floor
        return m + o + "\n" + f;
    }

    string build(int width, int height)
    {
        // House, tempStr, floor, room, x/y = room_row1/2
        string house = "", s, ceil, room = "", x, y;
        int i, v = width*4;
        Func<int,string,string> rep = (j,c) => {
            s = "";
            for(; j>0; j--) s += c;
            return s;
        };
        /// Roof
        house += rep(v, " ") + "*\n";
        for (i = 0; i < v;) {
            // LEFT Indent + '/' + Distance + '\'
            house += rep(v - i - 1, " ") + '/' + rep(i++ * 2 + 1, " ") + "\\\n";
        }
        /// Ceiling
        ceil = rep(width * 8 + 1, "-");
        house += ceil;
        /// Room
        x = "\n" + rep(width, "|" + rep(7, " ")) + "|";
        y = "\n" + rep(width, "|  ---  ") + "|";
        room = x + y + "\n" + rep(width, "|  | |  ") + "|" + y + x;
        for (i = 1; i < height; i++) {
            house += room;// + x.Replace(' ','-');
            house += "\n" + rep(width, "|" + rep(7, "-")) + "|";
        }
        /// Floor
        house += room + "\n" + ceil;
        return house;
    }
}

```
> 1 votes

# Answer
# VBA, 284 bytes

```
Function H(W,S)
L=vbLf:H=Space(4*W)&"*"&L
For R=1 To 4*W:H=H &Space(4*W-R)&"/"&Space(2*R-1)&"\"&L:Next
J=".":P=String(W,J)&"|"&L
D=String(8*W+1,"-")&L
E=Replace(P,J,"|       ")
F=Replace(P,J,"|  ---  ")
H=H &Replace(String(S,J),J,D &E &F &Replace(P,J,"|  | |  ")&F &E)&D
End Function

```

The Replace function is a neat tool for making multiple copies in a way that the String function unfortunately doesn't want to.

Invoke for best effect in the Immediate window of the VBA editor: `?H(8,8)` for example.

```
?H(8,8)
                                *
                               / \
                              /   \
                             /     \
                            /       \
                           /         \
                          /           \
                         /             \
                        /               \
                       /                 \
                      /                   \
                     /                     \
                    /                       \
                   /                         \
                  /                           \
                 /                             \
                /                               \
               /                                 \
              /                                   \
             /                                     \
            /                                       \
           /                                         \
          /                                           \
         /                                             \
        /                                               \
       /                                                 \
      /                                                   \
     /                                                     \
    /                                                       \
   /                                                         \
  /                                                           \
 /                                                             \
/                                                               \
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------

```
> 1 votes

# Answer
# APL (Dyalog Extended), 91 bytes

```
'*'↑⍨-1+3×w←⎕
' /'[⊖a],' ',' \'[a←∘.=⍨⍳w×3]
' |-'[2⍪⍨2⍪¯1↓⊃⍪/⎕⌿⊂1,⍨⊃,/w/⊂⍉3⊤269+⎕AV⍳'4 4#']

```

Try it online!

Full program, takes columns, then rows, on separate lines.
> 0 votes

# Answer
# Vyxal, 76 bytes

```
4*:×꘍,(¹4*n-‹\/꘍nd›\\꘍+,)¹8*›¤-?(…\|7꘍¹*\|+…\|:2꘍2-ømṪ¹*$+…»ŀ»‛ |τ¹*\|+,,,),

```

Try it Online!

A. Mess.
> 0 votes

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


title: Put on your sunglasses

text:
# Question
Title: Put on your sunglasses
## Introduction

You are probably familiar with the "puts on sunglasses" emoticon-meme:

```
(•_•)
( •_•)>⌐■-■
(⌐■_■)

```

In this challenge, your task is to take the first line as input, and output the last one, effectively putting sunglasses on that little button-eyed person. To make the task a bit more difficult, the characters have been scaled up and converted to (ugly) ASCII art.

## Input

Your input is *exactly* this multi-line string, with an optional trailing newline:

```
   r                       t
  /                         \
 :                           :
 /    ,##.           ,##.    \
|     q##p           q##p     |
|      **             **      |
 \                           /
 :                           :
  \                         /
   L      ##########       j

```

## Output

Your output is *exactly* this multi-line string, again with an optional trailing newline:

```
   r                                         t
  /                                           \
 :               ______             ______     :
 /              |######|           |######|    \
|     _______   |######|           |######|     |
|     #""""""   |######|           |######|     |
 \    #         |######|           |######|    /
 :    "          """"""             """"""     :
  \                                           /
   L                    ##########           j

```

Note that there are no trailing spaces in the input and output.

## Rules and scoring

You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

# Answer
> 3 votes
# Bubblegum, 97 bytes

```
0000000: e001 e500 595d 0010 6818 841b 8ec4 c1cd  ....Y]..h.......
0000010: edc4 82fe b74a b6dd affc 98aa dccc 0d35  .....J.........5
0000020: 6869 7333 10ec f862 efbc 1475 9496 cacf  his3...b...u....
0000030: 5379 f091 507e 3df4 4a1d 51fc 98f7 4fb8  Sy..P~=.J.Q...O.
0000040: a8e0 2e3e 3b1b dc32 cbcf 5f0c d010 9d96  ...>;..2.._.....
0000050: 63e9 c49a fc44 60ef 7680 9b58 9027 c000  c....D`.v..X.'..
0000060: 00

```

Compressed using LZMA. Try it online.

# Answer
> 3 votes
# Retina, ~~210~~ ~~161~~ ~~156~~ 133 bytes (ISO 8859-1 encoding)

Completely remade, doesn't care about input anymore.

```
s`.+
3r41t¶2/43\¶1:15,13,5:¶1/10 e\¶|5_,e |¶|5#'e |¶1\4#5 e/¶1:4"10'13'5:¶2\43/¶3L19 10$*#11j
e
3~11~4
~
|6$*#|
,
6$*_
'
6$*"
\d+
$*

```

There is a trailing space at the end of last line. Also, a trailing newline is included in the output. If you want to suppress it, change the second last line to `\`\d+`

Old version, which uses parts of input in output:

```
( {3})(.+¶){3}.{10}( +)\S+( +).¶.( +)(.+¶){5}.+?(#+).+
$1rq te /q$1\e:pf,p$1,f:e/p$4~$3~$4\¶|f,_$1~$3~f|¶|f#'$1~$3~f|e\$4#$4f~$3~$4/e:$4"p'p$1'f:e \q$1/¶$1Lpp$7$3j
~
|6$*#|
,
6$*_
'
6$*"
q
pppp
p
ff
e
¶
f
5$*

```

Try it online! (210-byte version)
Try it online! (161-byte version)
Try it online! (156-byte version)
Try it online! (133-byte version)

# Answer
> 1 votes
# JavaScript (ES6), 200 bytes

```
a=>a.split`
`.map((l,i)=>l[s="slice"](0,6)+(["_7 3",'#"6 3',"# 9",'" 9'][i-4]||"  9")+(g=[" _5 ",x="|#5|",x,x,x,' "5 '][i-2]||" 7")+l[s](10,21)+g+l[s](25)).join`
`.replace(/.\d/g,m=>m[0].repeat(m[1]))

```

## Explanation

Replaces the eyes of the input with run-length encoded glasses, then decodes them.

```
var solution =

a=>
  a.split`
`.map((l,i)=>                                      // for each line of the input
    l[s="slice"](0,6)                              // left outline
    +(["_7 3",'#"6 3',"# 9",'" 9'][i-4]||"  9")    // glasses frame
    +(g=[" _5 ",x="|#5|",x,x,x,' "5 '][i-2]||" 7") // left glasses lens
    +l[s](10,21)                                   // mouth
    +g                                             // right glasses lens
    +l[s](25)                                      // right outline
  )
  .join`
`                                                  // combine altered lines
  .replace(/.\d/g,m=>m[0].repeat(m[1]))            // run-length decoding

result.textContent = solution(
`   r                       t
  /                         \\
 :                           :
 /    ,##.           ,##.    \\
|     q##p           q##p     |
|      **             **      |
 \\                           /
 :                           :
  \\                         /
   L      ##########       j`
);
```

```
<pre id="result"></pre>
```

# Answer
> 0 votes
## Python 3, 283 bytes

```
import zlib;print(zlib.decompress('x\x9cSPP(R \x16\x94p)(è\x13\xadZA!\x86KÁ\nM(\x1e\x0cp\tYq¡\x9b_£\x0c\x0658\x84b¸j\x90Ì\x88\'¬A¡\x06ªCY\t\x0c\x88Ò¡\x10\x03ÖA¬£ô¡ÞVBHÃ-Ã*\x04ô6Ä\n"\x01Ð\x02\x05\x05\x1fl2Êp\x80$\x98\x05\x00ð>KB\n'.encode('latin-1')).decode())

```

Try it online

Doing the encoding and decoding to deal with the fact that `zlib.decompress` expects a `bytes` object is about 30 bytes cheaper than just directly passing a bytes object:

```
import zlib;print(zlib.decompress(b'x\x9cSPP(R \x16\x94p)(\xe8\x13\xadZA!\x86K\xc1\nM(\x1e\x0cp\tYq\xa1\x9b_\xa3\x0c\x0658\x84b\xb8j\x90\xcc\x88\'\xacA\xa1\x06\xaaCY\t\x0c\x88\xd2\xa1\x10\x03\xd6A\xac\xa3\xf4\xa1\xdeVBH\xc3-\xc3*\x04\xf46\xc4\n"\x01\xd0\x02\x05\x05\x1fl2\xcap\x80$\x98\x05\x00\xf0>KB').decode())

```

# Answer
> 0 votes
# ~~05AB1E~~ Osable, 174 bytes

Well, this was a mistake... 05AB1E doesn't have any compression built-in except for a dictionary compression method. Code:

```
2FSð18×sJ,}17÷\?'_6×Dð13×sð5×VY':J,ð'/ð14×J?'|'#6×'|JDð11×sð4×JUX'\J,'|Y'_7×ð3×Xð'|J,'|Y'#'"6×ð3×Xð'|J,ð'\ð4×'#ð9×X'/J,ð':ð4×'"ðT×'"6×Dð13×sY':J,\\\\\Sð18×sJ,5÷ð4×srð14×srJ?,

```

Try it online!

Uses **CP-1252** encoding.

# Answer
> 0 votes
# Python 2, 120 bytes

This source contains non-printable characters, so it is presented as a hexdump that can be decoded with `xxd -r`.

```
00000000: efbb bf70 7269 6e74 2778 018d cea7 1503  ...print'x......
00000010: 310c 5c30 50ae 29fe 3b0f 60ee 19b2 411a  1.\0P.).;.`...A.
00000020: 0f4b 81de 3dbd b7d3 67ea c246 d62e a8f2  .K..=...g..F....
00000030: 66a1 79b5 3cfb 956a a17a d1cb 59ff 919a  f.y.<..j.z..Y...
00000040: 4507 cb8b f101 3d3a 28c3 596a c20c 4af6  E.....=:(.Yj..J.
00000050: a91a 1a0c eeee c7be a65a 3093 5703 135f  .........Z0.W.._
00000060: 943b 0fab 03f0 3e4b 4227 2e64 6563 6f64  .;....>KB'.decod
00000070: 6528 277a 6970 2729                      e('zip')

```

# Answer
> 0 votes
# Vyxal, 214 bytes

```
3\r꘍41\t꘍+,2\/꘍43\\꘍+,1\:꘍2꘍13\_6*꘍d5\:꘍Wṅ,1\/꘍3꘍11\|\#3*+m꘍d4\\꘍Wṅ,\|5꘍\_7*`   |###`m3꘍øm2\|꘍Wṅ,\|5꘍\#\"6*`   |###`m3꘍øm2\|꘍Wṅ,1\\꘍4\#꘍ð6*`   |###`m3꘍øm1\/꘍Wṅ,1\:꘍4\"꘍₀\"6*3꘍꘍d2\:꘍Wṅ,2\\꘍43\/꘍+,3\L꘍20\#₀*꘍11\j꘍++,

```

Try it Online!

A hardcoding mess.

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


title: Help me Open the Box

text:
# Question
Title: Help me Open the Box
I have an ASCII-art box and I need a program to open it.

## Examples

Input:

```
-------
|     |
|_____|

```

Output:

```
      /
     /
    /
   /
  /
 /
/
|     |
|_____|

```

# Specification

* The first line will only consist of `-`, at least 3 of them
* The middle rows will start with `|` have spaces, and end with `|`
    + All the middle rows will be the same
* The last row will start with `|` have `_` and end with a `|`
* All rows will be the same length

Opening the box:

* Each `-` should be replaced by a `/` in ascending lines and position.

# Answer
> 7 votes
# CJam, 14 bytes

```
l,{N'/@S*}%W%q

```

Try it online!

### How it works

```
l               Read the first line from STDIN.
 ,              Compute the line's length. Result: L
  {      }%     Map; for each I in [0 ... L-1]:
                  (implicit) Push I.
   N              Push a linefeed.
    '/            Push a slash.
      @           Rotate I on top of the stack.
       S*         Turn I into a string of I spaces.
           W%   Reverse the resulting array of strings and characters.
             q  Read the remaining input from STDIN.

```

# Answer
> 11 votes
## JavaScript ES6, 57 bytes

```
s=>s[r="replace"](/-+/,s=>s[r](/-/g,`
$'/`))[r](/-/g,' ')

```

Outputs a leading newline. Works by taking the row of `-`s and converting them into a triangle, then replacing the `-`s with spaces.

Edit: Saved 5 bytes thanks to @edc65.

# Answer
> 9 votes
# Pyth, ~~16~~ 14 bytes

```
j+_m+*;d\/Uz.z

```

Explanation

```
   m      Uz   - [V for d in range(len(input()))]
    +*;d\/     - " "*d + "/"
  _            - ^[::-1]
j+          .z - "\n".join(^+rest_of_input())

```

Thanks @FryAmTheEggman for new algorithm!

Try it here.

# Answer
> 9 votes
# pb (NONCOMPETING), 125 bytes

```
^w[B!0]{>}w[B!45]{<w[B=10]{t[T+1]b[0]}}v[X]vw[T!0]{vb[124]<[X]b[124]>w[B=0]{>}t[T-1]}w[X!1]{<b[95]}<w[B!0]{^}w[Y!-1]{b[47]>^}

```

The version of pbi that you need to run this answer is newer than the question. It would have worked in older versions except that I never got around to allowing newlines in input. Oh well.

First, this determines the height of the box by counting newlines in the input. Once it knows that, it goes to the Y location of the right side of the box, goes down to where it needs to be and draws the walls and floor, finishing with the lid.

Check out this fun animation!

The long pause is the brush going over the input.

**Ungolfed:**

```
^w[B!0]{>}                # Go to the end of the input
w[B!45]{<                 # Head left until hitting a hyphen
    w[B=10]{                # For each newline on the way:
            t[T+1]                # Count it
            b[0]                  # Delete it
    }
}

v[X]                      # Move down as far as it is right + the number of \n
v                         # ...plus one

w[T!0]{                   # While the counting variable is nonzero:
    vb[124]                 # Go down and draw a pipe
    <[X]b[124]              # Draw a pipe on the left as well
    >w[B=0]{>}              # Go back to the right side
    t[T-1]                  # Decrement variable
}

w[X!1]{<b[95]}            # Draw the bottom of the box
<w[B!0]{^}                # Go up the left wall
w[Y!-1]{b[47]>^}          # Go up and right, drawing the lid

```

# Answer
> 8 votes
# Retina, ~~34~~ 20 bytes

```
-(?=(-*))¶?
$1/¶
-

```

In the first step every `-` is substituted with the `-`'s following it, a `/` and a newline. The newline at the end of the original first line is deleted. In the second step we change the new `-`'s to spaces which results in the desired output.

Try it online here.

# Answer
> 7 votes
# MATL, 14 ~~15~~ bytes

```
' /'jnXyPQ)`jt

```

Input should have a trailing newline.

**Try it online!**

### Explanation

```
' /'       % push string (will be indexed into to generate the open lid)
jn         % read first line of input and push its length
Xy         % identity matrix with that size
P          % flip vertically
Q          % add 1. Now the matrix contains 1 and 2, to be used as indices
)          % index into string. Produces a 2D char array for the lid
`          % do-while loop
  j        %   push input line
  t        %   duplicate. Truthy if nonempty
           % implicitly end loop. The loop condition is the top of the stack,
           % that is, the input line that has just been read.
           % This is truthy if non-empty; and in that case another line will
           % be read in the next iteration.
           % implicitly display stack contents, bottom to top

```

# Answer
> 5 votes
# Japt, ~~28~~ ~~26~~ ~~25~~ ~~22~~ ~~18~~ 17 bytes

```
Ur-@"
{SpUa- -Y}/

```

Test it online!

Outputs a leading newline, which is acceptable according to the OP.

### How it works

```
Ur-@       // Replace each hyphen X in the input and its index Y with this function:
"          //  Start a string that contains a newline.
{        } //  Insert here:
   Ua- -Y  //   Take the index of the last hyphen in the input, subtract Y,
 Sp        //   and return that many spaces.
/          //  Finish off the string with a slash.

```

This would be 4 bytes shorter if the hinge is allowed to be on the right edge of the box:

```
Ur-@"
{SpY}\\

```

# Answer
> 4 votes
# JavaScript (ES6), 66

```
b=>([a,t]=b.split`-
`,[...a+0].map(_=>(t=l+`/
`+t,l+=' '),l=''),t)

```

**TEST**

```
f=b=>([a,t]=b.split`-\n`,[...a+0].map(_=>(t=l+`/\n`+t,l+=' '),l=''),t)

var box = `-------
|     |
|_____|`

console.log=x=>O.textContent=x

console.log(f(box))
```

```
<pre id=O></pre>
```

# Answer
> 3 votes
# Java 8, ~~158~~ 118 bytes

This is just a start, but hey, FGITWFTW.

```
n->{String o="";int z=n.lastIndexOf("-"),i=z;for(;i-->0;o+="/\n")for(int y=i;y-->0;o+=" ");return o+n.substring(z+2);}
```

Expects input as a string, returns the box.

# Answer
> 3 votes
# Bash, ~~85~~ ~~84~~ 79 characters

(Pure Bash version, no external commands used.)

```
r(){
a="${a/-
/
$s/
}"
s+=\
[[ $a = -* ]]&&r
}
mapfile a
r
IFS=
echo "${a[*]}"

```

Outputs a leading newline.

Sample run:

```
bash-4.3$ bash open-the-box.sh <<< $'-------\n|     |\n|_____|'

      /
     /
    /
   /
  /
 /
/
|     |
|_____|

```

# Answer
> 3 votes
## **Perl, 61 54 33 + 3 = 36 characters**

```
s^-^" "x(length$')."/\n"^ge&chomp

```

Run it as

```
perl -ple 's^-^" "x(length${chr 39})."/\n"^ge&chomp' closed_box_file

```

Each `-` in first line is replaced by a string that is a result of concatenation of some number of , `/` and `\n`. `${chr 39}` evaluates to perl's (in)famous `$'` aka `$POSTMATCH` special variable. Lastly, chomp gets rid of the trailing newline character that was added for the last `-` character.

Thanks to @manatwork for saving 7 + more characters.

**Bonus** \- `s^-^" "x$i++."\\\n"^ge&&chop` opens the box from the right edge in 29 + 3 characters :). Run it as:

```
gowtham@ubuntu:~$ cat a
----
|  |
|__|
gowtham@ubuntu:~$ perl -plE 's^-^" "x$i++."\\\n"^ge&&chop' closed_box_file
\
 \
  \
   \
|  |
|__|

```

# Answer
> 2 votes
## Pyth, ~~26~~ 23 bytes

```
jXK.z0jm+*\ t-lhKd\/lhK

```

Yuck. Can definitely be shorter; still working on it.

# Answer
> 2 votes
# Python 3, 1̶7̶0̶ 88 bytes

Here is my short(er) code: EDIT: Now 82 bytes Shorter With @Dennis 's Code Edit!

```
f=open('f.txt')
d=len(f.readline())-1
a=f.read()
while d:d-=1;print(' '*d+'/')
print(a)

```

# Python 3, 421 bytes

Alternatively, just for fun, you could use one that opens it slowly:

```
import time
import os
f = open('f.txt', 'r')
e = f.readline()
a = f.read()
d = len(e)
c = 0
t = e + a
g = ''
clear = lambda: os.system('cls')
while c <= d - 1:
    clear()
    print(("\n" * ((d - 1) - (c))) + t)
    c += 1
    e1 = e[0:(d - c)  -1]
    e2 = e[(d - c):len(e)]
    e1 += '/'
    e2 = ' ' * len(e2)
    y = (' ' * len(e1)) + '/' + '\n'
    g += y
    t = (g + e1 + e2 + '\n' + a)[d:len(g + e1 + e2 + '\n' + a)]
    time.sleep(0.2)
f.close()

```

To use either, you must create a text file in the same directory containing an ascii box of any width or depth called 'f.txt'. It will then open that box.

# Answer
> 2 votes
# Python3, 76 bytes

```
f=open(0)
w=len(f.readline())
while w:w-=1;print(' '*w+'/')
print(f.read())

```
1. Get the length of the first input line.
2. Print lines of `/` preceded by a decreasing number of spaces.
3. Push the rest of `stdin` straight to `stdout`.

EDIT: I've just noticed that my code is almost identical to @Dennis' comment edit of @Monster's shorter Python3 code, the only difference being print the remainder of `stdin` directly instead of store it in a variable. Great minds!

# Answer
> 2 votes
# Canvas, ~~6~~ 4 bytes

```
ｊＬ／ｏ

```

Try it here!

Explanation:

```
j      remove 1st line of the input
 L     get the width of the remaining input
  /    push a diagonal of that size
   o   and output that diagonal
       and implicitly output the remaining input

```

# Answer
> 1 votes
# Python 2, 100 bytes

```
def o(b):
 m=b.split('\n')[1:]
 print"\n".join(["/".rjust(i)for i in range(len(m[0]),0,-1)]+m)

```

Defines a function `o` that takes a string as its input. (Full program wasn't specified in the question).

# Answer
> 1 votes
## PowerShell, 55 bytes

```
$d,$b=$args-split"`n";($d.length-1)..0|%{" "*$_+"/"};$b

```

Takes input `$args` as a string, `-split`s on newlines  ``n` <sub>(reference link)</sub>, stores the first line into `$d` (as a string) and the remaining into `$b` (as an array of strings). We then loop from the `length` of the first line (minus 1) to `0` and each iteration output that number of spaces plus a `/`. Finally, output `$b` (the rest of the input string) which by default will output one per line.

### Example Run

```
PS C:\Tools\Scripts\golfing> .\help-me-open-the-box.ps1 "----`n|  |`n|__|"
   /
  /
 /
/
|  |
|__|

```

# Answer
> 1 votes
# JavaScript (Node.js), 56 bytes

```
a=>a[b="replace"](/-+/,c=>c[b](d=/-/g,`
$'/`))[b](d,' ')

```

Try it online!

Should be written as a comment of **@Neil**'s answer but I can't create comments yet

# Answer
> 1 votes
# 05AB1E (legacy), 9 bytes

```
g'/1.Λ|»»

```

Try it online! (legacy-only)

### How it works

```
g'/1.Λ|»» – Full program. Takes input from STDIN.
g         - Length. Only takes the first line into account.
 '/       – Push a slash character, "/".
   1.Λ    – And diagonally up-right, draw a line of slashes of the given length.
      |»  – Push the remaining inputs (all other lines) joined on newlines.
        » – Then join the stack on newlines.

```

# Answer
> 1 votes
# Charcoal, 14 bytes

```
↙Ｌ§⪪θ¶⁰Ｍ→✂⪪θ¶¹

```

Try it online (verbose) or try it online (pure).

**Explanation:**

Split the input by newlines, take the length of the first line, and print a line of that length from the Top-Right to Down-Left:

```
Print(:DownLeft,Length(AtIndex(Split(q,"\n"),0)))
↙Ｌ§⪪θ¶⁰

```

Move once to the right:

```
Move(:Right)
Ｍ→

```

Split the input by newlines again, and remove the first item, and print what's left implicitly:

```
Slice(Split(q,"\n"),1)
✂⪪θ¶¹

```

(NOTE: Putting the input split by newlines in a variable (since I do it twice above) is ~~1 byte longer~~ also 14 bytes by using a slightly different method (thanks to *@Neil*):
`≔⮌⪪θ¶θ↙Ｌ⊟θＭ→⮌θ` Try it online (verbose) or try it online (pure)).

# Answer
> 1 votes
# Vyxal, 16 bytes

```
L:£(&‹¥\/꘍,)□Ḣ⁋,

```

Try it Online!

# Answer
> 0 votes
# JavaScript ES6, 106 bytes

```
q=>(q=q.split`
`,n=q[0].length,eval('for(i=0,r="";i<n;i++)r+=" ".repeat(n-i-1)+"/\\n"'),r+q.slice(1).join`
`)

```

Simple enough: getting the length of the first line, creating a spaced-triangle with trailing `/`, and adding that to the original, sliced and joined.

## Test it out! (ES6 only `:(`)

```
F=q=>(q=q.split`
`,n=q[0].length,eval('for(i=0,r="";i<n;i++)r+=" ".repeat(n-i-1)+"/\\n"'),r+q.slice(1).join`
`)
function n(){q.innerHTML=F(o.value)}
o.onkeydown=o.onkeyup=o.onchange=o.onkeypress=n;
n();
```

```
*{font-family:Consolas,monospace;}textarea{width:100%;height:50%;}#q{white-space:pre;}
```

```
<textarea id=o>----
|  |
|__|</textarea><div id=q>
```

# Answer
> 0 votes
# PHP, 127 characters

```
$s=$argv[1];$l=strlen(strtok($s,"\n"));for($i=0;$i<$l;$i++)$s=preg_replace("/-/","\n".str_repeat(" ",$l-$i-1)."/",$s,1);echo$s;

```

Ungolfed version :

```
$s=$argv[1];
$l=strlen(strtok($s,"\n"));

for($i=0;$i<$l;$i++){
    $v="\n".str_repeat(" ",$l-$i-1)."/";
    $s=preg_replace("/-/",$v,$s,1);
}
echo $s;

```

# Answer
> 0 votes
## Python 2.7, ~~120~~ 122 chars

Needs a file `f` with the original/closed box, output is the opened one. Cheers to @Monster for the idea... will try to figure out multi-line input later and see if it's shorter.

```
for l in open('f').readlines():
 if l[1]==('-'):
  for x in range(1,len(l)):print(' '*(len(l)-x+1)+'/')
 else:print l[:-1]

```

**Edit**

* just noticed that the leftmost `/` has a space in front; +2 bytes

# Answer
> 0 votes
# Ruby, 59 characters

(57 characters code + 2 characters command line options.)

```
s=""
$_=$_.chars.map{(s<<" ")[1..-1]+?/}.reverse*$/if$.<2

```

Sample run:

```
bash-4.3$ ruby -ple 's="";$_=$_.chars.map{(s<<" ")[1..-1]+?/}.reverse*$/if$.<2' <<< $'-------\n|     |\n|_____|'
      /
     /
    /
   /
  /
 /
/
|     |
|_____|

```

# Answer
> 0 votes
# Gema, ~~51~~ ~~49~~ 31 characters

```
-\P/-+/=@subst{-=\\ ;$1}/\n
-=/

```

Sample run:

```
bash-4.3$ gema -e '-\P/-+/=@subst{-=\\ ;$1}/\n;-=/' <<< $'-------\n|     |\n|_____|'
      /
     /
    /
   /
  /
 /
/
|     |
|_____|

```

# Answer
> 0 votes
## Bash, 129 characters

Requires a file called `a` with the closed box, outputs to stdout.

```
for i in $(seq `cat a|awk 'NR==1{print length($1)-1}'` -1 1);{ for j in `seq 1 $i`;{ printf " ";};echo "/";};echo "/";tail -n2 a

```

It might be possible to make it shorter by using `sed` and using stdin and piping.

# Answer
> 0 votes
# Awk, ~~47~~ 46 characters

(44 characters code + 2 characters command line option.)

```
/-/{OFS=RS;for(i=NF;i;i--){$i=s"/";s=s" "}}1

```

Sample run:

```
bash-4.3$ awk -F '' '/-/{OFS=RS;for(i=NF;i;i--){$i=s"/";s=s" "}}1' <<< $'-------\n|     |\n|_____|'
      /
     /
    /
   /
  /
 /
/
|     |
|_____|

```

# Answer
> 0 votes
# Python, 125 bytes (110 without box)

```
i="\n---\n| |\n|_|"
l,b,r=i.count("-"),i.split('\n'),range
for x in r(1,l):print" "*(l-x)+"/"
for x in r(2,len(b)):print b[x]

```

If anyone has any idea how to shorten it, please let me know!

# Answer
> 0 votes
# K (ngn/k), 18 bytes

```
{(" /"@|=#*x),1_x}

```

Try it online!

# Answer
> 0 votes
# 05AB1E (legacy), 12 bytes

```
€ðƶ€¦'/«R|«»

```

Try it online!

# Answer
> 0 votes
# brainfuck, 118 bytes

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

```

Try it online!

(You will have to check the "!" box to allow for everything after the ! to be considered input)

It is the same length as the Java answer, so I'm happy. Any help golfing it to be shorter than the Java answer would be greatly appreciated.

**Explanation**

```
-->+[<+>,----------]                                 Counts the number of characters until a linefeed
>>>++++[<++++++++>-]>-[<+>-----]++++++++++<----<<<<  Initialises the next 3 cells to 32 (space), 47 (/) and 10 (linefeed)
[                                                    Starts a loop on the length of the first line
[>+>+<<-]>[<+>-]>[>.<-]>>.>.[<]<<-                   Prints a space for every character and then prints a slash, a linefeed and then takes one from the number of characters, and repeats until that value is equal to zero
]                                                    Ends the loop
>>>>.>.[,.]                                          Prints the last slash, a newline and then the rest of the input

```

# Answer
> 0 votes
# Brain-Flak, 144 bytes

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

```

Try it online!

The longest answer yet.

## Explanation

```
({()<{}({}[((()()){}()){}])>}{}) #count the dashes "n"
{ #while N != 0
  (({}[()])<>) #copy --N to second stack for the next line
  {({}[()]<(((((()()){}){}){}){})>)}{} #indent
  (((((()()()){}){}){}){}[()]) # '/'
  (((()()){}()){}) # newline
  <>
}{}
<>{({}<>)<>}<> #copy output to main stack

```

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