title: Pristine and Unique Code Bowling

text:
# Question
Title: Pristine and Unique Code Bowling
Your challenge is simple: write as long of a pristine program as possible in the language of your choice using only unique bytes. (The full definition of a pristine program, copied from that link, is at the bottom of this question.)

That's right, no strings attached. Your code doesn't have to do anything at all, just run without erroring, meet the requirements for a pristine program (linked above), and include no duplicate bytes in the encoding you use.

For the purposes of the above explanation and linked definition of "pristine program", an error is defined as anything that causes the program to either entirely fail to run or to terminate with a nonzero exit code after a finite amount of time.

As this is , ***longest***, not shortest, code wins (measured by byte count). The maximum theoretically possible score is 256, as there are 256 distinct bytes possible. In case of a tie, the first answer at the highest score wins.

---

Here's the full definition of a pristine program, copied from the above link:

> Let's define a *pristine program* as a program that does not have any errors itself but will error if you modify it by removing any contiguous substring of N characters, where `1 <= N < program length`.
>
> For example, the three character Python 2 program
>
> ```
> `8`
>
> ```
>
> is a pristine program because all the programs resulting from removing substrings of length 1 cause errors (syntax errors in fact, but any type of error will do):
>
> ```
> 8`
> ``
> `8
>
> ```
>
> and also all the programs resulting from removing substrings of length 2 cause errors:
>
> ```
> `
> `
>
> ```
>
> If, for example,  ``8` had been a non-erroring program then ``8`` would not be pristine because **all** the results of substring removal must error.

# Answer
> 31 votes
# Jelly, ~~253 254~~ 256 bytes

```
M“¢£¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#%&'()*+,-./0145689:;<=>?@ABCDEFGHIJKNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|~¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻḅḍẹḥịḳḷṃṇọṛṣṭụṿẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż”L»«’Ɗạ‘}237$¤¡

```

Try it online! or Verify it!

Turns out golfing languages can bowl...

* +1 byte by working in . ~~Now only `«»` are not used~~
* +2 bytes with with `«»`. Now have the optimal score!

## How?

The crucial feature of Jelly that makes this possible is that the opening and closing characters for string literals are not the same like in nearly all other languages.

The program structure is as follows:

`M <239 character long string> L»«’Ɗạ‘}237$¤¡`

`M` finds the indices of its argument that point to maximal elements. All that matters is that with no argument to this program Jelly assigns `0` to the chain and Jelly errors when `M` is applied to `0`.

To prevent `M` from acting on `0` in the full program, we use the `¡` quick, which applies `M` a number of times determined by the result of the link immediately preceding it. In this case that link is `<239 character long string> L»«’Ɗạ‘}237$¤`.

`L` takes the length of this string (239), and `»«’Ɗ` decrements this to 238. The `»«` part doesn't do anything but `Ɗ` (last three links as a monad) makes it so that if they are deleted an error will occur. Then  takes the absolute difference between the result of `»«’Ɗ` and the monad `‘}237$` applied to the string.  increments and is a monad, but the `}` turns this into a dyad and applies it to it's right argument, `237`, yielding `238`. Thus  yields `0` in the full program.

`¤` links back to the string literal forming a nilad. The result of this is `0`, so `M` is not applied at all, preventing any error.

**Possible subprograms:**

* If any part of the string is removed, `<string>..¤` will be nonzero and `M` gets applied to `0`, causing an error.
* If any part of `L»«’Ɗạ‘}237$` is removed either `M` will get applied to `0` or there will be operations between the string and a number, resulting in a `TypeError`.
* If any of `¤¡` is removed, `M` gets applied to `0`.
* If the string closing character  and both of `’‘` get removed and  doesn't, everything after `M` turns into a string so `M` will act on `0`.
    + If the string closing character  and  get removed and  doesn't, everything between  and  turns into a list of integers.
* If `M` alone is removed there is a an `EOFError` because `¡` expects a link before the preceding nilad.
* If `M“` and any number of characters after it is removed, there will be an `EOFError` because the `¤` looks for a nilad preceding it but doesn't find one. `238` doesn't count because it is part of a monad.

This pretty much covers everything.

I previously hadn't used `«»‘` because the latter two cannot be included in the string because they match the  character to form things other than strings. `«` can't be in a `“”` string either but I don't know why.

# Answer
> 34 votes
# Haskell, ~~39~~ ~~45~~ ~~50~~ ~~52~~ 60 bytes

```
main=do{(\	陸 ⵙ商ߜ 新->pure fst)LT
EQ[]3
2$1}

```

Identifier `main` has to have type `IO a` for some type a. When the program is executed, the computation `main` is performed, and its result is discarded. In this case its type is `IO ((a,b)->a)`.

The result is an application of the function `(λ a b c d e f → return fst)`, a six-argument constant function returning the function fst (which gives the first element of a 2-tuple), injected into the IO monad. The six arguments are `LT` (enum for less than), `EQ` (enum for equality), empty list `[]`, `3`, `2` and `1`.

What would be spaces are replaced with unique characters that count as spaces: a tab, a non-breaking space, a formfeed, vertical tab, OGHAM SPACE MARK, regular space, newline and carriage return. If any of these are missing, there will be a mismatch in the number of arguments. The parameter names are chosen as three or four byte UTF-8 characters, `陸ⵙ商ߜ新`, carefully choosing characters that don't result in duplicate bytes.

Thanks to @BMO for his valuable contributions.

Hex dump:

```
00000000: 6d61 696e 3d64 6f7b 285c f0a4 b6b8 09ef  main=do{(\......
00000010: a793 c2a0 e2b5 990c e595 860b df9c e19a  ................
00000020: 80e6 96b0 2d3e 7075 7265 2066 7374 294c  ....->pure fst)L
00000030: 540a 4551 5b5d 330d 3224 317d            T.EQ[]3.2$1}

```

Try it online!

# Answer
> 26 votes
# Python 2,  ~~20 21 33 39 45~~  50 bytes

Now very much a collaborative effort!

+2 thanks to Aidan F. Pierce (replace `sorted({0})` with `map(long,{0})`)

+8 thanks to dylnan (use of `\` and newline to replace space; suggestions to move from `0` to a mathematical expression; replacing `-1` with `-True`; use of hexadecimal)

+11 thanks to Angs (`4*23+~91` -\> `~4836+9*1075/2` then later `~197836254+0xbCABdDF` -\> `~875+0xDEAdFBCbc%1439/2*6`)

---

```
if\
map(long,{~875+0xDEAdFBCbc%1439/2*6})[-True]:q

```

**Try it online!** Or see the confirmation suite

`0xDEAdFBCbc` is hexadecimal and evaluates to `59775106236`.
`~` is bit-wise complement so `~875` evaluates to `-876`.
`%` is the modulo operator so `0xDEAdFBCbc%1439` evaluates to `293`.
`/` is integer division so `0xDEAdFBCbc%1439/2` evaluates to `146`.
`*` is multiplication so `xDEAdFBCbc%1439/2*6` evaluates to `876`.
`+` is addition so `~875+xDEAdFBCbc%1439/2*6` evaluates to `0`.
...no stripped version also evaluates to `0`.

`{0}` is a `set` containing a single element, `0`.

Calling `sorted` with a `set` as the argument yields a list, which may be indexed into with `[...]`.

Without `sorted` the code `({0})` would just yield the `set` and this cannot be indexed into in the same fashion, `if({0})[-True]:q` would raise a `TypeError`.

Indexing in Python is 0-based and allows negative indexing from the back and `True` is equivalent to `1`, hence `sorted({0})[-True]` finds the element `0`, while `sorted({0})[True]` will raise an `IndexError`, as will `sorted({})[-True]` and `sorted({0})[]` is invalid syntax.

The `0` that is found is falsey so the body of the `if`, `q`, is never executed, however if it were it would raise a `NameError` since `q` has not been defined.

Since a non-empty list is truthy we cannot trim down to `if[-1]:q` either.

See the confirmation suite to see: confirmation the bytes being unique; all the errors; and the success of the code itself.

# Answer
> 18 votes
# C (tcc), x86\_64, ~~29~~ ~~31~~ ~~33~~ ~~39~~ 40 bytes

```
main[]={(23*8),-~0xABEDFCfebdc%95674+1};

```

Returns **0**. *Thanks to @feersum for suggesting uppercase hex digits.*

Try it online!

### How it works

The assignment writes two ints (**184** and **49664**) to the memory location of *main*. With 32-bit ints and little-endian byte order, the exact bytes are `b8 00 00 00 00 c2 00 00`.

Since tcc doesn't declare the defined array as *.data* (most compilers would), so jumping to main executes the machine code it points to.

* `b8 00 00 00 00` (`mov eax, imm32`) stores the int **0** in the eax register.
* `c2 00 00` (`ret imm16`) pops **0** extra bytes from the stack and returns. (The value in the eax register is the function return value).

# Answer
> 16 votes
# \>\<\>, 122 bytes

```
e"~l=?!z6-d0p}xwutsrqonmkjihgfcba`_]\[>ZYXWVUTSRQPONMLKJIHGFEDCB@<:98754321/,+*)('&%$# .	|{Ay

```

Try it online!

Does nothing. Based on the same format as my Programming a Pristine World answer.

First, we check that the length of the code is 122 and error if it isn't. `><>` programs can't end without the use of the `;` command, but if this command is in the program, we can just remove everything before it to make the program end immediately. To combat this, we use the `p` command to place a `;` in the code during runtime. To do this, we subtract 6 from `A` and place it after the `p`.

I'll probably add most of the other values above 127 once I figure out the right two byte values. The missing 5 values are `v^;` and the two newlines.

Of the 7502 sub-programs, 7417 of them errored from invalid instructions, 72 from memory underflow, and 13 from running out of memory.

# Answer
> 13 votes
# JavaScript, 42 bytes

```
if([0XacdCADE*Proxy.length]!=362517948)田

```
* Removing `i`, `f`, or `if` will cause `SyntaxError: missing ; before statement`;
* Removing  will cause `SyntaxError: expected expression, got end of script`;
* Removing 1 or 2 bytes from  will cause `Invalid or unexpected token`;
* Modify the boolean expression will cause either Syntax Error or Reference Error on

```
00000000: 6966 285b 3058 6163 6443 4144 452a 5072  if([0XacdCADE*Pr
00000010: 6f78 792e 6c65 6e67 7468 5d21 3d33 3632  oxy.length]!=362
00000020: 3531 3739 3438 29e7 94b0                 517948)...

```

```
(function () {
  let valid = code => { try { eval(code); return true; } catch (e) { return false; } };
  let test = P => {
    for (let i = 0; i < P.length; i++) for (j = i + 1; j <= P.length; j++) {
      let Q = P.slice(0,i) + P.slice(j);
      if (Q && valid(Q)) {
        console.log(Q);
        return false;
      }
    }
    return true;
  };
  let unique = P => !/(.).*\1/.test(P);
  let P = 'if([0XacdCADE*Proxy.length]!=362517948)田';
  console.log(unescape(encodeURIComponent(P)).length);
  console.log(valid(P));
  console.log(unique(P));
  console.log(test(P));
}());
```

# Answer
> 11 votes
# Brain-Flak, 2 bytes

```
<>

```

Try it online!

Alternatively, `[]`, `{}` or `()`. Removing either bracket causes the other bracket to become unmatched.

Proof that this is the optimal solution:

A Brain-Flak program is made out of nilads (a pair of brackets on their own) or monads (a pair of brackets containing 1 or more nilads). A monad cannot be in a pristine program, as you can simply remove one or more of the nilads. Similarly, you cannot have more than one nilad in the program, since you can remove one of them without breaking the program.

As such, this might be the least optimal language for pristine or unique programming.

# Answer
> 6 votes
# Ada, 110 bytes (latin1)

Probably the best answer you'll get out of any language in use in industry?

Hexdump:

```
0000000: 7061 636b 4167 4520 6266 686a 6c6d 6f71  packAgE bfhjlmoq
0000010: 7274 7576 7778 797a e0e1 e2e3 e4e5 e6e7  rtuvwxyz........
0000020: e8e9 eaeb eced eeef f0f1 f2f3 f4f5 f6f8  ................
0000030: f9fa fbfc fdfe 0d69 730b 656e 6409 4246  .......is.end.BF
0000040: 484a 4c4d 4f51 5254 5556 5758 595a c0c1  HJLMOQRTUVWXYZ..
0000050: c2c3 c4c5 c6c7 c8c9 cacb cccd cecf d0d1  ................
0000060: d2d3 d4d5 d6d8 d9da dbdc ddde 3b0a       ............;.

```

Compile by saving to any file ending in `.ads` and running `gcc -c <filename>`. Produces an executable that does nothing. (Can't provide TIO link since TIO puts code in a `.adb` file and `gcc` by default tries to find a matching spec for them)

Basically declares a package with a name abusing capital/lowercase latin1 letters. Needs a different whitespace character for each of the spaces, so it uses space, CR, LF, and TAB.

How it looks in vim version:

```
packAgE bfhjlmoqrtuvwxyzàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ^Mis^Kend^IBFHJLMOQRTUVWXYZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ;

```

### How it works

In Ada even spec's can be compiled. Spec's are like c's header files, but are more full-featured and can compile some basic code. In order to be valid any specification must have the format: `package <NAME> is ... end <NAME>;` with `<NAME>` matching. The nice thing about Ada is that it is completely case insensitive. Thus as long as your name has uppercase and lowercase variants, you'll be good to go!

The hard part was getting a compilable unit. Normally Ada programs have a 'main' procedure or function lying outside of any package that will become the final executable. Unfortunately procedures require the `begin` keyword, which leads to too many `e`s (only 2 cases known) while functions require the `return` keyword, which leads to too many `n`s. Thus I had to just compile a package.

# Answer
> 5 votes
# C, 8 bytes

```
main(){}

```

Does nothing.

Try it online!

# Answer
> 5 votes
# Python 3 \+ Flask-Env, ~~7~~ ~~13~~ ~~14~~ 17 bytes

```
import\
flask_env

```

No TIO because it doesn't have `flask-env`.

Found the longest module name that has no intersection with `import` and doesn't have any numbers at the end of the name. `_sha256` is longer but `256` on it's own doesn't error. I did find one library, `b3j0f.sync` that is one byte longer but I could not get it to import properly.

* +1 byte by replacing a space after `import` with `\<newline>`. Taking out either or both causes an error.

There still may be longer options than `flask_env`, I didn't really do an exhaustive search but I did look through ~70,000 modules. Open to suggestions.

# Answer
> 5 votes
# JavaScript, 22 bytes

```
with(0xF?JSON:[])parse

```

Try it online!

### Possible errors

When altered, it will throw one of the following errors1:

```
[some_identifier] is not defined
expected expression, got ')'
expected expression, got ':'
expected expression, got '?'
expected expression, got ']'
expected expression, got end of script
identifier starts immediately after numeric literal
missing ( before with-statement object
missing ) after with-statement object
missing : in conditional expression
missing ] after element list
missing exponent
missing hexadecimal digits after '0x'
missing octal digits after '0o'
unexpected token: ')'
unexpected token: ']'
unexpected token: identifier

```

1. The exact number of distinct errors depends on the engine. This list was generated with SpiderMonkey (Firefox).

# Answer
> 3 votes
# , 14 bytes

```
(Sys.readlink)

```

Try it online!

This might be the longest possible in R. Calling any function is doomed to failure, because you would be able to remove everything but the function name, which would just result in printing the function's source code. This is the longest named object in the default R setup with no duplicate characters and no object name left over when removing contiguous characters.

*This first try didn't work, but I learned a lot by trying!*

~~`dontCheck({family;NROW})`~~

# Answer
> 2 votes
# Perl 5, 3 bytes

```
y=>

```

`=>` is the "fat comma," which quotes the bareword on the left. So this is equivalent to

```
"y",

```

which does nothing.

Without the fat comma, `y` is the transliteration operator, which is invalid without three of the same character repeated later.

The fat comma alone is also invalid, as is `=` and `>` alone.

# Answer
> 2 votes
# brainfuck, 2 bytes

```
[]

```

Try it online!

Inspired by Jo King's Brain-Flak answer. This is optimal because the only error in brainfuck is unmatched brackets. (Again thanks to Jo King for this info.)

# Answer
> 2 votes
# Ruby, 28 bytes

```
(?2*0xA)[%r<\d{1}>].unpack$/

```

Try it online!

Verify it!

# Answer
> 1 votes
# Tcl, 6 bytes

```
puts a

```

Try it online!

---

~~Tcl, 3 bytes
```
pwd

```
Try it online!
~~

---

~~Tcl, 2 bytes
```
cd

```
Try it online!
~~

# Answer
> 1 votes
# Standard ML, 22 bytes

```
val 1089=op-(765,~324)

```

Try it online! `op-(a,b)` is the de-sugared form of `a-b`. `~` denotes the unary minus, so we are actually computing `765+324`. This expression is pattern-matched on the constant `1089`. This match succeeds if the program has not been tampered with and does - well, nothing.

If the match does not succeed because some digits were removed one gets an `unhandled exception: Bind`. Removing `op-` results in a type error because a tuple is matched on an `int`. All other removals should result in an syntax error.

# Answer
> 0 votes
# Batch, 7 bytes

```
set/px=

```

A nice start

# Answer
> 0 votes
# Retina, 2 bytes

I wouldn't be surprised if this is optimal...

```
()

```

**Try it online!**

The regex contains an empty group. Removing either paren will cause a parse error due to unmatched parentheses.

Other solutions are: `\(`, `\)`, `\[`, `\]`, `\*`, `\+`, `\?`, `a]`

# Answer
> 0 votes
# Malbolge, 76 bytes

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

```

Try it online!

Malbolge is a great language for this challenge due to the way it translates normalized Malbolge into your familiar keyspam-esque Malbolge.

---
Tags: restricted-source, code-bowling, pristine-programming
---


title: Double bit rotation to the right

text:
# Question
Title: Double bit rotation to the right
Given a positive integer as input, output that integer, but with its bits rotated two times to the right. Also, think of the number as a donut of bits, eg. `21 -> (10101)`. If all of the bits suddenly decided to move to the right, they would wrap around. eg. `rRot(21) -> (11010) = 26`. Do what i explained 2 times (at the same time).

Test cases:

```
24 -> 6
21 -> 13
32 -> 8
0 -> 0
1 -> 1
3 -> 3

```

Remember that this is , so the shortest answer in bytes wins!

Also, here's a snippet for the leaderboard:

```
var QUESTION_ID=244139;
var OVERRIDE_USER=8478;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```

```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}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="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <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><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><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```

# Answer
# Vyxal, 4 bytes

```
bǔǔB

```

Try it Online!

All these languages without rotate right built-ins smh.

## Explained

```
bǔǔB
b    # convert input to binary
 ǔ   # rotate that right once
  ǔ  # and rotate that right all over again.
   B # convert back to base 10

```
> 6 votes

# Answer
# 05AB1E, ~~6~~ 4 bytes

*-2 bytes thanks to Kevin Cruijssen*

```
bÁÁC

```

Try it online!

Explanation:

```
         # implicit input
b        # convert to binary
 ÁÁ      # rotate right twice
    C    # convert from binary to decimal
         # implicitly output

```
> 4 votes

# Answer
# MathGolf, 2 bytes

```
╪╪

```

Try it online.

**Explanation:**

```
╪   # Rotate the bits of the (implicit) input-integer once towards the right
 ╪  # And do it again
    # (after which the entire stack is output implicitly as result)

```
> 4 votes

# Answer
# , ~~59~~ ~~58~~ 46 bytes

*Edit: -1 byte thanks to Giuseppe, and then a change-of-approach benefitting heavily from Giuseppe's golfing again*

```
function(x,z=x%/%4)z+2^(log2(z*2+!z)%/%1)*x%%4

```

Try it online!

Integer-divide x by 4, and then add `x` modulo 4 multiplied by `2^ceiling(log2(x/4))`.

---

Or, if the rotation is done in two separate steps, with removal of leading zeros after each step:

# , ~~61~~ 56 bytes

*Edit: -5 bytes thanks to Giuseppe*

```
function(x,z=x%/%4)z+2^(log2(z*2+!z)%/%1)*(x%%4-!x%%4-2)

```

Try it online!

Integer-divide x by 4, and then add the number of `1`-bits of `x` modulo 4 multiplied by `2^ceiling(log2(x/4))`. Works because each rotation only adds a 1 to the front if the least-significant-bit is non-zero.
> 4 votes

# Answer
# APL (dzaima/APL), 6 bytes

Anonymous tacit prefix function.

```
¯2∘⌽⍢⊤

```

Try it online! (TIO is outdated; the 0 case works in the latest version)

`¯2∘⌽` rotate two steps right

under

binarification

Compare to "surgery under anaesthesia" — the anaesthesia is undone once the surgery is over.
> 3 votes

# Answer
# APL (Dyalog Extended), 5 bytes

Anonymous tacit prefix function

```
⊥¯2⌽⊤

```

Try it online!

from-base-2 of

`¯2⌽` negative two left rotations of

to-base-2
> 3 votes

# Answer
# Brachylog, 6 bytes

```
ḃ↻₂⊇~ḃ

```

Try it online!

```
ḃ         Convert to binary,
 ↻₂       and rotate right 2.
   ⊇      Try subsequences largest first until
    ~ḃ    it can be converted from binary without leading zeroes.

```
> 3 votes

# Answer
# Desmos, 82 bytes

```
k=floor(log_2(n+0^n))
l=[0...k]
f(n)=total(mod(floor(n/2^l),2)[mod(l+2,k+1)+1]2^l)

```

Try It On Desmos!

Try It On Desmos! - Prettified

Thanks @Bubbler for supplying a helpful formula in the chat (I did `l+2` instead of `l-2`, though, because I realized it was golfier to do that).
> 3 votes

# Answer
# Jelly, 5 bytes

```
Bṙ-2Ḅ

```

Try It Online!

```
Bṙ-2Ḅ  Main Link
B      convert to base 2
 ṙ-2   rotate left -2 times
    Ḅ  convert from base 2

```
> 2 votes

# Answer
# JavaScript (ES6), 29 bytes

```
n=>n%4<<32-Math.clz32(n/=4)|n

```

Try it online!

### Commented

```
n =>          // n = input
  n % 4       // isolate the two least significant bits
  <<          // left-shift them by
  32 -        // the bit length of n once it has been divided by 4
  Math.clz32( // this is computed by using the number of leading
    n /= 4    // zeros in the 32-bit representation
  )           //
  | n         // bitwise OR with n (which is now input / 4)

```
> 2 votes

# Answer
# Charcoal, 15 bytes

```
≔↨Ｎ²θＩ↨²Ｅθ§θ⁻κ²

```

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

```
≔↨Ｎ²θ

```

Convert the input integer to binary.

```
Ｉ↨²Ｅθ§θ⁻κ²

```

Rotate the array by two bits and convert it back from binary.
> 2 votes

# Answer
# Retina 0.8.2, 50 bytes

```
.+
$*
+`(1+)\1
$1_
r`(.+)(_1?_1?)
$2_$1
+`1_
_11
1

```

Try it online! Link includes test cases. Explanation:

```
.+
$*

```

Convert to unary.

```
+`(1+)\1
$1_

```

Convert to a modified binary where `_` represents `0` and `_1` represents `1`. (Another way of thinking of it is that each `1`'s value depends only on the number of following `_`s.)

```
r`(.+)(_1?_1?)
$2_$1

```

Rotate the last two bits of the number to the start.

```
+`1_
_11

```

Convert back to unary.

```
1

```

Convert to decimal.
> 2 votes

# Answer
# Husk, 5 bytes

```
ḋṙ_2ḋ

```

Try it online!

```
    ḋ  # binary digits from number
 ṙ_2   # rotate left -2 positions
ḋ      # number from binary digits

```

---

Or **7 bytes** if the rotation is done in two separate steps, with removal of leading zeros after each step:

```
‼(ḋṙ_1ḋ

```

Try it online!
> 2 votes

# Answer
# Python 3, 34 bytes (@m90)

```
lambda n:n%4<<len(bin(n|2))-4|n>>2

```

Try it online!

### Old Python 3, 37 bytes

```
lambda n:(n%4<<len(bin(n>>1))-1)+n>>2

```

Try it online!

Mostly straight forward. The only bit that needs a bit of care is very small numbers because their bits may wrap around more than once. Here this is solved by making sure that the wrap around shift (the one that is applied to the two smallest bits) is always at least 2.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 33 bytes

```
2^BitLength[a=⌊#/4⌋](#-4a)+a&

```

Try it online!
> 2 votes

# Answer
# Ruby, ~~31~~ 29 bytes

```
->n{n%4<<(n/=4).bit_length|n}

```

Try it online!
> 2 votes

# Answer
# Factor, 23 bytes

```
[ >bin -2 rotate bin> ]

```

```
           ! 24
>bin       ! "11000"
-2 rotate  ! "00110"
bin>       ! 6

```
> 1 votes

# Answer
# Pyth, 9 bytes

```
i.>.BQ2 2

```

Try it online!
> 1 votes

# Answer
# C (gcc), 57 bytes

```
i;f(n){for(i=2;i--;n/=2)n+=n%2<<32-__builtin_clz(n);i=n;}

```

Try it online!
> 1 votes

---
Tags: code-golf, integer, bitwise
---


title: Remove oddly nested substrings

text:
# Question
Title: Remove oddly nested substrings
**Task:**

Input will consist of some text, with nested `[]` separating some of it into nested groups:

```
abc[d[fgijk]nopq]rst[u[v[[w]]]xy[[[z]]]]

```

Your task is to remove all brackets, and everything wrapped in an odd number of brackets. For example, `a[b]c` would remove the `[]`, and the `b` inside of it. `a[[b]]c`, however, would only remove the brackets (as `b` is wrapped in an even number of brackets). If the string were instead `a[b[c]d]f`, the result would be `acf`, as the `b` and `d` are wrapped in an odd number of brackets, but `c` is not.

The correct output for the input given at the top would be:

```
abcfgijkrstvwz

```

**I/O:**

You can take input as a string, or any reasonable representation of one (like an array of characters). You can output in a similar fashion, with trailing whitespacing being allowed. You can assume all non-bracket characters are lowercase letters, and you can choose whether the brackets are `()`, `[]`, or `{}`.

You can assume the brackets are properly nested (e.g., `[` or `][` won't be given as inputs), and that there is at least one letter in the input.

**Test cases:**

```
abc                                                 abc
a[b]c                                               ac
[ab]c                                               c
ab[c]                                               ab
[]abc                                               abc
a[]bc                                               abc
abc[]                                               abc
a[[b]]c                                             abc
a[[[b]]]c                                           ac
a[b][c]d                                            ad
a[b][]c                                             ac
[a[b]c]                                             b
a[b[c]d]f                                           acf
[ab]c[df]                                           c
a[a]a[[a]]                                          aaa
abc[d[fgijk]nopq]rst[u[v[[w]]]xy[[[z]]]]            abcfgijkrstvwz
zyx[w]v[ut[s]r[[qp][kj]i]gf][d][][][c][b[][a]]      zyxvsia

```

**Other:**

This is , so shortest answer (in bytes) per language wins!

# Answer
# Jelly, ~~10~~ 8 bytes

```
e€Ø[œpm2

```

Try it online! or see all test cases

Full program as we use Jelly' smash printing. Uses some tricks from Jonah's J answer, so be sure to upvote that as well!

-2 bytes thanks to Nick Kennedy.

## How it works

```
e€Ø[œpm2 - Main link. Takes a string S on the left e.g. S = "a[b[c]d]e"
  Ø[     - Builtin constant; Yield "[]"
 €       - Over each character in S:
e        -   Is it a bracket?                      e.g. [0,1,0,1,0,1,0,1,0]
    œp   - Partition S at the truthy indices       e.g. [['a'], ['b'], ['c'], ['d'], ['e']]
      m2 - Take every second sublist               e.g. [['a'], ['c'], ['e']]
           Smash-print and return                  e.g. 'abc'

```
> 10 votes

# Answer
# Vyxal `s`, 4 bytes

```
øW4Ḟ

```

Try it Online!

```
øW   # Split on words (Matches sequences of word chars + single non-word chars)
     # (Used for dictionary compression algorithm)
  4Ḟ # Get every fourth item.

```

Beating Jelly :) -2 thanks to Aaron Miller.
> 10 votes

# Answer
# Retina, 7 bytes

```
\W\w*.

```

Try it online!

* -7 bytes (50%) thanks to DLosc :)
> 10 votes

# Answer
# , 39 24 23 18 15 bytes

```
#~'_'(*=/\)@I.]

```

Try it online!

*-3 bytes and new approach thanks to FrownyFrog!*

## old answer, 39 24 23 18 bytes

```
(+:~:/\)@e.&'[]'#]

```

Try it online!

*Saved around 10 bytes after reading dingledooper's answer and realizing I didn't have distinguish between open and close brackets.*

*-6 thanks to some damn clever tricks by Bubbler!*

Consider `'a[b[c]d]f'`:

* `e.&'[]'` Is the input a bracket? Returns a boolean mask:

```
0 1 0 1 0 1 0 1 0

```
* `(+:~:/\)@` Transform that mask first by a scan using a not equal reduction. Only items with odd numbers of brackets to their left (including themselves) become 1. Then "not-or" `+:` that result with the original mask:

```
1 0 0 0 1 0 0 0 1

```
* `#]` Use that to filter the original input:

```
acf

```
> 9 votes

# Answer
# Japt v2.0a0 `-P`, ~~7~~ 5 bytes

Vyxal was being too cocky for my liking! :D

```
q\W ë

```

Try it or run all test cases

```
q\W ë     :Implicit input of string
q         :Split on
 \W       :  RegEx /[^a-z0-9]/i
    ë     :Get every second element, starting with the first
          :Implicitly join and output

```
> 9 votes

# Answer
# Python 3, 45 bytes

Input is taken from STDIN, and outputs a list of characters, each on its own line.

```
n=1
for c in input():n^=c<'a'or n>0==print(c)

```

Try it online!

The main observation is that whether or not a letter is wrapped in an odd number of brackets can be solely determined by taking the parity of the number of brackets preceding that letter.

### Python 3, 48 bytes

Same as above, but outputs the entire string on one line.

```
n=1
for c in input():n^=not'`'<c!=print(end=c*n)

```

Try it online!

### Python 3.8 (pre-release), 49 bytes

A `lambda`-based solution which is just slightly longer, in comparison:

```
lambda L,n=1:[c for c in L if(n:=n^(b:=c<'a'))>b]

```

Try it online!
> 6 votes

# Answer
# Wolfram Language (Mathematica), 40 bytes

```
StringSplit[#,"["|"]",All][[;;;;2]]<>""&

```

Try it online!
> 6 votes

# Answer
# , ~~33~~ 32 bytes

*-1 byte thanks to @Shaggy.*

```
function(s)gsub("\\W\\w*.","",s)

```

Try it online!

Simple regex-based solution.
> 6 votes

# Answer
# Zsh, 19 bytes

```
<<<${(e)1//[][]/\`}
```

Attempt This Online!

Replaces `[` and `]` with ```, and `(e)`xpands the backtick substitutions. For example, `A[[]BCD]` becomes

<pre><code>A```BCD`

The contents of backticks when in strings are evaluated as commands. Since there are no commands made only of uppercase letters, the bits in backticks do nothing and aren't included in the output.

If we can't assume input is uppercase, the same method can be adapted to force it to uppercase:

## Zsh, 26 bytes

```
<<<${(L)${(eU)1//[][]/\`}}
```

Attempt This Online!

---

## Zsh, 21 bytes

```
<<<${1//[][][a-z]#?/}
```

Attempt This Online!

A less interesting alternative that uses the equivalent of the `\W\w*.` regex method used by some other answers: `[][]` matches any square bracket, then `[a-z]` any letter (`#` means "0 or more times"), then `?` matches any single character.

Must be run with `--extendedglob` to enable the `#` pattern feature.
> 6 votes

# Answer
# brainfuck, ~~96~~ ~~89~~ 71 bytes

-25(!) bytes thanks to Daniel Cristofani

Uses `()` as brackets.

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

```

Try it online!

~~This is the most complex brainfuck I've ever written and I had quite a few troubles with getting the pointer back to a common position after branches, so I suspect there is some room for optimization.~~

With some comments:

```
                              tape layout: _; input1; input2; parity flag
,[                            while loop: runs as long as there is input
  [>+>+<<-]                   make two copies of the input to the right
  +++++[>--------<-]>         subtract 40 from the first copy
  [-[                         if the result is not 0 or 1:
    [-]                         set first copy to 0
    >>[<]<[.<<]                 print second copy is not set
                                pointer is now at _
  ]]
  >[                          if the pointer is at input1
    >-[++>]<[<]                 toggle the parity flag
  ]
  >[-]<<                      set second copy to 0
,]

```

Try it online!
> 6 votes

# Answer
# AutoHotKey, 44 bytes

```
#UseHook
[::
]::
A:=not A
BlockInput,%A%

```

You need execute it as Administrator permission. And you can always back to normal input status with `Ctrl-Alt-Delete` if you are in trouble.
> 4 votes

# Answer
# Pip, 10 bytes

```
@UW:a^`\W`

```

Try it online!

### Explanation

The key observation is that the two types of brackets don't need to be distinguished...

```
    a       First command-line argument
     ^`\W`  Split on this regex (any non-word character, i.e. a bracket)
 UW:        Unweave (the : is needed for precedence reasons, unfortunately)
@           Take the first of the unweave results

```

Unweave turns a list like `[1 2 3 4 5]` into `[[1 3 5] [2 4]]`, so `@UW` applied to the split results gives every other result, starting with the first.
> 4 votes

# Answer
# C (gcc), ~~55~~ 52 bytes

-3 thanks to dingledooper.

Scans through the string and increments a even-starting depth counter, printing any characters on an even depth: as the input is guaranteed to be balanced, the starting depth will always be an even number. Uses Jonah's trick of only scanning for brackets regardless of direction.

```
l;f(char*s){for(;*s;s++)*s>96?l%2||putchar(*s):l++;}

```

Try it online!
> 4 votes

# Answer
# JavaScript, ~~27~~ 26 bytes

Using pajonk's RegEx replacement approach; be sure to `+1` them if you're `+1`ing this.

```
s=>s.replace(/\W\w*./g,``)

```

Try it online!

## Original, 44 bytes

Adaptation of my Japt solution.

```
s=>s.split(/\W/).filter((_,y)=>++y%2).join``

```

Try it online!
> 4 votes

# Answer
# Haskell, 50 bytes

```
f(h:t)=[h|h>']',even$sum[1|b<-t,b<'a']]++f t
f x=x

```

Try it online!
> 3 votes

# Answer
# Vyxal `K`, 24 bytes

Thanks to exedraj, emanresu A and hyper-neutrino for guiding me through my Vyxal journey's beginning.

```
ƛ91≠*;ƛ93≠*;'[¥¬|¥¬£];C∑

```

Try it Online!
> 3 votes

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

```
x=>[...x].filter(x=>(z^=b=x>'z')>b,z=1).join``

```

Try it online!

Port of dingledooper's answer thanks to dingledooper.

# JavaScript (Node.js), 51 bytes

```
x=>x.replace(/[{}]([^{}]*)/g,(a,b)=>i++%2?b:'',i=0)

```

Try it online!

This makes use of the fact that after an even amount of open or close brackets, the bit of the string up until the next bracket should be kept. After an odd amount, it shouldn't. For example, on the demo input string, the following happens:

```
Full:    abc[d[fgijk]nopq]rst[u[v[[w]]]xy[[[z]]]]
Valid:   abc  [fgijk     ]rst  [v [w ]   [ [z ] ]
Invalid:    [d      ]nopq    [u  [  ] ]xy [  ] ]

```

We just smoosh the valid half together, remove all the brackets, and we have our answer!
> 2 votes

# Answer
# APL (Dyalog Classic), 22 bytes

```
{((~≠\⍵∊'[]')/⍵)~'[]'}

```

Try it online!

**Explained**

```
{                    }   ⍝ Monadic function, takes string on left
      ⍵∊'[]')            ⍝ Boolean mask for characters which are braces
 ((~≠\                   ⍝ Scan the mask by not-equal and negate (Mask for characters that is needed to kept with braces)
             /⍵)         ⍝ Filter the input using the scanned mask
                ~'[]'    ⍝ Remove the braces

```

Try it online!

# APL (Dyalog Classic), 24 bytes

```
{((~2|+\⍵∊'[]')/⍵)~'[]'}

```

Try it online!

Monadic function, takes the string on right

Approaches in array oriented languages are really neat
> 2 votes

# Answer
# jq, 19 bytes

```
gsub("\\W\\w*.";"")

```

Uses the regular expression from tsh's answer.

Try it online!
> 2 votes

# Answer
# Python 3, 40 bytes (using regex)

```
lambda s:re.sub("\W\w*.","",s)
import re

```

Try it online!

## Version without lambda, 44 bytes

```
import re
print(re.sub("\W\w*.","",input()))

```

Try it online!

Thanks to @emanresu A for the lambda version
> 2 votes

# Answer
# Haskell, ~~66~~ 61 bytes

```
f(x,y)c=(x-sum[x+x|c>'z'],y++[c|c<'{',x>0])
snd.foldl f(1,"")

```

Try it online!

Haskell doesn't really do regex.
> 2 votes

# Answer
# Charcoal, 16 bytes

```
ＦＳ¿№βιＦ¬﹪Ｌυ²ι⊞υι

```

Try it online! Link is to verbose version of code. Explanation: Prints lowercase letters unless an odd number of other characters have been recorded.

Alternative solution, also 16 bytes:

```
⪫Φ⪪⪫⪪Ｓ]¦[¦[¬﹪κ²ω

```

Try it online! Link is to verbose version of code. Explanation: Replaces `]`s with `[`s, then splits on `[`s and outputs alternate elements.
> 2 votes

# Answer
# K (ngn/k), 12 bytes

```
{x&=\x>:93}#

```

Try it online!

Takes advantage of the input restrictions, i.e. only having to deal with lower cased characters and `[]` as the brackets.

* `{...}#` set up a filter, removing items from the (implicit) input that do not match the criteria in `{...}`
    + `x>:93` determine which characters in the input are letters, updating `x` inplace (ASCII codes for `[]` are `91 93`, `a..z` are `97..122`)
    + `=\` do an equals-scan over this (characters at an even level of nesting become 1, otherwise are 0)
    + `x&` take the logical and, essentially asking "is this a letter AND is it at even level of nesting?"
> 2 votes

# Answer
# Ly, 37 bytes

```
1s>ir['aL:[pfpl!sp0]p![pl[p:o0]pp0]p]

```

Try it online!

This code takes advantage of the input constraints that the characters will only come from the set of characters `a-z` and `[` or `]`. Which means checking to see if the codepoint is less than the codepoint for `a` is sufficient to identify the brackets. It also relies on the constraint that only valid sequences of open and close brackets will given. That allows each bracket to be a "on/off" toggle for the print setting, since it doesn't matter whether it's an open or close, it will always change the even/odd state of the accumulated groupings.

```
1s                                    -- Set "true" as initial print boolean state
  >                                   -- Change to a clean stack
   ir                                 -- Read all input as codepoints, reverse stack
     [                              ] -- Loop to process each input codepoint
      'aL                             -- Compare top of stack to "a"
         :[p      0]p                 -- if/then, true is codepoint is "[" or "]"
            fp                        -- Pull codepoint forward and delete
              l!sp                    -- Flip "on/off" boolean print state
                     ![p         0]p  -- if/then, true if codepoint is "a-z"
                        l             -- Load print boolean state
                         [p  0]p      -- if/then, true if we should print the character
                           :o         -- Duplicate the codepoint and print one copy
                                p     -- Delete the current codepoint from the stack

```
> 2 votes

# Answer
# brainfuck, 439 bytes

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

```

Try it online!

---

Generated using a self-written yet poorly optimizing brainfuck compiler still under development. Its *brainfuck macro assembler* source code without the prelude can be seen below. I am certain a carefully layed out tape together with hand-written brainfuck would dramatically improve this byte count.

```
(macro ppcg233884 () (
    ; define parity cell
    (let:nve $parity 0 (
        ; read in character stream
        (let:nve $char 0 (
            (getc:w $char)
            (while:re $char (

                ; check if it is a bracket and update parity
                (let:nve $wasbracket 0 (
                    (let:nve $bracket 91 (
                        ; '['
                        (sub:ra $char $bracket)
                        (ifnot:re $bracket (
                            (not:a $parity)
                            (inc:a $wasbracket)))
                        ; ']'
                        (inc:a $bracket)
                        (inc:a $bracket)
                        (ifnot:ze $bracket (
                            (not:a $parity)
                            (inc:a $wasbracket)))))

                    ; only print on even parity when it was not a bracket
                    (ifnot:ze $wasbracket (
                        (ifnot:re $parity (
                            (putc:r $char)))))))

                (getc:w $char)))))))))

(macro main () (
    (ppcg233884)))

```
> 2 votes

# Answer
# V (vim), 19 bytes

Thanks to Aaron Miller for this two bytes shorter version.

```
äh:s/]/[/g
òf[df[òx

```

Try it online!

---

# V (vim), 21 bytes

```
xPP:s/]/[/g
òf[df[ò0x

```

Try it online!

## Explanation

```
xPP       " Duplicate initial character,
          "     since `f[` would else skip it.
          "     If the input is empty, error out.
:s/]/[/g  " Unify all brackets to `[`.
ò         " As long as necessary,
 f[       "     keep everything until even `[` and
 df[      "     discard everything until odd `[`.
ò         " End the loop.
0x        " Remove the duplicate character.

```
> 2 votes

# Answer
# 05AB1E, 6 bytes

```
Aм¡ιн˜

```

I/O as a list of characters. If a nested list output is allowed, the trailing `˜` could be removed.

Try it online or verify all test cases.

**Explanation:**

```
A       # Push the lowercase alphabet
 м      # Remove all these letters from the (implicit) input-list
  ¡     # Split the (implicit) input-list on the remaining characters ["[","]"]
   ι    # Uninterleave this list of lists into two parts
    н   # Only leave the first part of sublists
     ˜  # Flatten this nested list into a single list of characters
        # (after which it is output implicitly as result)

```

(Could also work for mixed cased letters by replacing `A` with `á`.)
> 2 votes

# Answer
# Curry (PAKCS), 55 bytes

```
f(h:t)=[h|h>']',0<foldl(*)1[-1|b<-t,b<'a']]++f t
f[]=[]

```

Try it online!

This is based on Lynn's Haskell answer. There are two difficulties adapting it to Curry however. The first is that curry doesn't have falling through so the case `f x=x` needs to be replaced\* with `f[]=[]` for an extra byte.

The next is that curry doesn't have `sum` so we need to replace it with some sort of fold. The most efficient way to do this is to actually make a `product` instead of a `sum` since it is way cheaper to check if something is positive than whether it is even.

\*: This doesn't actually behave like I would expect. I'm not a curry expert. However in both the expected behavior and the actual behavior it fails so...
> 2 votes

# Answer
# C (gcc), ~~66~~ 63 bytes

```
f(char*s){for(char*z=s,n=0;*z=*s++;*z-91&&*z-93?n%2||++z:++n);}

```

Try it online!
> 1 votes

# Answer
# Haskell, 53 bytes

```

s?(x:r)|x<'a'=(1-s)?r|s>0=s?r|s<1=x:s?r;_?q=q;f=(0?)

```

Try it online!
> 1 votes

# Answer
# Factor, 27 bytes

```
[ R/ \W\w*./ ""re-replace ]

```

Try it online!
> 1 votes

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


# Question
Title: How many blocks make a "truncated square-pyramid garden"?
A ***truncated square-pyramid*** of height \\$h\\$ has \\$h\\$ square layers where each layer has a side \\$1\\$ greater than the one above it, apart from the top layer which is a square of blocks with a given side length.

Here is a truncated square-pyramid of height \\$7\\$ and top side-length \\$4\\$ viewed from the side:

```
             side length   blocks
   ████          4          16
  ▐████▌         5          25
  ██████         6          36
 ▐██████▌        7          49
 ████████        8          64
▐████████▌       9          81
██████████      10         100
                   Total = 371

```

It requires \\$\sum\_{i=4}^{10}i^2=371\\$ blocks to construct.

---

A ***truncated square-pyramid garden*** of size \\$N\\$ consists of truncated, square-pyramids of heights \\$1\\$ to \\$N\\$ where the \\$n^{th}\\$ tallest pyramid has a top side-length of \\$x\\$ where \\$x\\$ is the remainder after dividing \\$N\\$ by \\$n\\$ unless there is no remainder in which case \\$x=n\\$.

Here is a side-on view of a pyramid garden with \\$N=6\\$ pyramids, arranged from tallest to shortest:

```
N=6                ▐▌
                   ██     ██
                  ▐██▌   ▐██▌   ▐██▌
                  ████   ████   ████   ██
                 ▐████▌ ▐████▌ ▐████▌ ▐██▌ ▐▌
                 ██████ ██████ ██████ ████ ██  ██████
          height   6      5      4     3   2     1
               n   1      2      3     4   5     6
remainder of N/n   0      0      0     2   1     0
 top side-length   1      2      3     2   1     6

```

This garden takes \\$337\\$ blocks to construct.

### Task

Given a positive integer, \\$N\\$, calculate the number of blocks required to build a *truncated square-pyramid garden* of size \\$N\\$.

You are not required to handle size zero (just in case that causes an edge case for anyone).

Since this is a sequence, you may instead opt to output the block counts for all gardens up to size \\$N\\$ (with or without a leading zero, for size zero), or generate the block counts indefinitely without input (again a leading zero is acceptable). It's not currently in the OEIS, and neither is its two-dimensional version.

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

### Test cases

The first \\$100\\$ terms of the sequence are (starting with \\$N=1\\$):

```
1, 9, 28, 80, 144, 337, 455, 920, 1251, 1941, 2581, 4268, 4494, 7065, 9049, 11440, 13299, 19005, 20655, 28544, 31140, 37673, 45305, 59360, 59126, 73289, 86256, 101124, 109647, 136805, 138364, 170780, 184520, 211485, 241157, 275528, 272869, 326729, 368320, 414692, 424823, 499261, 510708, 596140, 636361, 680537, 753508, 867036, 857345, 966889, 1027920, 1130172, 1197747, 1358369, 1393684, 1528840, 1571095, 1712605, 1860668, 2083248, 2023267, 2261821, 2445122, 2584136, 2685714, 2910217, 2980225, 3298056, 3459910, 3719313, 3824917, 4206640, 4128739, 4534965, 4846194, 5081240, 5308615, 5695545, 5827090, 6349936, 6395099, 6753185, 7173903, 7783720, 7688846, 8192521, 8679955, 9202980, 9429730, 10177969, 10090513, 10725680, 11134432, 11766133, 12407705, 13134004, 13024244, 13979357, 14523352, 15111244

```

---

Note: there is a surprisingly terse Jelly solution to find for this one, happy hunting!

Here's a hint that might help get you thinking about a different approach:

> In Jelly lists are 1-indexed and indexing is modular, so finding the top side-length could be calculated by using \\$N\\$ to index into a list of `[1,2,...,n]`.

*2022-03-15*: If you just want to see this solution I have now posted it below.

# Answer
# Python 3, 62 bytes

-2 bytes thanks to Neil!

```
lambda N:sum((N%~n-~h)**2for n in range(N)for h in range(n,N))

```

Try it online!
> 4 votes

# Answer
# JavaScript (Node.js), ~~63~~ 61 bytes

```
n=>eval("for(x=y=0;x++<n;)for(z=0;z++<=n-x;)y+=(~-n%x+z)**2")

```

Try it online!

Shortened by @ophact.
> 4 votes

# Answer
# , ~~58~~ 49 bytes

```
function(N){for(i in 1:N)F=F+(x=i:N+N%%-i)%*%x
F}

```

Try it online!

Relatively straightforward implementation of the spec.

# , ~~58~~ 54 bytes

```
function(N)sum(unlist(Map(seq,N%%-(1:N)+1:N,l=N:1))^2)

```

Try it online!

Slightly more interesting but longer; relies on the same logic as above to generate the size of the top of each tower.
> 4 votes

# Answer
# Jelly, 11 bytes

```
Rr_"N%RƊF²S

```

Try it online!

```
R              Range [1..n]
 r             Range each to n: [[1..n], [2..n], …, [n]]
    N%RƊ       [(-n)%1, …, (-n)%n]
  _"           Vectorize subtract
        F²S    Flatten, square, sum

```
> 3 votes

# Answer
# APL+WIN, ~~47~~ 38 bytes

Prompts for N

```
+/∊((((n=0)×i)+n←i|N)+¯1+⌽⍳¨i←⍳N←⎕)*¨2

```

Try it online! Thanks to Dyalog Classic
> 2 votes

# Answer
# 05AB1E, ~~14~~ 11 bytes

```
L(%ā.sR+˜nO

```

Try it online or verify the first 25 test cases.

**Explanation:**

```
    #  e.g. input=6
L   # Push a list in the range [1, (implicit) input]
    #  STACK: [1,2,3,4,5,6]
(   # Negate each value
    #  STACK: [-1,-2,-3,-4,-5,-6]
%   # Modulo the implicit input by these values
    #  STACK: [0,0,0,-2,-4,0]
ā   # Push a list in the range [1,length] (without popping)
    #  STACK: [0,0,0,-2,-4,0],
    #         [1,2,3,4,5,6]
.s  # Get its suffixes
    #  STACK: [0,-4,-2,0,0,0],
    #         [[6],[5,6],[4,5,6],[3,4,5,6],[2,3,4,5,6],[1,2,3,4,5,6]]
R   # Reverse the list of suffixes
    #  STACK: [0,-4,-2,0,0,0],
    #         [[1,2,3,4,5,6],[2,3,4,5,6],[3,4,5,6],[4,5,6],[5,6],[6]]
+   # Add the values in the two lists at the same positions together
    #  STACK: [[1,2,3,4,5,6],[2,3,4,5,6],[3,4,5,6],[2,3,4],[1,2],[6]]
˜   # Flatten to a single list
    #  STACK: [1,2,3,4,5,6,2,3,4,5,6,3,4,5,6,2,3,4,1,2,6]
n   # Square each integer
    #  STACK: [1,4,9,16,25,36,4,9,16,25,36,9,16,25,36,4,9,16,1,4,36]
O   # Sum them together
    #  STACK: 337
    # (after which the result is output implicitly)

```
> 2 votes

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

```
N=>eval('for(k=n=0;n++<N;)for(c=e=N%n||n;c<=e+N-n;)k+=c*c++')

```

Try it online!

-2 by Polichinelle.

Iteratively calculates sum, which is shorter than direct calculation.
> 2 votes

# Answer
# Pari/GP, 37 bytes

```
N->sum(n=1,N,sum(i=n,N,(i-(-N)%n)^2))

```

Try it online!
> 2 votes

# Answer
# C (gcc), 71 bytes

```
s;h;n;x;f(N){for(s=n=0;N/++n;)for(h=-~N-n,x=N%n?:n;h--;++x)s+=x*x;n=s;}

```

Try it online!

Inputs an integer \\$N\>0\\$.
Returns the number of blocks needed to make a truncated square pyramid garden of size \\$N\\$.
> 2 votes

# Answer
# JavaScript (ES6), 56 bytes

```
f=(N,n=N)=>n&&f(N,n-1)+(g=k=>n++<=N&&k*k+g(k+1))(N%n||n)

```

Try it online!

---

# Faster, 66 bytes

A longer version that works in \\$O(N)\\$:

```
f=(N,n=N,k=N%n||n)=>n&&f(N,n-1)-(g=x=>x*(x+++x)*x/6)(k-1)+g(k+N-n)

```

Try it online!
> 2 votes

# Answer
# Jelly, 8 bytes

```
ịṡ¥Ɱ¹²FS

```

Try it online!

Uses the very clever tip supplied, but I'm not sure this quite inspires the description "surprisingly terse" yet... that `¹` just smells wrong!

More equivalent 8-byters:

* `ṡR⁸ịⱮ²FS`
* `ịⱮṡR$²FS`
* `ịⱮṡⱮ`²FS`
* `RɓịⱮṡ²FS`

```
   Ɱ¹       For each n in [1 .. N],
 ṡ          get a list of all substrings of [1 .. N] of length n,
ị ¥         and take the one at modular 1-index N.
     ²      Square each,
      F     flatten,
       S    and sum.

```
> 2 votes

# Answer
# Charcoal, 19 bytes

```
ＮθＩΣＥθΣＸ⁺⊕…ιθ﹪θ±⊕ι²

```

Try it online! Link is to verbose version of code. Explanation: Inspired by @KevinCruijssen's and @ovs's answers. Explanation:

```
Ｎθ                  Input `N` as a number
     θ              Input `N`
    Ｅ               Map over implicit range
          …         Range from
           ι        Current value
            θ       To input `N`
         ⊕          Vectorised Increment
        ⁺           Vectorised Plus
              θ     Input `N`
             ﹪      Modulo
                 ι  Current value
                ⊕   Incremented
               ±    Negated
       Ｘ          ² Vectorised Squared
      Σ             Take the sum
   Σ                Take the sum
  Ｉ                 Cast to string
                    Implicitly print

```
> 1 votes

# Answer
# Ruby, ~~54~~ 46 bytes

```
->n{(1..n).sum{|x|(x..n).sum{|y|(n%-x+y)**2}}}

```

Try it online!
> 1 votes

# Answer
# Burlesque, 27 bytes

```
roJngsaj.%jiS~]q?+Z]FLqS[ms

```

Try it online!

Port of Kevin Cruijssen's answer

```
ro    # Range [1..N]
J     # Dup
ng    # Negate
sa    # Non-destructive length
j.%   # Modulo (implicit zip)
j     # Reorder stack
iS    # Generate tails
~]    # Drop final
q?+Z] # Zip and sum
FL    # Flatten
qS[   # Square
ms    # Map sum

```
> 1 votes

# Answer
# Jelly, 5 bytes

Much of this post is in spoiler blocks, just in case anyone wants to try to find it for themselves since I mentioned it in the question.

> ```
> ịⱮẆ²S
> ```

**Try it online!**

### How?

> Unrelated String got to the method in their answer, just not to the golfed code!
>
> ```
> ịⱮẆ²S - Link: integer, N
>   Ẇ   - all sublists of [1..N]
>           e.g. N=6 -> [[1],[2],[3],[4],[5],[6]
>                       ,[1,2],[2,3],[3,4],[4,5],[5,6]
>                       ,[1,2,3],[2,3,4],[3,4,5],[4,5,6]
>                       ,[1,2,3,4],[2,3,4,5],[3,4,5,6]
>                       ,[1,2,3,4,5],[2,3,4,5,6]
>                       ,[1,2,3,4,5,6]
>                       ]
>           i.e. for size in [1..N]:
>                  for start in [1..N+1-len]
>                    [start..start+size]
>  Ɱ    - for each sublist:
> ị     -   N index into sublist
>           - indexing in Jelly is 1-indexed and modular so...
>           e.g 6 ị [3,4,5,6] -> 4
>           i.e N ị [start..start+size]
>               -> (N mod size)+start-1 if (N mod size) != 0 else start+size
>         e.g. 6 ịⱮ (6Ẇ) ->  [1,2,3,4,5,6,2,3,4,5,6,3,4,5,6,2,3,4,1,2,6]
>               ...if these were grouped in lengths of [N..1] they
>                  are our tower level side lengths:
>                    [[1,2,3,4,5,6]  (height 6: [top..bottom])
>                    ,[2,3,4,5,6]    (height 5: [top..bottom])
>                    ,[3,4,5,6]      (height 4: [top..bottom])
>                    ,[2,3,4]        (height 3: [top..bottom])
>                    ,[1,2]          (height 2: [top..bottom])
>                    ,[6]            (height 1: [top..bottom])
>                    ]
>    ²  - square (vectorises)
>     S - sum
>
> ```
> 1 votes

---
Tags: code-golf, sequence, integer
---


# Question
Title: S̶t̶r̶i̶k̶e̶t̶h̶r̶o̶u̶g̶h̶ the Word Search List
## Introduction:

Every workday I read the newspaper in the morning while eating breakfast, and also do some of the puzzles at the back. When I do the word-search puzzles, I (almost) always go over the words in order, and strike them through one by one. The word-searches in the newspaper have two columns of words, and after I finished a column I will also put a vertical strike through it.

## Challenge:

Let's do the same as a challenge. Given a list of lists of words and an integer \\$n\\$ for the amount of words I've already struck through, output the ASCII art representing that.
The words of each inner list will be placed in the same column, where the columns will have two spaces as delimiter (based on the longest word). All the letters in the words that are struck through are replaced with `-`, and if an entire column is struck through it's replaced with a vertical `|`.

## Challenge rules:

* `|` rules:
    + For the position of the `|`, we take the middle of the longest word in the column
    + If the longest word has an even length, we take the left character of the two middle characters (e.g. `----``-|--`)
    + If a word in the column is shorter than the (left-focused) middle of the longest word, pad spaces between this shortest word and the vertical `|` line
* You can assume the list of words will only contain regular ASCII letters (in a casing of your choosing - e.g. all lowercase; all uppercase; or mixed casing)
* You can assume the list of words will all be of equal length, except for the last column which might potentially be shorter
* You can assume there is always at least one word in the list
* You can assume \\$0 \leq n \leq W\\$ (where \\$W\\$ is the total amount of words)
* Probably not really relevant, but you can assume the words are in alphabetical order
* Trailing spaces/newlines in the output are optional
* The input-list can be taken in any reasonable format. Could be a list/stream/array; could be taken from STDIN; could be a space-delimited string list; a matrix of characters; etc.
* You're allowed to take the words-input as a list of rows instead of columns. So input `[["A","ABC","DEFGHIJ","FG","KLMN"],["QRSTUVW","QRSTUVWXYZ","ST","Y","YZ"],["Z","ZZZZZ"]]` would be `[["A","QRSTUVW","Z"],["ABC","QRSTUVWXYZ","ZZZZZ"],["DEFGHIJ","ST"],["FG","Y"],["KLMN","YZ"]]` instead

## Examples:

Input 1:

```
Words: [["A","ABC","DEFGHIJ","FG","KLMN"],["QRSTUVW","QRSTUVWXYZ","ST","Y","YZ"],["Z","ZZZZZ"]]
n:     0

```

Output 1:

```
A        QRSTUVW     Z
ABC      QRSTUVWXYZ  ZZZZZ
DEFGHIJ  ST
FG       Y
KLMN     YZ

```

Input 2:

```
Words: Same as the previous example
n:     11

```

Output 2:

```
-  |     ----|--     -
---|     ----|-----  ZZZZZ
---|---  --  |
-- |     -   |
---|     --  |

```

## General rules:

* This is , so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (e.g. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

Input 1:

```
Words: [["A","ABC","DEFGHIJ","FG","KLMN"],["QRSTUVW","QRSTUVWXYZ","ST","Y","YZ"],["Z","ZZZZZ"]]
n:     0

```

Output 1:

```
A        QRSTUVW     Z
ABC      QRSTUVWXYZ  ZZZZZ
DEFGHIJ  ST
FG       Y
KLMN     YZ

```

Input 2:

```
Words: [["A","ABC","DEFGHIJ","FG","KLMN"],["QRSTUVW","QRSTUVWXYZ","ST","Y","YZ"],["Z","ZZZZZ"]]
n:     11

```

Output 2:

```
-  |     ----|--     -
---|     ----|-----  ZZZZZ
---|---  --  |
-- |     -   |
---|     --  |

```

Input 3:

```
Words: [["A","ABC","DEFGHIJ","FG","KLMN"],["QRSTUVW","QRSTUVWXYZ","ST","Y","YZ"],["Z","ZZZZZ"]]
n:     12

```

Output 3:

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

```

Input 4:

```
Words: [["BACKWARD","DIAGONAL","FIND","HORIZONTAL"],["RANDOM","SEEK","SLEUTH","VERTICAL"],["WIKIPEDIA","WORDSEARCH"]]
n:     0

```

Output 4:

```
BACKWARD    RANDOM    WIKIPEDIA
DIAGONAL    SEEK      WORDSEARCH
FIND        SLEUTH
HORIZONTAL  VERTICAL

```

Input 5:

```
Words: [["BACKWARD","DIAGONAL","FIND","HORIZONTAL"],["RANDOM","SEEK","SLEUTH","VERTICAL"],["WIKIPEDIA","WORDSEARCH"]]
n:     6

```

Output 5:

```
----|---    ------    WIKIPEDIA
----|---    ----      WORDSEARCH
----|       SLEUTH
----|-----  VERTICAL

```

Input 6:

```
Words: [["TEST"]]
n:     1

```

Output 6:

```
-|--

```

# Answer
# Jelly, 35 bytes

```
z⁶Z)µẎ«”-$⁹R¤¦Fṁ”|LHĊƊ¦€ḟƑ¡"⁸Zj€⁾

```

A dyadic Link that accepts the list of lists of words on the left and the number done on the right and yields a list of lines.

**Try it online!**

### How?

```
z⁶Z)µẎ«”-$⁹R¤¦Fṁ”|LHĊƊ¦€ḟƑ¡"⁸Zj€⁾   - Link: W, N
   )                                - for each list in W:
z⁶                                  -   transpose with space filler
  Z                                 -   transpose
    µ                               - start a new monadic Link, call that X
     Ẏ                              - tighten (to a list of padded words)
         $⁹R¤¦                      - apply to indices [1..N]:
       ”-                           -   a '-' character
      «                             -   minimum (vectorises) -> '-' if not ' '
              F                     - flatten
               ṁ                    - mould like X
                           "⁸       - zip with X applying:
                        ḟƑ¡         -   if invariant under filter-discard:
                     Ɗ¦€            -     for each apply to indices...
                  L                 -     ...length
                   H                -        halved
                    Ċ               -        ceiling
                ”|                  -     ...a '|' character
                             Z      - transpose
                              j€⁾.. - join each with "  "

```
> 5 votes

# Answer
# Python3, 321 bytes:

```
L=len
Y=lambda x:max(map(L,x))
g=lambda x:[[i+' '*((M:=Y(x))-L(i))for i in x],[i[:(T:=(J:=M//2)--~M%2)]+' '*(H:=max(T-L(i),0))+'|'+i[J+M%2:]+' '*(M-L(i)-H-(L(i)<=T))for i in x]][{i[0]for i in x}=={'-'}]
f=lambda w,n,c=0:'\n'.join(map('  '.join,zip(*[g([[j,'-'*L(j)][(c:=c+1)<=n]for j in i])+['']*(Y(w)-L(i))for i in w])))

```

Try it online!
> 4 votes

# Answer
# Ruby,~~152 155~~ 153 bytes

```
->l,n{l.map!{|c|c.map!{|w|w.tr((0>n-=1)?'':'^ ',?-).ljust X=c.map(&:size).max}
n<0?c:c.each{|w|w[~-X/2]=?|}}
(0...l[0].size).map{|y|l.map{|c|c[y]}*"  "}}

```

Try it online!

* Added 3 Bytes to fix vertical lines position as spotted by @Kevin Cruijssen, whom then saved 2 suggesting the use of (bitwise x negated) trick, e.g. *(x-1)/n =\> ~-x/n*

Lambda taking *l* list and *n* that outputs an Array of lines.

The first adversity was to draw the vertical line, which can be done after padding, because it's not possible to access a string out of its bounds.

*l.map!{|c|c.map!{|w|..*
First we deep map(columns x words) each word by:

* *tr((0\>n-=1)?'':'^ ',?-*
Substitute not-spaces *'^ '* with ?`-` if *n* decreased is still \>=0
* *ljust X=c.map(&:size).max*
Pad to max length of column, which is saved in constant *X* for later.

Before we continue to the next column:
*n\<0?c:c.each{|w|w\[~-X/2\]=?|}*
we overwrite each word at X/2 with ?`|` if *n* is still \>=0

The second adversity was obtaining rows, *transpose* wouldn't work because the last column is shorter.

*(0...l\[0\].size).map{|y|*
We build the rows by mapping the range \[0..column size) and
*l.map{|c|c\[y\]}\*" "}*
taking ith rows at each column.
> 3 votes

# Answer
# Python 3.8 (pre-release), ~~276~~ 258 bytes

```
L=len
def f(T,s,j=0):
	h=L(T[0])
	r=[""]*h
	for C,u in zip(T,[s-i*h<L(T[i])for i in range(L(T))]):
		a=L(max(C,key=L))
		for i,w in enumerate(C):r[i]+=((j<s and(c:=L(w)*"-"+a*" ")[:(b:=a//2+a%2-1)]+["|",""][u]+u*c[b]+c[b+1:a]or w)+a*" ")[:a+1];j+=1
	return r

```

Yields a list of lines

Try it online!
> 3 votes

# Answer
# Charcoal, 47 bytes

```
Ｆθ«Ｅι⎇‹ληＬκκ≔⌈ＥιＬκζＭ⊘⊖ζ±ＬιＦ¬‹ηＬιＰ↓ＬιＭ⊘ζ→→→≧⁻Ｌιη

```

Try it online! Link is to verbose version of code. Very forgiving as to the input words. Explanation:

```
Ｆθ«

```

Loop over the list of columns of words.

```
Ｅι⎇‹ληＬκκ

```

Replace each word that has already been struck through with its length and print the result. This outputs a line of `-`s of that length for those words and the words unchanged for the remaining words.

```
≔⌈ＥιＬκζ

```

Get the length of the longest word.

```
Ｍ⊘⊖ζ±Ｌι

```

Move horizontally to the middle of the longest word (but vertically to the first word).

```
Ｆ¬‹ηＬιＰ↓Ｌι

```

If all of the words in this column have been struck through then vertically output a `|` for each word without moving the cursor.

```
Ｍ⊘ζ→

```

Move to the end of the longest word.

```
→→

```

Move to where the next block of words belongs.

```
≧⁻Ｌιη

```

Adjust the number of remaining words that have been struck through.
> 3 votes

# Answer
# Julia 1.0, <sup>~~165~~</sup> 166 bytes

```
! =length
f(N;n)=""
f(N,l,L...;n=!l,m=~-max(.!l...))=(1:n.|>i->i>!l ? "" : rpad(i>N ? l[i] : '-'^!l[i],m+3)|>x->N<!l ? x : x[1:m÷2]*'|'x[m÷2+2:!x]).*f(N-n,L...;n=n)

```

Try it online!

A recursive solution, using multiple dispatch. `N` and the lists are taken as arguments of the function `f`. Returns a list of strings

+1 to fix a bug pointed out by Kevin Cruijssen
> 1 votes

# Answer
# JavaScript (Node.js), ~~205~~ 204 bytes

-1 byte thanks to @Kevin Cruijssen.

```
w=>n=>(R=Array(N=w[0][L='length']).fill``,w.map((C,x)=>C.map((c,y)=>R[y]+=c.replace(a=/./g,s=>j=n>y+N*x?'-':s).padEnd(l=Math.max(...C.map(s=>s[L]))+2).replace(a,(s,i)=>j&&n>=N*x+C[L]&i==l-3>>1?'|':s))),R)

```

Try it online!

Written using currying syntax, call as `S(w)(n)`. Outputs an array of lines containing the ASCII art.
> 1 votes

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


title: Why was 6 afraid of 7?

text:
# Question
Title: Why was 6 afraid of 7?
## *Why was 6 afraid of 7? Because 7 8 9!*

Given a string apply the following transformations:

* If there is a 6 next to a 7 remove the 6 (6 is afraid of 7)
* If the sequence "789" appears remove the 8 and the 9 (7 ate 9)

(If I'm not mistaken it doesn't matter what order you do the transformations in)

Keep applying these transformations until you can no longer.

Example:

`78966`

First we see "789", so the string becomes "766". Then we see "76", so we take out the 6, and the string becomes "76". Then we see "76" again, so we are left with "7".

Test Cases:

* `987` =\> `987` (Not in the right order. Does nothing.)
* `6 7` =\> `6 7` (The whitespace acts as a buffer between 6 and 7. Nothing happens)
* `676` =\> `7`
* `7896789` =\> `77`
* `7689` =\> `7`
* `abcd` =\> `abcd`

# Answer
# Retina, 12

Translation of the sed answer:

```
6*7(6|89)*
7

```

Try it online
> 31 votes

# Answer
# Java, ~~126~~ ~~81~~ ~~66~~ 58 bytes

Thanks to @GamrCorps for providing the lambda version of this code!

Thanks to @user902383 for pointing out an autoboxing trick!

...yup.

It's actually longer than I expected - Java replaces items in strings with `replaceAll()` once per match, not repeatedly until it stops changing. So I had to use a fancy for loop.

### Lambda form:

```
x->{for(;x!=(x=x.replaceAll("67|76|789","7")););return x;}
```

### Function form:

```
String s(String x){for(;x!=(x=x.replaceAll("67|76|789","7")););return x;}
```

### Testable Ungolfed Code:

```
class B{
    public static void main(String[]a){
        System.out.print(new B().s(a[0]));
    }
    String s(String x){for(;x!=(x=x.replaceAll("67|76|789","7")););return x;}
}
```
> 12 votes

# Answer
# Javascript ES6, 29 bytes

```
s=>s.replace(/6*7(89|6)*/g,7)

```

Test:

```
f=s=>s.replace(/6*7(89|6)*/g,7)
;`987 -> 987
6 7 -> 6 7
676 -> 7
7896789 -> 77
7689 -> 7
abcd -> abcd`
.split`\n`.every(t=>(t=t.split` -> `)&&f(t[0])==t[1])

```
> 12 votes

# Answer
# GNU Sed, 17

Score includes +1 for `-r` option.

```
s/6*7(6|89)*/7/g

```
> 9 votes

# Answer
# Perl 6,  ~~19~~  18 bytes

~~```
{S:g/6*7[6|89]*/7/} # 19 bytes

```~~
```
$ perl6 -pe 's:g/6*7[6|89]*/7/' # 17 + 1 = 18 bytes

```

( Note that `[6|89]` is the non-capturing version of `(6|89)` which is spelt as `(?:6|89)` in Perl 5. `<[6|89]>` is how you would write what's spelt as `[6|89]` in Perl 5)

usage:

```
$ perl6 -pe 's:g/6*7[6|89]*/7/' <<< '
987
6 7
6676689
7896789
7689
abcd
68978966897896
79|689
'

```

```
987
6 7
7
77
7
abcd
68977
79|689

```
> 8 votes

# Answer
# Pyth, 17 bytes

```
u:G"67|76|789"\7z

```

Try it here.

Leaky Nun has outgolfed this by a byte in the comments.
> 7 votes

# Answer
# Perl 5, 17 bytes

```
perl -pe 's/6*7(6|89)*/7/g' # 16 + 1

```

usage:

```
$ perl -pe 's/6*7(6|89)*/7/g' <<< '
987
6 7
6676689
7896789
7689
abcd
68978966897896
'

```

```
987
6 7
7
77
7
abcd
68977

```
> 5 votes

# Answer
## Mathematica, 52 bytes

```
StringReplace[#,"67"|"76"|"789"->"7"]&~FixedPoint~#&

```

Explanation:

```
                                                   &   A function returning
                                     &                   a function returning
              #                                            its first argument
StringReplace[ ,                    ]                     with
                "67"                                        "67"
                    |                                      or
                     "76"                                   "76"
                         |                                 or
                          "789"                             "789"
                               ->                         replaced with
                                 "7"                       "7"
                                    ~FixedPoint~        applied to
                                                #        its first argument
                                                        until it no longer changes.

```
> 4 votes

# Answer
# Ruby, 27 bytes

This solution is from comments, credit to *Brad Gilbert b2gills*.

```
->s{s.gsub /6*7(6|89)*/,?7}

```

---

## Ruby, 37 bytes

***(old solution)***

This solution uses the fact that you will never need to replace more times than characters in the string.

```
->s{s.chars{s.sub! /67|76|789/,?7};s}

```
> 3 votes

# Answer
# MATL, 17 bytes

```
jt"'789|76'55cYX]

```

### Example

```
>> matl
 > jt"'789|76'55cYX]
 >
> 7896789
77

```

**EDIT**: **Try it online!**

### Explanation

```
j                   % input string
t                   % duplicate
"                   % for each character. Iterates as many times as the string length
    '789|76'        % regular expression for replacement
    55c             % string to insert instead: character '7'
    YX              % regexprep
]                   % end for

```

This works by applying a regular expresion replacement for *as many times as there are characters in the original string*. This is enough, since each substitution reduces the number of characters.
> 3 votes

# Answer
## Rust, 96 bytes

```
fn f(mut s:String)->String{for _ in 0..s.len(){for r in&["67","76","789"]{s=s.replace(r,"7")}}s}

```

Hopelessly long, as per usual for Rust...

Ungolfed:

```
fn seven_ate_nine(mut str: String) -> String {
    for _ in 0..str.len() {
        for to_replace in &["67","76","789"] {
            str = str.replace(to_replace, "7");
        }
    }
    s
}

```
> 3 votes

# Answer
# Emacs Lisp, 59 bytes

```
(lambda(s)(replace-regexp-in-string"6*7\\(6\\|89\\)*""7"s))

```

It becomes a bit clearer with spaces:

```
(lambda (s) (replace-regexp-in-string "6*7\\(6\\|89\\)*" "7" s))

```
> 3 votes

# Answer
# Japt, 15 bytes

```
Ur"6*7(89|6)*"7

```

Simple RegEx solution

Try it online
> 2 votes

# Answer
# PowerShell, 27 bytes

```
$args-replace'6*7(89|6)*',7

e.g.
PS C:\temp> .\ate.ps1 "7689"
7

PS C:\temp> .\ate.ps1 "abcd"
abcd

PS C:\temp> .\ate.ps1 "68978966897896"
68977

```

Making use of:

* someone else's regex pattern
* the way `-replace` does a global replace by default in PowerShell
* loop unrolling, where it will apply the `-regex` operator to the array `$args` by applying it to all the elements individually, and there's only one element here because there's only one script parameter, so it works OK and we can avoid having to index element `[0]`.

---

Novelty previous attempt before realising a global replace would do it; 74 bytes of building a chain of "-replace -replace -replace" using string multiplication, as many times as the length of the string, then eval()ing it:

```
"'$($args)'"+("{0}6|6(?=7)'{0}89'"-f"-replace'(?<=7)")*$args[0].Length|iex

```

(With a bit of string substitution to shorten the number of replaces).
> 2 votes

# Answer
## Seriously, 29 bytes

```
,;l`'7;;"67"(Æ"76"(Æ"789"(Æ`n

```

Takes input as a double-quoted string, like `"6789"`. Try it online (you will need to manually quote the input).

Explanation:

```
,;l`'7;;"67"(Æ"76"(Æ"789"(Æ`n
,;l                            get input and push its length (we'll call it n)
   `                       `n  call the following function n times:
    '7;;"67"(Æ                   replace all occurrences of "67" with "7"
              "76"(Æ             replace all occurrences of "76" with "7"
                    "789"(Æ      replace all occurrences of "789" with "7"

```
> 1 votes

# Answer
## PHP, 36 bytes

```
preg_replace('/6*7(6|89)*/','7',$a);

```

regex solution, takes $a string and replaces via the expression.
> 1 votes

# Answer
# Thue, 26 bytes

```
67::=7
76::=7
789::=7
::=

```

including a trailing newline.

Input is appended to the program before starting it.
Output is read off the program state when it terminates, similarly to a Turing machine.
(Thue *does* have an output stream, but it's difficult to use correctly, so I'm not sure whether this is an acceptable output method)
> 1 votes

# Answer
## CJam, ~~70~~ 64 bytes

Thanks to @Peter Taylor for cutting `{"789":I}{"76:":I}?` to `"789""76"?:I`

`~~"67":Iq:A{AI#:B){AB<7+A{BI,+}~>+s:A];}{"76"I={"789":I}{"76":I}?];}?}/A~~`

`"67":Iq:A{AI#:B){AB<7+A{BI,+}~>+s:A];}{"76"I="789""76"?:I];}?}/A`

I know this could probably be golfed a lot further and your help would be greatly appreciated, but frankly I'm just happy I managed to get the answer. This was my first attempt at writing CJam.

Explanation:

```
"67":I                e# Assign the value of 67 to I
q:A                   e# Read the input and assign to A
{                     e# Opening brackets for loop
    AI#:B)            e# Get the index of I inside A and assign to B. The increment value by 1 to use for if condition (do not want to process if the index was -1)
    {                 e# Open brackets for true result of if statement
        AB<           e# Slice A to get everything before index B
        7+            e# Append 7 to slice
        A{BI,+}~>     e# Slice A to get everything after index B plus the length of string I (this will remove I entirely)
        +s:A          e# Append both slices, convert to string, and assign back to A
        ];            e# Clear the stack
    }                 e# Closing brackets for the if condition
    {                 e# Open brackets for false result of if statement
        "76"I=        e# Check if I is equal to 76
        "789"         e# If I is 76, make I 789
        "76"?:I       e# If I is not 76, make I 76
        ];            e# Clear the stack if I does not exist inside A
    }?                e# Closing brackets for false result of if statement
}/                    e# Loop
A                     e# Output A

```
> 1 votes

# Answer
## R, 35 bytes

```
cat(gsub("6*7(6|89)*",7,scan(,"")))

```

I didn't know I could use `gsub` this way, a big thank you for every answer here that made me learn something new.
> 1 votes

# Answer
# Dyalog APL, 17 bytes

```
'6*7(6|89)*'⎕R'7'

```

`'6*` any number of sixes
`7` followed by a seven
`(``)*'` followed by zero or more sequences of…
`6|89` a six or eight-nine

`⎕R`**R**eplace that with

`'7'` a seven
> 1 votes

# Answer
# ///, 19 bytes

```
/67/7//76/7//789/7/

```

You can't actually provide input in this language, so the supposed input goes to the right of the code, which is allowed by recent rules.
> 1 votes

# Answer
## Python 3, 46 bytes

```
import re
lambda s:re.sub(r'6*7(6|89)*','7',s)

```
> 1 votes

# Answer
# Jolf, 15 bytes

Try it here! Do I really have to explain?

```
pi"6*7(6|89)*"7
p               replace any entity in
 i               the input
  "6*7(6|89)*"   that matches this regex
              7  with 7
                implicit output

```
> 0 votes

# Answer
## **PHP 51 characters**

```
while($s!=$r=str_replace([789,67,76],7,$s)){$s=$r;}

```

**Test case written in long hand**

```
$s = '78966';
while ($s != $r = str_replace([789, 67, 76], 7, $s) )
{
    $s = $r;
}
echo $s; // 7;

```

This does the string comparison and the string replace both in the while condition. If while condition is met, it updates the left hand of the comparison with the result. Let me know of any improvements.
> 0 votes

# Answer
## Clojure, 71 bytes

Clojure is less-than-ideal for golfing due to its verbose nature - but nonetheless it's an interesting exercise:

Golfed version, using Java interop:

```
(defn f[s](let[x(.replaceAll s "67|76|789" "7")](if(= s x)s(recur x))))

```

Un-golfed version, using Java interop:

```
(defn six-fears-seven [s]
  (let [x (.replaceAll s "67|76|789" "7")]
    (if (= s x)
      s
      (recur x))))

```

Un-golfed "pure Clojure" version:

```
(defn six-fears-seven [s]
  (let [x (clojure.string/replace s #"67|76|789" "7")]
    (if (= s x)
      s
      (recur x))))

```
> 0 votes

# Answer
# Bash, 102 82 67 (+7)? bytes

### extglob version

```
x=$1
while v=${x/@(76|67|789)/7};[ $v != $x ];do x=$v;done
echo $v

```

This is meant to be put in a file and called with e.g. `bash -O extglob 789.sh 6567678989689789656`. The (+7)? bytes is for if the extglob option counts toward bytes.

Thanks to @BinaryZebra for pointing out extglob features!

---

### Non-extglob version (82 bytes)

```
x=$1
while v=${x/76/7};v=${v/67/7};v=${v/789/7};[ $v != $x ];do x=$v;done
echo $v

```

This is meant to be put in a file and called with e.g. `./789.sh 65678989656`.

It makes use of parameter expansion to search and replace in a loop. I involved a series of expansions to do the replacing since I'm not aware of a way to more effectively chain expansions.
> 0 votes

# Answer
# Japt v2.0a0, 12 bytes

```
e/6?7(6|89/7

```

Try it online!

### How it works

`String.e` is recursive replace function. Japt 2 has a new regex syntax and auto-completion of parentheses inside regex, which saves one byte here. (In Japt 1.x, we had to pass strings in place of regexes, which was kinda clunky.)
> 0 votes

# Answer
# 05AB1E, ~~12~~ 11 bytes

```
Δ67Â‚789ª7:

```

Try it online or verify all test cases.

**Explanation:**

```
Δ            # Continue doing the following until it no longer changes:
 67          #  Push 67 to the stack
   Â         #  Bifurcate (short for Duplicate & Reverse copy): 76
    ‚        #  Pair them together: [67,76]
     789ª    #  Append 789 to this list: [67,76,789]
         7:  #  Replace all occurrences of these three integers with 7
             #   i.e. 1789372 → 17372
             # (after the loop, output the result after implicitly)

```

`67Â‚789ª` could alternatively be `•4BĆx•₄в` for the same byte-count.
> 0 votes

# Answer
# K (ngn/k), 27 bytes

```
{x{"7"/y@x}/(\'$67 76 789)}

```

Try it online!

* `$67 76 789` shorthand for `("67";"76";"789")`
* `(\'...)` create list of splitter functions, i.e. `("67"\;"76"\";"789"\)`
* `x{...}/(...)` set up a reduce, seeded with `x` (the input), run over the list of splitter functions
    + `{"7"/y@x}` split the input (`x`) using the current splitter function (`y`), then join the result with `"7"`. feed this to the next iteration of the reduce
> 0 votes

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


title: Draw a battery indicator

text:
# Question
Title: Draw a battery indicator
Given the battery level `L` in the range `0-5`, your code should draw the following ASCII art.

When `L=0`:

```
############
#          ###
#          ###
#          ###
############

```

When `L=1`:

```
############
###        ###
###        ###
###        ###
############

```

When `L=2`:

```
############
#####      ###
#####      ###
#####      ###
############

```

And etc. You can change the character `#` to any other (except space), it's up to you. Trailing spaces are allowed.

This is a code-golf challenge so the shortest solution wins.

# Answer
# Google Sheets, 124 bytes

```
=substitute(query({rept("#",12);sort(if({1;1;1},"#"&rept("#",A1*2)&rept("-",10-A1*2)&"###"));rept("#",12)},,9)," ",char(10))

```

## 89 bytes if it's okay for the output to be displayed in separate cells

```
={rept("#",12);sort(if({1;1;1},"#"&rept("#",A1*2)&rept("-",10-A1*2)&"###"));rept("#",12)}

```

Try it here
> 14 votes

# Answer
# brainfuck, ~~266 245~~ 242 bytes

-21 bytes thanks to @emanresu A's suggestion to use `ÿ` instead of `!` (since `ÿ`'s charcode is the same as the glider reference value `255` on an 8 bit bf interpreter like TIO's).

-3 bytes by removing unnecessary code (at the expense of a pretty memory layout).

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

```

Try it online!

Uses a glider and fancy loop tricks to print the middle 3 rows. Uses `ÿ` instead of `#` since that is allowed by the challenge.

Ungolfed:

```
memory layout
(pni = 5 minus inp)
3   4   5   6   7   8   9   10  11  12
' ' \n  ÿ   pni inp pni inp pni inp ÿ

' ' = 32
-[-[-<]>>+<]>-
\n = 10
>>+++++[<++>-]
ÿ = 255
-

print top row of ÿs
>++++[<...>-]<<.>+

get input
>-[>+<-----]>---<,>[<->-]<[<+>-]<

copy to loop cells
[>->+>->+>->+<<<<<<-]
+++++[>+>>+>>+<<<<<-]
create glider refs
->>>>>>>-<+

main loop
[
  glider collision guard
  exit the loop when all loop variables are exhausted
  [-
    print first ÿ
    +[-<+]-.>
    +[->+]-
    print ÿs in battery
    <[
      +[-<+]-..>
      +[->+]-
      <-
    ]
    move glider back one cell
    >+<-
    print spaces in battery
    <[
      +[-<+]-<<..>>>
      +[->+]-
      <-
    ]
    print last 3 ÿs and \n
    +[-<+]-...<.>>
    +[->+]
    move glider back one cell
    <->
  ]<<+
]

print last row of ÿs
++++[>...<-]

```
> 13 votes

# Answer
# Python, 46 bytes

```
lambda n:[s:="#"*12,*3*[f'#{"##"*n:10}###'],s]
```

Attempt This Online!

Outputs a list of lines, as allowed by standard I/O rules.

\\$ -9 -1 = -10 \\$ thanks to @xnor

---

## Python, 76 bytes

```
lambda n,r=f"#{' '*10}#".replace:[a:=r(" ","#")]+[r(" ","#",2*n)+"##"]*3+[a]
```

Attempt This Online!

Did you know Python's `str.replace` method has a third parameter to limit the maximum number of replacements that will be performed? You do now!
> 10 votes

# Answer
# C (POSIX), 83 bytes

```
#define s"\n############"
#define r"\n%1$-11s###"
f(i){printf(s r r r s,s+12-i*2);}

```

I was originally tweaking ErikF's answer but ended up making more substantial changes, so it felt like a new separate answer. Note that this saves some space by printing a newline *before* the output, which has been approved.

Uses compile-time string concatenation to compress the output template, then uses `printf` to fill in the correct amount of the bar.

## Breakdown:

### `r` template pattern

```
\n             - print a literal newline
  %     s      - followed by a string
   1$          - from the first argument (POSIX extension)
     -         - padded with trailing spaces
      11       - to at least 11 characters
         ###   - followed by 3 literal hash symbols

```

### `printf` call

```
printf(
  s r r r s,     // concatenate define'd strings into full pattern
  s + 12 - i * 2 // first argument: fragment of s (last i * 2 + 1 characters)
);

```

### Expanded

```
f(i) {
    printf(
        "\n############\n%1$-11s###\n%1$-11s###\n%1$-11s###\n############",
        "\n############" + 12 - i * 2
    );
}

```

Try it online

---

As an interesting alternative, this version uses hex values to draw the shape, so it's limited to `f` characters, but avoids the initial newline. It is the same size (83 bytes):

```
#define r"%2$-11lxfff\n"
f(i){printf("%lx\n"r r r"%1$lx",(1l<<48)-1,(16l<<i*8)-1);}

```
> 7 votes

# Answer
# Charcoal, 18 bytes

```
ＵＯ⊕⊗Ｎ³-¹²↘‖Ｏ↓ＵＯ±³-

```

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

```
ＵＯ⊕⊗Ｎ³

```

Draw the fullness of the top half of the battery.

```
-¹²↘

```

Draw the line at the top of the battery and leave the cursor at the top right of the 3×3 square end.

```
‖Ｏ↓

```

Reflect to complete the fullness and sides of the battery. (This also moves the cursor to the bottom right of the 3×3 square end.)

```
ＵＯ±³-

```

Draw the 3×3 square end.
> 5 votes

# Answer
# *Acc!!*, 152 bytes

```
N-46
Count i while i-2 {
Count l while (l-3)*i {
Count c while c-14 {
Write 32+1/((c+3)/2%7/_+1)
}
Write 10
}
Count h while h-12 {
Write 33
}
Write 10
}

```

Uses exclamation points. Try it online!

### Explanation

This was fun to golf. The verbose syntax of *Acc!!* drove me to combine as many `Count while` and `Write` statements as possible, which required some interesting expressions to encapsulate the logic.

```
N-46

```

Read a character from stdin and store its codepoint minus 46 in the accumulator. If the input number is `L`, the accumulator now holds the value `L+2`.

```
Count i while i-2 {
...
}

```

Do the following twice:

```
Count l while (l-3)*i {

```

Do the following (output the middle part of the battery) three times, but only on the second iteration of the `i` loop:

```
Count c while c-14 {

```

Do the following (output a character in the middle part of the battery) fourteen times:

```
Write 32+1/((c+3)/2%7/_+1)

```

Write either a space or an exclamation point, based on the loop index `c` and the accumulator value `_`.

Observe that we want to output some number of exclamation points, then some number of spaces, then three more exclamation points. This looks like a slice into a periodic function. Since we want to add exclamation points in pairs, let's aim for something like this:

```
0         1
01234567890123456789
!!!!..........!!!!..

```

where `!` means "definitely maps to `!`" and `.` means "might map to either `!` or  depending on the accumulator value."

We want to run our loop from 3 to 16 in this function; since loop variables in *Acc!!* always start at zero, we'll just add 3 to the loop variable `c`.

Next, we combine the pairs of characters that will always be the same by int-dividing by 2:

```
0123456789
!!.....!!.

```

We can get the periodic behavior if we take this input mod 7:

```
0123456
!!.....

```

Now it's just a matter of adjusting the cutoff depending on the input value. Conceptually, we want exclamation points if this number is less than `L+2`, and spaces if it is greater than or equal to `L+2`. Conveniently, `L+2` is the value in the accumulator. Inconveniently, *Acc!!* doesn't have comparison operators, so we'll have to abuse some arithmetic:

With integer division, and assuming `b` is always positive, `a/b` is `0` if `a<b` and some positive number otherwise. To turn 0 vs positive into 1 vs 0, we can add 1 (making it 1 vs greater than 1) and then int-divide 1 by that quantity. End result: `1/(a/b+1)` is `1` if `a<b` and `0` otherwise.

In our case, we have `a = (c+3)/2%7` and `b = _` (the accumulator). Substituting those into the above expression and adding to `32` gives exclamation point (ASCII 33) or space (ASCII 32) exactly where we want them.

```
}
Write 10
}

```

Close the `c` loop, write a newline, and close the `l` loop.

```
Count h while h-12 {
Write 33
}
Write 10

```

Output the top/bottom of the battery: Loop 12 times and write exclamation point; then write a newline.
> 5 votes

# Answer
# Pari/GP, 82 bytes

```
n->[print(l)|l<-[s="############",e=Strchr([35-3*(j>n+n&j<11)|j<-[0..13]]),e,e,s]]

```

Try it online!

This code is most probably not the shortest possible, as this is my first time golfing in Pari/GP.

Thanks @alephalpha for -14 bytes.
> 4 votes

# Answer
# Vyxal, 18 bytes

```
d×*₀↲×p14e:"×12*p∞

```

Try it Online!

```
d                  # Input * 2
 ×*                # That many asterisks
   ₀↲              # Pad the left to length 10 with spaces
     ×p            # Prepend an asterisk
       14e         # Extend to length 14 by appending the first char
          :"       # Pair with itself
                p  # Prepend to this...
            ×12*   # 12 asterisks
                 ∞ # Palindromise the result

```
> 3 votes

# Answer
# Retina 0.8.2, 55 bytes

```
.+
#$&$*_10$* ###¶
+`(_*)_
##$1
.+¶
12$*#¶$&$&$&12$*#

```

Try it online! Explanation:

```
.+
#$&$*_10$* ###¶

```

Produce a body row of the empty battery but include `L` `_`s.

```
+`(_*)_
##$1

```

For each `_`, delete two spaces and add two `#`s.

```
.+¶
12$*#¶$&$&$&12$*#

```

Triplicate the row and wrap it in lines of 12 `#`s.
> 2 votes

# Answer
# C (gcc) with `-lm`, ~~93~~ 91 bytes

* -2 thanks to ceilingcat

Uses `9` as the fill character. I make use of 10*n*-1 producing *n* nines when *n*\>0.

```
*s="999999999999";f(i,j){for(puts(s),j=3;j--;printf("%-11.f999\n",exp10(i-~i)-1));puts(s);}

```

Try it online!
> 2 votes

# Answer
# Python 3.8, ~~85~~ ~~72~~ ~~68~~ ~~49~~ 46 bytes

```
lambda l,a="##":[a*6,*3*[f'#{l*a:10}###'],a*6]

```

Outputs a list of strings, as allowed by standard I/O rules

Try it online!

-13 thx to @Aiden chow

-4 thx to @ovs

-3 thx to @Aiden chow
> 2 votes

# Answer
# Julia 1.0, ~~57 51~~ 48 bytes

```
c='#';!n=[c^12,(h=rpad(c*c^2n,11)*c^3;),h,h,c^12]

```

Try it online!

-3 MarcMush
> 2 votes

# Answer
# Excel, ~~82~~ 74 bytes

It Taylor Rained 8 bytes.

```
=LET(a,REPT("#",12),b,MID(a&REPT(" ",10),12-2*A1,11)&"###
",a&"
"&b&b&b&a)

```

Input of `L` is in the cell `A1`. Output is wherever the formula is. For best results, make sure the column is wide enough, text wrapping is on, and the font is monospace. The output will be correct regardless but this makes that fact visually apparent.

* `LET(a,REPT("#",12)` defines `a` to be 12 number signs in a row. Combining `LET()` and `REPT()` only saves us 1-3 bytes but savings are savings.
* `b,MID(a&REPT(" ",10),12-2*A1,11)&"###\n"` has a lot going one but the summary is this:
    + Create a string of 12 `#` and 10 spaces.
    + Find the right spot (based on the input) in the middle of that string to start pulling characters.
    + Pull 11 characters (1 `#` \+ 2\*input `#` \+ however many spaces).
    + Add `###` and a line break.
    + Set the resulting string to the variable `b`.
* `a&"\n"&b&b&b&a` concatenates the pieces into an output.
> 2 votes

# Answer
# brainfuck, 202 bytes

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

```

Try it online!

first, I try to comment this shorter bytes brainfuck to first brainfuck(245 bytes) comment, but i don't have enough reputation. so i decide to comment here and give the link to that first comment. also if I can, I will try to expaining this code later
> 2 votes

# Answer
# JavaScript, 76 70 bytes

-6 thanks to Hannesh

```
_=>(a=`############
`)+`#${'##'.repeat(_).padEnd(10)}###
`.repeat(3)+a

```

Try it Online!
> 2 votes

# Answer
# C++, 267 bytes

```
#include<iostream>
#define c std::cin
#define o std::cout
#define h()o<<H<<'\n'
#define L 12
#define H 111111111111
#define M 1
typedef int I;
I main(){I l;c>>l;h();for(I i=0;i<3;i++){o<<M;for(I j=0;j<l*2;j++){o<<1;}for(I k=0;k<L-l*2-2;k++){o<<' ';}o<<111<<'\n';}h();}

```

Try it Online!

First time golfing in C++, not sure if it's good or not.
> 2 votes

# Answer
# Python 3, 86 bytes

```
a,b="#"*12,int(input())
c="#"+"#"*2*b+" "*(10-2*b)+"###"
print("\n".join([a,c,c,c,a]))

```

Try it online!

Quick and dirty, but it works.
> 1 votes

# Answer
# Charcoal, 49 bytes

```
Ｐ×-¹²Ｐ↓×-⁵≔Ｎα↓→Ｆ³«Ｐ×-×α²↓»Ｐ×-¹¹Ｆχ«→»Ｐ↑×-⁴Ｆ³«↑Ｐ×-³`

```

Try It Online! Link is to verbose version of code.

My second Charcoal answer!

Uses "`-`" instead of "`#`" because if I change, The Output uses both "-" and "#".

## Explanation:

TODO: Understand the code and explain
> 1 votes

# Answer
# Java (JDK), 98, 95 bytes

```
L->{System.out.format("%s"+"%2$-11s###\n".repeat(3)+"%1$s","############\n","#".repeat(L-~L));}

```

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~19~~ 18 bytes

```
X12×$·×Tj7bìĆRD».∊

```

Outputs `1` instead of `#`.

Try it online or verify all test cases.

**Explanation:**

```
X               # Push 1
 12             # Push 12
   ×            # Repeat the "1" 12 times: 111111111111
$               # Push 1 and the input
 ·              # Double the input
  ×             # Repeat the "1" that many times
   Tj           # Pad it with leading spaces up to length 10
     7bì        # Prepend the binary of 7: 111
        Ć       # Enclose; append its own head
         R      # Reverse it
          D     # Duplicate it
           »    # Join the stack with newline delimiter
            .∊  # Mirror it vertically with overlap
                # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Noether, 76 bytes

```
I~l12("#"P!i)?3(0~rl2*1+("#"P!r)0~r11l2*-(r0{>}{" "P}!r)"###"P?!k)12("#"P!y)

```

Try it online!
> 1 votes

# Answer
# Perl 5, 63 bytes

```
$_=($s='#'x12 .$/).('#'.'#'x($x=2*$_).$"x(10-$x)."###\n")x3 .$s

```

Try it online!
> 1 votes

# Answer
# J, ~~50~~ ~~46~~ 44 bytes

```
(a,3 1#(a=:12#'#'),:~'# #'#~(>:,10&-,3:)@+:)

```

Found that building row by row can be shorter.

Try it online!
> 1 votes

# Answer
# Lua, 87 bytes

```
x,b=...,"\n"d=b.rep a=d("#",12)print(a..b..d(b.format("%-11s###\n",d("#",1+2*x)),3)..a)

```

Attempt This Online!

My alternate approach before the format string was 6 bytes longer at **93 bytes**:

```
x,b=...,"\n"d,f=b.rep,''a=d("#",12)print(a..b..d(d("#",1+2*x)..d(" ",10-2*x).."###"..b,3)..a)

```
> 1 votes

# Answer
# Pip, 29 bytes

```
i:00YPiX6L3P[iJiXa.sXt-2*ai]y

```

Attempt This Online!
> 0 votes

# Answer
# APL+WIN, 51 bytes

Prompts for n

```
t←14↑12⍴'#'⋄v←3 14⍴' '⋄v[;(⍳1+2×⎕),11+⍳3]←'#'⋄t⍪v⍪t

```

Try it online! Thanks to Dyalog Classic
> 0 votes

# Answer
# PowerShell, 45 bytes

```
%{'#'*12;"#{0,-10}###`n"-f('##'*$_)*3+'#'*12}

```

Try it online!

Try it in a PS console (Windows or Core):

```
 0..5|%{'#'*12;"#{0,-10}###`n"-f('##'*$_)*3+'#'*12}

```

## Explanation

`%` is an Alias for the Cmdlet "ForEach-Object", which accepts input from the pipeline and processes each incoming object inside the ScriptBlock `{...}`
`'#'*12;` First line, PowerShell can "multiply" strings; the `;` terminates the command, output is implicit.
`"#{0,-10}###`n"` The level row; `{0,-10}` is a placeholder where the first argument of the following `-f` format operator will be inserted. `-10` will print the string inserted left-aligned, and padded to a length of 10. The  ``n` is a newline.
`-f('##'*$_)` Inserts the actual level into the row using the `-f` format operator; `$_` is the current input value.
`*3` Multiplies the level row created by `"#{0,-10}###`n"-f('##'*$_)` three times
`+'#'*12` Adds the last line to the level rows created above.
Output is implicit.
> 0 votes

# Answer
# Canvas, 23 bytes

```
２×╵#×α⁵∔ ×#３×）∑３＊#⁶×ｑ；Ｏ

```

Try it here!

### Explanation:

```
２×╵                         push input*2+1 (called n)
    #×                       repeat '#' n times
      α⁵∔ ×                  repeat ' ' 11-n times
           #３×               repeat '#' 3 times
               ）∑            join
                  ３＊         repeat 3 times vertically
                     #⁶×       repeat '#' 12 times
                        ｑ；Ｏ  print without popping, reverse stack, print stack

```
> 0 votes

# Answer
# CJam, 38 bytes

```
li2*:I;'#:OC*N+_O_I*+AI-S*+O3*+N+3*\++

```

Try it online!
> 0 votes

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