title: Which character to change (Robbers)

text:
# Question
Title: Which character to change (Robbers)
Cops thread
Robbers, your task is to crack a cops answer. Reveal the character that should be changed and what it should be changed to too. Please notify the cop if you cracked their challenge.

The robber winner is the user with the most cracks.
I will declare the winner cop and robber a week after this challenge is posted.

### Example Submission

<pre><code># Cracked [math's answer](http://example.com/17290/Change-a-character)

1[`a`|`b -> a

0[`a`|`b -> b

[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=1%5B%60a%60%7C%60b&inputs=&header=&footer=)
```
</code></pre>

# Answer
> 10 votes
# Python 3, 53 bytes, cracks dingledooper's 51 bytes

```
r=(1,)*8**9
r=r,len,ﬆr=r,str,sum
print(len(str(r)))

```

Try it online!

Replaces the newline at the end of the second line with . This is LATIN SMALL LIGATURE ST which is U+FB06, but Python 3 is apparently willing to interpret it as `st` in `str`. I spent some time thinking "if only I could make two letters" until I googled for "st ligature" which does just that.

The second line now redefines `str` as `sum`, and `len` as `str`, so `len(str(r))` is now `str(sum(r))`, which is just the stringification of its length of `r`, which is `8**9`. Also apparently the `r=r` in the trio of assignments overrules the left `r=...`, causing `r` to retain its original value.

# Answer
> 9 votes
# , cracks Robin Ryder's answer

```
a=b=co2
for(a in 0:b)pi=pi+exists("c")/4
intToUtf8(pi)

```

Try it online!

The clue was in the `exists("c")` bit: `c` is a built-in function in , so `exists("c")` will always be `TRUE`, even without the definition of a variable `c` on the first line. So we look for built-in variables starting with `c`... wait... there's one called `co2` \- one character away from `c=2`.
The first element of `co2` is 315, and 315/4 equals 78.75, which after addition of `pi` and rounding to an integer equals 82, the ACII value of `"R"`.

# Answer
> 7 votes
# Cracked A username's Vyxal answer

My complete lack of knowledge of Vyxal may have helped here as it allowed me to just try random things instead of trying to figure out what the obscure hack might be.

```
kaka(|←

```

Try it!

# Answer
> 6 votes
# Sisyphus, Python 2

```
print pow(2,2**1337133713371337,195889276175237072760362530940173700767)

```

I solved this by brute forcing the change needed to the modulus and exploiting the fact that \\$a^x = a^{x \bmod \lambda(n)} \pmod n\\$, where \\$\lambda\\$ is Carmichael's lambda function. This requires factoring \\$n\\$. Fortunately, the modulus is relatively small; had it been larger, we'd need to factor a large semiprime just to *verify* a guess.

# Answer
> 6 votes
# Python 2, cracks xnor's answer

```
print 0in(0,0)>min(0,0)

```

Try it online!

# Answer
> 5 votes
# Cracked Vyxal's lyxal answer

```
`Ẇ₁¹kḢ`«∧λf⇧\#¯ḣ⌐ƒż1

```

Try it Online!

Once I realized A) the lambda is useless because it always returns 1, and B) the target string consists only of lowercase letters and whitespace, the crack became trivial.

# Answer
> 4 votes
# Vyxal, cracks A username's second answer 5 bytes

```
lyoax

```

Try it Online!

# Answer
> 4 votes
# Cracked tsh's answer

```
a=9
if(a>0)a=0xa>9&&print(a)

```

Replacing the newline moves the `print` to occur before the assignment; choosing `x` as the replacement character creates a hexadecimal value greater than 9.

Try it Online!

# Answer
> 4 votes
# APL (Dyalog Extended), cracks Adám's second answer

```
≢∊⎕AT¨⎕A

```

Try it online!

is changed into `T`, making a totally different system function `⎕AT`, "Attributes".

`⎕AT` takes a name, and gives some attributes about it. The only thing that is important here is that, given an undefined name, `⎕AT` returns a row of `(0 0 0)(0 0 0 0 0 0 0)(0)('')`, which has 11 atoms in total. `⎕AT¨⎕A` calls `⎕AT` on each of the 26 uppercase alphabet, and since none is defined yet, returns 26 such rows. The total number of atoms in this array is `26×11=286`.

# Answer
> 3 votes
# Cracked A username's Vyxal answer

Ninjaed by pxeger :\

```
lyoax

```

Try it Online!

# Answer
> 3 votes
# Cracked DLosc's Pip answer

```
-PZ-PI

```

Try it online!

I don't know how this language works, I just looked through the docs and found a `PZ` function.

# Answer
> 3 votes
# Cracked Daniel H.'s Rattle answer

```
d&|!p

```

Try it!

# Answer
> 3 votes
# Vyxal, 24 bytes, cracks A username’s answer

```
kHø`string`D‟‟Ẋf∑vd∑qĖ₁Ẏ

```

Try it Online!

# Answer
> 3 votes
# Jelly, 11 bytes, cracks Caird’s answer

```
“Y$Ḥß““¿<ȧ»

```

Try it online!

# Answer
> 3 votes
# JavaScript (Node.js) by A username, 155 bytes

```
z=247275939563830539741033318025n
k=''
e='Hello, world'
while(z) k+=String.fromCharCode(Number(z%128n)),z/=128n;
console.log(eval([...k].reverse().join``))

```

Try it online!

Changes `"console.log(e)"` to `"console.log;\n\t"`

I mostly found this by narrowing down after which digit the `console.log` ended and then just spamming guesses until I found something syntactically valid that would `eval` to the same thing as `console.log` itself.

# Answer
> 3 votes
# , cracks Robin Ryder's second answer

```
a=b=2
for(a in 0xb)pi=a+a-pi
el(LETTERS[pi])

```

Try it online!

`0xb` denotes hexadecimal number `b`, or eleven. So the `for` 'loop' becomes just a single pass, setting `pi` equal to `11+11-pi`, which is 18.85841.
`LETTERS[pi]` rounds this to the integer 18, and selects that capital letter: the 18th letter is `"R"`.

# Answer
> 3 votes
# , cracks Robin Ryder's 3rd answer

```
x=z=6
y=0
while(x+7-1>y){x=x-1;z=z+1}
LETTERS[z]

```

Try it online!

Changes the first `y` in the while loop condition to a `7`.

Cracked by educated manual semi-brute-force.

# Answer
> 3 votes
# , cracks Robin Ryder's fourth answer

```
x=z=6
yy=0
while(x+yy->>yy){x=x-1;z=z+1}
LETTERS[z]

```

Try it online!

Preamble:  code encourages the use of the right-to-left assignment operator `<-` instead of `=` (as in `x<-3` instead of `x=3`); this isn't seen much in `code golf`, of course, as it's one character longer. There is also a - much less used - left-to-right version, `->` (so `3->x` is equivalent to `x<-3` and `x=3`), and - even less used - versions that assign into the parent scope: `<<-` and `->>`.
The crack of Robin's answer uses this last one to sneakily assign `x+yy` directly to the variable `yy`, replacing the comparison in the `while` condition.

# Answer
> 3 votes
# , cracks Dominic's R answer

```
a=b=c=2
for(a in 1:b)c=c*3i
el(LETTERS[-c:0])

```

Try it online!

Our goal is to extract 18th letter ("R") from built-in `LETTERS`. It is to be done with here `c=17` or `c=-18`. After noticing that `pi` is very close to a digit with an imaginary number `[0-9]i`, we can indeed conclude that `3i` is our answer - for loop executes twice and effectively we multiply `c=2` by `3i*3i=-9`, which leads to `c=-18`.

# Answer
> 3 votes
# Japt, cracks user's answer

```
"1,2"c@X+2

```

Try it online!

I know nothing about Japt, but found the `c` function while scrolling through the docs, which seems to map each character `X -> f(X)` by ASCII value. This works out nicely since `"1,2"` and `"3.4"` differ by an ASCII value of 2.

# Answer
> 3 votes
# , cracks Robin Ryder's 5th answer

```
PO=0
TA=TO =min(0 * 0 * 0, FALSE, 0 * 0 * 0)
if(TA^TO)PO=18
LETTERS[PO]

```

Try it online!

Changes `|` (logical OR) for `^` (exponentiation). Zero raised to the power of zero is one, and so truthy.

# Answer
> 3 votes
# \>\<\>, cracks A username's answer

After drawing some execution paths by hand, I replaced a `/` in the first line with a space.

```
\\ /   \     9    \
/\     /  /\  /   \\
    / 1/  \       \\\
\\ //  \  \\  /    \\\
 \\  /\ / \\\/ \   \\\\
 ///  \\   \ \//   // \\
/ /\  \\\ \/ \\ \  \\/ /
\\ / \  \\     /\\ // /
//  /     \\\   \\ \ \  \
\\\  /\\/// \ \\// /  \ +
///\ /\/\/ //   /    /
\\/\\/\/\/ / /// / /3 / n\
// \\     /         \ / /
  \ \/\/\/ / // // \/ /  /
\\  //\/\/ / / /  / ;
   \//\/\\ /\/\ /     /
 \  \    \//\ /    \/
 /       //  \ ///
/\\/\/ /\///\\ //
  \/\/
  //\\//\/     \\
 \\  \/    /\/ /\\
\ \  \/  \\  /  //
  \  \/  \/
     \     /\/ \/

```

Try it online!

The relevant commands are `1 9 + n ;` I don't really know how the IP gets to this path, but here is the end of the new execution path:

# Answer
> 3 votes
# Julia 1.0, cracks MarcMush's answer

```
show(sum(count.(==('1'),bitstring.(Inf16[9973%36]))))

```

Try it online!

`Int16` is the type for signed 16-byte integers. `Inf16` is the 16-byte version of `Inf`, a value greater than all 16-byte floating-point values. Its binary representation is `0111110000000000`, with the required five `1`s.

# Answer
> 3 votes
# APOL, cracks Ginger Industries' answer

```
ƒ(56 ¿(%(I(I(∈ )) 4) ¿(F :(33:3():33::()) ¿(F 2  ¿(T(∈) 2 3))))((X)) )

```

Try it Online!

I just went through each command and found what it did in the docs, and figured out that the condition on the last `¿` statement needed to return true, so I just put a `True` in there, and it worked. Here's some golfed code to achieve the same result:

```
ƒ(56 ¿(%(∈ 4) 2))

```

Essentially, for every number `x` in the range `[0..56)`, change the number to `2` if `x % 4` is truthy, otherwise change it to `None`.

# Answer
> 2 votes
# Cracked DLosc's 2nd Pip answer

```
E***t

```

Try this code here

If you don't want to run the code yourself, this is what it looks like:

```
=== Welcome to Pip, version 0.21.07.05 ===
Enter command-line args, terminated by newline (-h for help):

Enter your program, terminated by Ctrl-D or Ctrl-Z:
E***t
Executing...
42

```

# Answer
> 2 votes
# Vyxal `o`, cracks Aaron Miller's answer, 13 bytes,

```
`₴ḟ₴`₴`Buzz`F

```

Try it Online!

Vyxal's dictionary compression uses SCCs, two non-ascii characters joined together to make something that decompresses into a word. However, a single unmatched non-ascii character is a NOP, so replacing the space with that removes the space.

# Answer
> 2 votes
# Rattle, 8 bytes, cracks Daniel H.'s answer

```
<[c]@I^p

```

Try it Online!

# Answer
> 2 votes
# hyper-neutrino, Jelly

```
“5gỊƑ!ṆḥḌ³`⁻Ɓc?Ạ°þạḅI§Ɠ¦mṪ9ʂ:Nȯx1®Ḟ ƭḣTsÄẉṭ7|ẏẋzⱮɦḲ⁵.ṗbÐɱ8Ñ3"Øȧ¡Ė÷ʠ\¬ṇƥṀœṙRṅẈɓẒ#Ẏỵ⁼Ȧ©MỴƤ⁷ẹ⁴ż;OṃċẊnFḶ¤ȤḟỤẇçİ/ƒjƬhƙA2PẸtX¿ṢḢṡyiṂCd)ÆṣĠʋŒ-ė~YZ⁾ĿṘ²ŀ'ṄLȷU£BSƲɼṛñ½ȥÞ6pḂæ×ẆɠG4ịı$EƊ¹¥ḃɗ}DK]u*ġṚk⁹ɲḊµṾW_,ȧwß⁺⁸0ọv(<Ɲṁḍl=Q+ð@Çø[Żṫoera&Ọ¢Vḷ¶Ṗ€ƈḋ{⁶ƇĊqḄHḳJ⁽Ȯ%>^ḤṠfƘṬ‘Œ¿

```

Just brute force. Try it online!

# Answer
> 2 votes
# Japt, cracks Shaggy's answer

```
PùÅÔÌ

```

Try it online!

This was pretty simple. Shaggy's original started with `¤` instead of `P`, which converted the input (`0` if not given) to a base 2 string (`"0"`). However, `P` is the empty string. After that, `ùÅ` pads to length 1 using `s`, which is useless for the original, but turns the cracked version into `"s"`, which is exactly what we want. `Ô` reverses the string and `Ì` gets the last character, so they're both basically no-ops for single-character strings.

## Another crack

```
¤ù¤ÔÌ

```

Try it online!

This time, the `Å` is replaced with `¤`, so that it pads with `s` to a length of two instead of just one, making the string `s0`. `Ô` reverses it and `Ì` picks the last character, `s`.

# Answer
> 2 votes
# , cracks pajonk's answer

```
a=is.numeric
bb=strrep(11,1)
"if"(a(bb),LETTERS[a(bb)],"R")

```

Try it online!

`as.numeric` returns its argument coerced to numeric form; `is.numeric` \- which conveniently differs by only a single character - returns `TRUE` if its argument is already numeric, and `FALSE` otherwise. `FALSE` is the case here, since `bb` is a character string (of digits).

# Answer
> 2 votes
# , cracks Robin Ryder's 5th answer

```
PO=0
TA=TO =min(0 * 0 * 0, FALSE, 0 * 0 * 0)
if(T |TO&TA&TO)PO=18
LETTERS[PO]

```

Try it online!

Maybe another unintended crack...

I know nothing about . I just know TRUE is truthy.

# Answer
> 2 votes
# Cracked agtoever's answer

```
import operator as o
import inspect as i
a,d = 37,lambda n:n if len(str(n))==1else d(sum(map(int,str(n))))
for k, v in{d(sum(map(ord, n))): f for n, f in i.getmembers(o,i.isbuiltin)[::11]}.items():
 a+= int(v(a,k**2))
print(a)

```

Changed a space to a plus sign on line 5.

Try it online!

# Answer
> 2 votes
# brainfuck, cracks Zachary Cotton's answer

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

```

Try it online!

Simple, really. We just have to print each byte decremented by one. An obvious way to do this is to replace a `+` with a no-op, right before the printing begins.

# Answer
> 2 votes
# Cracked Bubbler's answer

`13024e0` -\> `13024`

`130b4e0` -\> `69420`

This is \\$(4,14,0)\_{130}\\$.

Try it online!

# Answer
> 2 votes
# APL (Dyalog Unicode), cracks Adám's answer

```
{(⍵ ⍵)(⍵ ⌶)(⍵ ⍵)},8

```

Try it online!

Because of how APL's parsing works, it is possible to get a meaningful result only when the first or second `(...)` is changed into a function, and it is only possible in the form of either `(⍵X⍵)` (using a dyadic operator X) or `(⍵ X)` (using a monadic operator X).

So I went through the built-in operators in turn until I hit  (a monadic op that becomes an experimental function based on an integer code).

`8⌶` is Inverted table index of. It takes "inverted tables" on its two sides, and computes "index of" rows of right arg in rows of left arg. `⍵ ⍵` is treated as a single-row, two-column table for this purpose, and the row to search is trivially found at index 1. Therefore the result is `1`.

# Answer
> 2 votes
# Labyrinth, cracks Bubbler's answer

```
99>
!!@

```

`9`, right, `9`, down, `!`, print 99, up, `9`, right, `>`, pop 9 and rotate the bottom row to `@!!`, down, `!`, print 0, left, `!`, print 0, left, `@`, end.

Try it Online!

# Answer
> 2 votes
# Vyxal, 14 bytes, cracks A username's answer

```
‛⟑»:K:Ẋf∑$βS2Ẏ

```

Try it Online!

Probably not the intended solution, but this simply changes the compressed string from `iraq` to `hours`. The string itself doesn't matter, what matters is that it is a string made of 5 different characters. In fact, if you could change 2 characters, you could change it to `Vyxal` (`₴ŀ`) and it would still work.

# Answer
> 1 votes
# Vyxal `s`, 13 bytes, cracks A username’s answer

```
khǍ⇩k•$Fk¹FsU

```

Try it Online!

# Answer
> 1 votes
# Japt, cracks Shaggy's answer

```
@TwXµY *!ZøX ªX+YÑ}gB Bs

```

Try it here.

The trick here is to replace the unicode shortcut `Ì` (equal to `gJ`) with `B` (equals `11`), breaking the chain and resulting in a comma operator instead. A nice brain teaser for sure.

# Answer
> 1 votes
# Yggdrasil, 3 bytes, cracks Aaron Miller's answer

```
?.:

```

Try it online!

Honestly just tried random commands until I found something that worked. I realised the `.` had to be there, and the `:` printed it all, so the first character needed modifying.

# Answer
> 1 votes
# brainfuck, cracks emanresu A's answer

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

```

Try it online!

The unmodified program prints a single byte per iteration of the main loop. This means there are two ways to make it print more than the original two bytes:

* Make one of the inner loops print the entire output in one run. This seems unlikely as the loops are quite simple.
* Change the `>+<` in the end to get away from the zero cell. There are only a few changes that make some sense, so I got to `>++` in a few attempts of trial and error.

# Answer
> 1 votes
# \>\<\>, cracks Fmbalbuena's answer

```
 \   ÇÇÇÇÇÇÇÇ
/!\; ÇÇÇÇÇÇÇÇ
\n/!<ÇÇÇÇÇÇÇÇ
 !   ÇÇÇÇÇÇÇÇ
 >  ^ÇÇÇÇÇÇÇÇ
\\2   \! \/! ~! \
 ÇÇÇ\ v! ~      /
 ÇÇÇÇÇ\'"a"\ÇÇÇÇÇ
 ÇÇÇÇÇÇÇÇ\\/ÇÇÇÇÇ

```

Try it online!

The changed character is the second backslash on the last line (previously a space), which sends the instruction pointer upwards to collect the string  `/ÇÇÇÇÇ\` before continuing along a path that removes the last two values from the stack and prints 199 (the character code of `Ç`).

# Answer
> 1 votes
# Javascript (REPL?), cracks Nicolas B's answer

```
a=!![],a++,a+!![]

```

Replacing the `+=` with `+!`.

# Answer
> 1 votes
# Python 3, cracks grandBagel's answer

```
a=6
b=++a++a++++a++a
a=5*5/5**2
print(b*1-b)

```

Try it online!

The thing that makes the output a float is multiplying `b` by `a`, which has a value of `1.0`. If we multiply `b` by `1` instead, the result is an int.

---
Tags: string, source-layout, cops-and-robbers
---


title: Extended Truth Machine

text:
# Question
Title: Extended Truth Machine
Many people know what a truth machine in programming is. But is time we kick things up a notch. Introducing, the extended truth machine! An extended truth machine takes two things as input, a integer `n` and a nonempty string `s`. It outputs `s` `n` times with optional trailing whitespace. However, if `n` is equal to `0`, you must output `s` until the program is manually stopped i.e. it should never terminate.

Also, if `n` is a negative number, then the string needs to be reversed. For example with `s=hello` and `n=-1`, output would be `olleh`.

Standard methods of input, any kind of output as long as it can handle infinite. If you have an answer that does not handle infinite, feel free to post it if it is interesting or in a language that cannot handle infinite output.

# Test Cases

```
n, s, output

5, "hello world", "hello worldhello worldhello worldhello worldhello world"
0, "PPCG", "PPCGPPCGPPCGPPCG..."
-2, "truThY", "YhTurtYhTurt"
2000, "o", "oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"

```

This is , so shortest code wins!

Here is the original Sandbox post. Edits have been made to it. Thanks go to @ComradeSparklePony for creating the idea of this challenge

# Answer
> 3 votes
## Haskell, ~~57~~ 54 bytes

```
f 0=cycle
f n|n<0=f(-n).reverse|n>0=concat.replicate n

```

Explanation:

```
f 0           -- If n=0 ..
 =cycle       -- infinitely repeat the input
f n|n<0       -- Otherwise, if n<0 ..
 =f(-n)       -- call f with the negative of n ..
 .reverse     -- and the reverse of the input
 |n>0         -- Finally, if n>0 ..
 concat       -- concatenate the result of ..
 .replicate n -- repeating the input n times

```

-3 bytes thanks to @nimi

# Answer
> 2 votes
# PHP\>=7.1, 67 Bytes

```
for([,$x,$y]=$argv,$z=$x<=>0;!$z||$x;$x-=$z)echo$x<0?strrev($y):$y;

```

Version with `list(,$x,$y)` instead of `[,$x,$y]` Try it online!

# Answer
> 2 votes
# 05AB1E, ~~17~~ ~~16~~ 14 bytes

```
0‹iR}¹Ä×¹_i[²?

```

Try it online!

**Explanation:**

```
0‹iR}¹Ä×¹_i[²?
0‹             Is the input negative?
  iR}          If so, reverse the second input.
     ¹Ä        Get the absolute value of the first input.
       ×       Repeat the string that many times.
        ¹_     Boolean NOT the first input. (Is the first input 0?)
          i    If so...
           [   Do forever...
            ²? Print the second input without a newline.

```

Saved 2 bytes thanks to @EriktheOutgolfer

# Answer
> 2 votes
# MATL, 37 bytes

```
jXJiXI0=?`1wtwDw]}I0>?I:"t]x}PI|:"t]x

```

Try it online!

Explanation:

```
j            % input string
XJ           % copy to clipboard J
i            % input
XI           % copy to clipboard I
0            % number literal
=            % is equal? (element-wise, singleton expansion)
?            % if
  `          % do...while
    1        % number literal
    w        % swap elements in stack
    t        % duplicate elements
    w        % swap elements in stack
    D        % convert to string and display / string representation
    w        % swap elements in stack
  ]          % end
}            % else
  I          % paste from clipboard I
  0          % number literal
  >          % is greater than? (element-wise, singleton expansion)
  ?          % if
    I        % paste from clipboard I
    :        % range; vector of equally spaced values
    "        % for
      t      % duplicate elements
    ]        % end
    x        % delete
  }          % else
    P        % flip the order of elements
    I        % paste from clipboard I
    |        % absolute value / norm / determinant
    :        % range; vector of equally spaced values
    "        % for
      t      % duplicate elements
    ]        % end
    x        % delete
             % (implicit) end
             % (implicit) end
             % (implicit) convert to string and display

```

# Answer
> 1 votes
## Python 3, 71 bytes

```
def f(n,s,k=1):
 if n<0:s=s[::-1];n=-n
 while n|k:print(end=s);n-=1;k=0

```

Try it online!

The variable `k` guarantees the loop is always run at least once. This means that if `n=0`, then `n` will be negative on the next iteration of the loop, so the loop will continue to be run forever.

# Answer
> 1 votes
# Matlab, 87 bytes

```
n=input('')
s=input('','s')
a=repmat(s,1,abs(n))
while~n s=[s s]
end
if n<0,flip(a)
end

```

My first attempt at code-golf! Any suggestions for golfing are welcome.

# Answer
> 1 votes
# Cubix, 41 ~~Forty four~~ ~~45~~ bytes

Takes input as *`<N> <String>`*

```
.uq.sB.p$IA;p?;ouu(..!q/o()uq?..@<w?q<<_)

```

Try it online!

Cubified:

```
      . u q
      . s B
      . p $
I A ; p ? ; o u u ( . .
! q / o ( ) u q ? . . @
< w ? q < < _ ) . . . .
      . . .
      . . .
      . . .

```

Watch it running

There is still an amount of no-ops in the code which I might be able to get a few more bytes out of, but wanted to get this up before I break it.

Basic procedure is

* `I` get counter from input
* `A` take the rest of input in as characters
* `;p?` remove the space, bring the number up and test it
    + `psuqB$)` if the counter is negative, reverse the stack. This involves handling the input number and EOI marker(-1). Increment the counter.
    + `;p;ouqu` if the counter is zero, remove the counter and EOI marker and start perpetual output loop.
    + `(` if positive decrement the counter
* `<<q?/o()u` the output loop. This will output each character of the stack until the EOI marker (-1) is reached.
* `... _ ... ?wq!` on end EOI marker, go around the cube and reflect back to the `?`, change lane, drop the EOI marker to the bottom and test the counter.
* `@` if zero, halt
* `?u(` if positive u-turn and decrement, thie ends up hitting the beginning of the loop
* `? ... <)` if negative, go around the cube to the otherside, redirect to the beginning of the loop while passing over a increment.
* `/)<` if negative increment and carry on to output loop

# Answer
> 0 votes
# JavaScript (ES6), ~~98~~ ~~94~~ ~~91~~ 83 bytes

```
n=>s=>{s=n<0?[...s].reverse().join``:s;while(!n)l(s);l(s.repeat(n<0?-n:n))}

```

-4, -5 bytes thanks to Arjun

-3 bytes thanks to Rick Hitchcock

Started out different than the Java answer, but quickly became very similar after golfing. Alert is infinite, but if you want it to look nice, switch to `console.log`. `l=alert;` and writing out `alert` are the same length, but if you switch to `console.log` it's shorter to redefine it.

# Answer
> 0 votes
# JavaScript (ES6), 79 bytes

```
 f=(n,s)=>n<0?f(-n,[...s].reverse().join``):(alert(!n?s:s.repeat(n)),!n&&f(n,s))

```

**Snippet:**

```
f=(n,s)=>n<0?f(-n,[...s].reverse().join``):(alert(!n?s:s.repeat(n)),!n&&f(n,s))

f(5, "hello world")
//f(0, "PPCG")  //uncomment this at your peril!!!
f(-2, "truThY")
f(2000, "o")
```

# Answer
> 0 votes
# Java (OpenJDK 8), 137 bytes

```
void f(String[] a){for(long n=Long.valueOf(a[0]),i=0;n==0|i++<Math.abs(n);)System.out.print(n<0?new StringBuilder(a[1]).reverse():a[1]);}

```

Try it online!

# Answer
> 0 votes
## QBIC, 36 bytes

Lot ging on here, and QBIC/QBasic just doesn't have the syntax to deal with such conditions elegantly.

```
~:<0|;=_fA}[abs(a)|Z=Z+A]~a|_X}{?A';

```

Explanation:

```
~:<0|       IF cmd line arg 'a' is negative
  ;=_fA         Make cmd line arg A$ into its reverse
}           Close the IF (this eliminates the need for a | fuction terminator on _f)
[abs(a)|    FOR b = 1 to (abs(a) (hammering out negatives)
  Z=Z+A         Add A$ to Z$ (on exit, Z$ is printed explicitly)
]           NEXT
~a|_X       IF a is non-zero, terminate the program
}           END IF
{?A';       If we're here, just start a DO-loop and keep on printing the input.

```

# Answer
> 0 votes
# str, 30 bytes

```
I#Lbd0<[_u_][d0='e'u#?]#?xo;db

```

Try it online!

## Explanation

```
I#Lbd0<[_u_][d0='e'u#?]#?xo;db
...........................;      preamble
I                                 read number
 #L                               read rest of STDIN
   b                              buffer the STDIN
    d                             duplicate number
     0<[   ]           #?         if the number is less than zero
        _                         negate that number
         u_                       and reverse STDIN from buffer
            [         ]           otherwise
             d0='e  #?            if its 0, push the empty string
                  'u              otherwise, push the unbuffered STDIN untouched
                         x        repeat STDIN by the TOS
                          o       and output
                           ;..    main program (only activates when input = 0)
                            d     duplicate the implicitly unbuffered STDIN
                             b    and rebuffer it
                                  implicitly displayed

```

# Answer
> 0 votes
# C (gcc), ~~115~~ ~~112~~ ~~109~~ ~~107~~ 104 bytes

```
f(n,s,l,p,d)char*s;{d=n<0?-1:1;do for(l=1,p=0;p>=0;p+=l)s[p]?d==l&&putchar(s[p]):l--;while(!n||(n-=d));}

```

Try it online!

> Who said, we need `strlen`?

## C (gcc), 115 bytes (134 with `#include<string.h>` in front)

```
#include<string.h>
f(n,s)char*s;{int l=strlen(s),d=n<0?0:2,m=d--,p;do for(p=m?0:l-1;p!=(m?l:-1);p+=d)putchar(s[p]);while(!n||(n-=d));}

```

Try it online!

> Without `#include<string.h>` we get an implicit prototype for `strlen` that returns `int`, but `strlen` is `size_t` (at least nowadays, not perfectly sure about k&r or c89, but I believe, it returned `int` in the old days).
>
> The missing `#include <stdio.h>` isn't a problem, because due to integer promotion, the default prototype will be `int putchar(int)` which is exactly what we want.

# Answer
> 0 votes
# Retina, 49 bytes

```
/¶-/&V`^.+
/¶0/&//+>G0`
~`(.+)¶-*(\d+)
.-$2+>K`$1

```

Input format: takes in the string, followed by a newline, followed by the number.

Try it online!

**Explanation:**

```
/¶-/&V`^.+

```

The `/¶-/&` runs this line only if the number is negative. `V` is the reverse stage, and it reverses `^.+`, which matches the string (`.` matches every character apart from newlines).

```
/¶0/&//+>G0`

```

The `/¶0/&` runs this line only if the number is 0. `//+>` starts an infinite loop, which prints the working string after each iteration. `G0` takes the string and discards the number; it does this infinitely, printing every time.

```
~`...

```

This marks code that will generate a string; the program evaluates the string as Retina code after.

```
(.+)¶-*(\d+)
.-$2+>K`$1

```

`(.+)¶-*(\d+)` matches the whole string and puts the string in capturing group 1 and the number in capturing group 2. `.-$2+>K`\` `$1` generates the Retina code to be run: `.` turns implicit output off (otherwise the string would be printed n+1 times), `-$2+` sets a repeat loop that repeats for {capturing group 2} times. The minus at the beginning turns the number into a negative number, as this disables the convergence functionality in the loop, which would stop it after the 1st iteration. `>` sets this loop to print after each iteration. The rest of the code is just to print the string.

# Answer
> 0 votes
# Perl 6, 44 bytes

```
{[$^s.flip,$s,$s Zxx-$^n,Inf,$n][$n.sign+1]}

```

Try it online!

Anonymous code block that takes a number and a string and returns a (possibly infinite) list

# Answer
> 0 votes
# Pip, 16 bytes

```
TaOba<0?RbbX:ABa

```

Replit! Or, here's a 17-byte equivalent in Pip Classic: Try it online!

### Explanation

```
TaOba<0?RbbX:ABa
                  a and b are the two command-line arguments
Ta                Loop until a is truthy:
  Ob               Output b without a newline
                  If a=0, this loops infinitely; otherwise, it doesn't loop at all
    a<0?          If a is negative:
        Rb         b reversed
                  Else (if a is positive):
          b        b
           X:     Repeat that string this many times:
             ABa  Absolute value of a

```

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


# Question
Title: In as few bytes as possible in t-sql, return 100 rows containing the phrase 'Have a great Christmas'
In as few bytes as possible in t-sql, return 100 rows containing the phrase 'Have a great Christmas'

92 (I think) to beat :D

```
CREATE TABLE #(m char(99))
GO
INSERT # SELECT'Have a great Christmas'
GO 100
SELECT * FROM #

```

Previous best effort was:

```
WITH t(m,r)AS(SELECT'Have a great Christmas',1 UNION ALL SELECT m,r+1 FROM t WHERE r<100)SELECT m FROM t;

```

# Answer
> 4 votes
# SQL Server (tested on 2016) - 82 78 bytes

```
SELECT TOP 100*FROM STRING_SPLIT(REPLICATE('Have a great Christmas!',100),'!')

```

## SQL Server (tested on 2016) - 88 87 bytes (Old Solution)

```
WITH N(a)AS(SELECT'Have a great Christmas'UNION ALL SELECT*FROM N)SELECT TOP 100*FROM N

```

Of course, on a sql instance with existing objects, you can come up with some... hackier solutions.

For example, 58 bytes that are pretty darn likely to work:

```
SELECT TOP 100'Have a great Christmas'FROM sys.all_objects

```

# Answer
> 4 votes
# SQL Server 2016, ~~54~~ 53 bytes

*Edit: -1 byte thanks to @Kevin Cruijssen.*

```
select top 100'Have a great Christmas'from spt_values

```

Works in my instance of SQL Server 2016.

`spt_values` may be replaced with any system view/table of at least 100 rows.

Inspired by this tips answer.

---
Tags: code-golf, kolmogorov-complexity, tips, sql
---


title: Integer Complexity

text:
# Question
Title: Integer Complexity
Your task is to write a program that, on input n, outputs the *minimal expression* of each number 1 through n in order. The shortest program in bytes wins.

A minimal expression combines 1's with addition and multiplication to result in the given number, using as few 1's as possible. For example, `23` is expressed as `23=((1+1+1)(1+1)+1)(1+1+1)+1+1` with eleven ones, which is minimal.

Requirements:

1. The program must take as input a positive natural number n.
2. Output must be in this format: `20 = ((1+1+1)(1+1+1)+1)(1+1)`
3. Your output may not have needless parentheses, like `8 = ((1+1)(1+1))(1+1)`.
4. The multiplication sign `*` is optional.
5. Spaces are optional.
6. You don't have to output all the possible equations for given value: For example, you have the choice to output `4=1+1+1+1` or `4=(1+1)(1+1)`. You don't have to output both.
7. The shortest program (in bytes) in each language wins.

```
1=1
2=1+1
3=1+1+1
4=1+1+1+1
5=1+1+1+1+1
6=(1+1+1)(1+1)
7=(1+1+1)(1+1)+1
8=(1+1+1+1)(1+1)
9=(1+1+1)(1+1+1)
10=(1+1+1)(1+1+1)+1
11=(1+1+1)(1+1+1)+1+1
12=(1+1+1)(1+1)(1+1)
13=(1+1+1)(1+1)(1+1)+1
14=((1+1+1)(1+1)+1)(1+1)
15=(1+1+1+1+1)(1+1+1)
16=(1+1+1+1)(1+1)(1+1)
17=(1+1+1+1)(1+1)(1+1)+1
18=(1+1+1)(1+1+1)(1+1)
19=(1+1+1)(1+1+1)(1+1)+1
20=((1+1+1)(1+1+1)+1)(1+1)

```

Here are some more test cases: (remember, that other expressions with the same number of 1's are also allowed)

```
157=((1+1+1)(1+1)(1+1)+1)(1+1+1)(1+1)(1+1)+1

444=((1+1+1)(1+1+1)(1+1)(1+1)+1)(1+1+1)(1+1)(1+1)

1223=((1+1+1)(1+1+1)(1+1+1)(1+1+1)(1+1+1)+1)(1+1+1+1+1)+1+1+1

15535=((((1+1+1)(1+1+1)(1+1+1)(1+1+1)+1)((1+1+1)(1+1)+1)+1)(1+1+1)+1)(1+1+1)(1+1+1)+1

45197=((((1+1+1)(1+1)(1+1)(1+1)+1)(1+1+1+1+1)(1+1)+1)(1+1+1)(1+1)(1+1)+1)(1+1+1+1+1)(1+1+1)+1+1

```

Good Luck! \- The Turtle

# Answer
# Pyth, 60 bytes

```
LjWqeb\1b`()L?tbho/N\1++'tb"+1"m+y'/bdy'df!%bTr2b1VSQ++N\='N

```

Demonstration

The online compiler can reach 1223 before the time out, thanks to Pyth's automatic function memoization.

```
1223=((1+1+1)(1+1+1)(1+1+1)(1+1+1)(1+1+1)+1)(1+1+1+1+1)+1+1+1

```

In abbrieviated notaion,

```
1223=(3^5+1)*5+3

```

This uses a recursive function `'`, which calculates all possbile products and sums which could give the desired output, finds the shortest string with each final operation, then compares them by `1` count and returns the first one.

It uses a helper function, `y`, which parenthesizes an expression only if it needs to be parenthesized.

Offline, I am running the program with the input `15535`, and it is nearly complete. Results are printed incrementally, so it is easy to see the progress.

Final lines of the output:

```
15535=((((1+1+1)(1+1+1)(1+1+1)(1+1+1)+1)((1+1+1)(1+1)+1)+1)(1+1+1)+1)(1+1+1)(1+1+1)+1

real    7m8.430s
user    7m7.158s
sys 0m0.945s

```

In abbreviated notation,

```
15535=(((3^4+1)*(3*2+1)+1)*3+1)*3^2+1

```
> 10 votes

# Answer
# CJam, ~~105~~ ~~102~~ ~~98~~ 96 bytes

```
q~{)'=1$2,{:I{I1$-'+}%3/1>Imf'*+aImp!*+{)\{j}%\+}:F%{e_"+*"-:+}$0=}j2,{F)_'*={;{'(\')}%1}&*}jN}/

```

Try it online in the CJam interpreter.

### Test run

The online interpreter is too slow for the larger test cases. Even with the Java interpreter, the larger test cases will take a *long* time and require a significant amount of memory.

```
$ time cjam integer-complexity.cjam <<< 157
1=1
2=1+1
3=1+1+1
4=1+1+1+1
5=1+1+1+1+1
6=(1+1)(1+1+1)
7=1+(1+1)(1+1+1)
8=(1+1)(1+1)(1+1)
9=(1+1+1)(1+1+1)
10=1+(1+1+1)(1+1+1)
11=1+1+(1+1+1)(1+1+1)
12=(1+1)(1+1)(1+1+1)
13=1+(1+1)(1+1)(1+1+1)
14=(1+1)(1+(1+1)(1+1+1))
15=(1+1+1)(1+1+1+1+1)
16=(1+1)(1+1)(1+1)(1+1)
17=1+(1+1)(1+1)(1+1)(1+1)
18=(1+1)(1+1+1)(1+1+1)
19=1+(1+1)(1+1+1)(1+1+1)
20=(1+1)(1+1)(1+1+1+1+1)
21=(1+1+1)(1+(1+1)(1+1+1))
22=1+(1+1+1)(1+(1+1)(1+1+1))
23=1+1+(1+1+1)(1+(1+1)(1+1+1))
24=(1+1)(1+1)(1+1)(1+1+1)
25=1+(1+1)(1+1)(1+1)(1+1+1)
26=(1+1)(1+(1+1)(1+1)(1+1+1))
27=(1+1+1)(1+1+1)(1+1+1)
28=1+(1+1+1)(1+1+1)(1+1+1)
29=1+1+(1+1+1)(1+1+1)(1+1+1)
30=(1+1)(1+1+1)(1+1+1+1+1)
31=1+(1+1)(1+1+1)(1+1+1+1+1)
32=(1+1)(1+1)(1+1)(1+1)(1+1)
33=1+(1+1)(1+1)(1+1)(1+1)(1+1)
34=(1+1)(1+(1+1)(1+1)(1+1)(1+1))
35=(1+1+1+1+1)(1+(1+1)(1+1+1))
36=(1+1)(1+1)(1+1+1)(1+1+1)
37=1+(1+1)(1+1)(1+1+1)(1+1+1)
38=(1+1)(1+(1+1)(1+1+1)(1+1+1))
39=(1+1+1)(1+(1+1)(1+1)(1+1+1))
40=(1+1)(1+1)(1+1)(1+1+1+1+1)
41=1+(1+1)(1+1)(1+1)(1+1+1+1+1)
42=(1+1)(1+1+1)(1+(1+1)(1+1+1))
43=1+(1+1)(1+1+1)(1+(1+1)(1+1+1))
44=(1+1)(1+1)(1+1+(1+1+1)(1+1+1))
45=(1+1+1)(1+1+1)(1+1+1+1+1)
46=1+(1+1+1)(1+1+1)(1+1+1+1+1)
47=1+1+(1+1+1)(1+1+1)(1+1+1+1+1)
48=(1+1)(1+1)(1+1)(1+1)(1+1+1)
49=1+(1+1)(1+1)(1+1)(1+1)(1+1+1)
50=(1+1)(1+1+1+1+1)(1+1+1+1+1)
51=(1+1+1)(1+(1+1)(1+1)(1+1)(1+1))
52=(1+1)(1+1)(1+(1+1)(1+1)(1+1+1))
53=1+(1+1)(1+1)(1+(1+1)(1+1)(1+1+1))
54=(1+1)(1+1+1)(1+1+1)(1+1+1)
55=1+(1+1)(1+1+1)(1+1+1)(1+1+1)
56=(1+1)(1+1)(1+1)(1+(1+1)(1+1+1))
57=(1+1+1)(1+(1+1)(1+1+1)(1+1+1))
58=1+(1+1+1)(1+(1+1)(1+1+1)(1+1+1))
59=1+1+(1+1+1)(1+(1+1)(1+1+1)(1+1+1))
60=(1+1)(1+1)(1+1+1)(1+1+1+1+1)
61=1+(1+1)(1+1)(1+1+1)(1+1+1+1+1)
62=(1+1)(1+(1+1)(1+1+1)(1+1+1+1+1))
63=(1+1+1)(1+1+1)(1+(1+1)(1+1+1))
64=(1+1)(1+1)(1+1)(1+1)(1+1)(1+1)
65=1+(1+1)(1+1)(1+1)(1+1)(1+1)(1+1)
66=(1+1)(1+1+1)(1+1+(1+1+1)(1+1+1))
67=1+(1+1)(1+1+1)(1+1+(1+1+1)(1+1+1))
68=(1+1)(1+1)(1+(1+1)(1+1)(1+1)(1+1))
69=1+(1+1)(1+1)(1+(1+1)(1+1)(1+1)(1+1))
70=(1+1)(1+1+1+1+1)(1+(1+1)(1+1+1))
71=1+(1+1)(1+1+1+1+1)(1+(1+1)(1+1+1))
72=(1+1)(1+1)(1+1)(1+1+1)(1+1+1)
73=1+(1+1)(1+1)(1+1)(1+1+1)(1+1+1)
74=(1+1)(1+(1+1)(1+1)(1+1+1)(1+1+1))
75=(1+1+1)(1+1+1+1+1)(1+1+1+1+1)
76=(1+1)(1+1)(1+(1+1)(1+1+1)(1+1+1))
77=1+(1+1)(1+1)(1+(1+1)(1+1+1)(1+1+1))
78=(1+1)(1+1+1)(1+(1+1)(1+1)(1+1+1))
79=1+(1+1)(1+1+1)(1+(1+1)(1+1)(1+1+1))
80=(1+1)(1+1)(1+1)(1+1)(1+1+1+1+1)
81=(1+1+1)(1+1+1)(1+1+1)(1+1+1)
82=1+(1+1+1)(1+1+1)(1+1+1)(1+1+1)
83=1+1+(1+1+1)(1+1+1)(1+1+1)(1+1+1)
84=(1+1)(1+1)(1+1+1)(1+(1+1)(1+1+1))
85=1+(1+1)(1+1)(1+1+1)(1+(1+1)(1+1+1))
86=(1+1)(1+(1+1)(1+1+1)(1+(1+1)(1+1+1)))
87=(1+1+1)(1+1+(1+1+1)(1+1+1)(1+1+1))
88=(1+1)(1+1)(1+1)(1+1+(1+1+1)(1+1+1))
89=1+(1+1)(1+1)(1+1)(1+1+(1+1+1)(1+1+1))
90=(1+1)(1+1+1)(1+1+1)(1+1+1+1+1)
91=1+(1+1)(1+1+1)(1+1+1)(1+1+1+1+1)
92=1+1+(1+1)(1+1+1)(1+1+1)(1+1+1+1+1)
93=(1+1+1)(1+(1+1)(1+1+1)(1+1+1+1+1))
94=1+(1+1+1)(1+(1+1)(1+1+1)(1+1+1+1+1))
95=(1+1+1+1+1)(1+(1+1)(1+1+1)(1+1+1))
96=(1+1)(1+1)(1+1)(1+1)(1+1)(1+1+1)
97=1+(1+1)(1+1)(1+1)(1+1)(1+1)(1+1+1)
98=(1+1)(1+(1+1)(1+1+1))(1+(1+1)(1+1+1))
99=(1+1+1)(1+1+1)(1+1+(1+1+1)(1+1+1))
100=(1+1)(1+1)(1+1+1+1+1)(1+1+1+1+1)
101=1+(1+1)(1+1)(1+1+1+1+1)(1+1+1+1+1)
102=(1+1)(1+1+1)(1+(1+1)(1+1)(1+1)(1+1))
103=1+(1+1)(1+1+1)(1+(1+1)(1+1)(1+1)(1+1))
104=(1+1)(1+1)(1+1)(1+(1+1)(1+1)(1+1+1))
105=(1+1+1)(1+1+1+1+1)(1+(1+1)(1+1+1))
106=1+(1+1+1)(1+1+1+1+1)(1+(1+1)(1+1+1))
107=1+1+(1+1+1)(1+1+1+1+1)(1+(1+1)(1+1+1))
108=(1+1)(1+1)(1+1+1)(1+1+1)(1+1+1)
109=1+(1+1)(1+1)(1+1+1)(1+1+1)(1+1+1)
110=1+1+(1+1)(1+1)(1+1+1)(1+1+1)(1+1+1)
111=(1+1+1)(1+(1+1)(1+1)(1+1+1)(1+1+1))
112=(1+1)(1+1)(1+1)(1+1)(1+(1+1)(1+1+1))
113=1+(1+1)(1+1)(1+1)(1+1)(1+(1+1)(1+1+1))
114=(1+1)(1+1+1)(1+(1+1)(1+1+1)(1+1+1))
115=1+(1+1)(1+1+1)(1+(1+1)(1+1+1)(1+1+1))
116=(1+1)(1+1)(1+1+(1+1+1)(1+1+1)(1+1+1))
117=(1+1+1)(1+1+1)(1+(1+1)(1+1)(1+1+1))
118=1+(1+1+1)(1+1+1)(1+(1+1)(1+1)(1+1+1))
119=(1+(1+1)(1+1+1))(1+(1+1)(1+1)(1+1)(1+1))
120=(1+1)(1+1)(1+1)(1+1+1)(1+1+1+1+1)
121=1+(1+1)(1+1)(1+1)(1+1+1)(1+1+1+1+1)
122=(1+1)(1+(1+1)(1+1)(1+1+1)(1+1+1+1+1))
123=(1+1+1)(1+(1+1)(1+1)(1+1)(1+1+1+1+1))
124=(1+1)(1+1)(1+(1+1)(1+1+1)(1+1+1+1+1))
125=(1+1+1+1+1)(1+1+1+1+1)(1+1+1+1+1)
126=(1+1)(1+1+1)(1+1+1)(1+(1+1)(1+1+1))
127=1+(1+1)(1+1+1)(1+1+1)(1+(1+1)(1+1+1))
128=(1+1)(1+1)(1+1)(1+1)(1+1)(1+1)(1+1)
129=1+(1+1)(1+1)(1+1)(1+1)(1+1)(1+1)(1+1)
130=(1+1)(1+1+1+1+1)(1+(1+1)(1+1)(1+1+1))
131=1+(1+1)(1+1+1+1+1)(1+(1+1)(1+1)(1+1+1))
132=(1+1)(1+1)(1+1+1)(1+1+(1+1+1)(1+1+1))
133=(1+(1+1)(1+1+1))(1+(1+1)(1+1+1)(1+1+1))
134=1+(1+(1+1)(1+1+1))(1+(1+1)(1+1+1)(1+1+1))
135=(1+1+1)(1+1+1)(1+1+1)(1+1+1+1+1)
136=1+(1+1+1)(1+1+1)(1+1+1)(1+1+1+1+1)
137=1+1+(1+1+1)(1+1+1)(1+1+1)(1+1+1+1+1)
138=(1+1)(1+1+1)(1+1+(1+1+1)(1+(1+1)(1+1+1)))
139=1+(1+1)(1+1+1)(1+1+(1+1+1)(1+(1+1)(1+1+1)))
140=(1+1)(1+1)(1+1+1+1+1)(1+(1+1)(1+1+1))
141=1+(1+1)(1+1)(1+1+1+1+1)(1+(1+1)(1+1+1))
142=(1+1)(1+(1+1)(1+1+1+1+1)(1+(1+1)(1+1+1)))
143=(1+1+(1+1+1)(1+1+1))(1+(1+1)(1+1)(1+1+1))
144=(1+1)(1+1)(1+1)(1+1)(1+1+1)(1+1+1)
145=1+(1+1)(1+1)(1+1)(1+1)(1+1+1)(1+1+1)
146=(1+1)(1+(1+1)(1+1)(1+1)(1+1+1)(1+1+1))
147=(1+1+1)(1+(1+1)(1+1+1))(1+(1+1)(1+1+1))
148=(1+1)(1+1)(1+(1+1)(1+1)(1+1+1)(1+1+1))
149=1+(1+1)(1+1)(1+(1+1)(1+1)(1+1+1)(1+1+1))
150=(1+1)(1+1+1)(1+1+1+1+1)(1+1+1+1+1)
151=1+(1+1)(1+1+1)(1+1+1+1+1)(1+1+1+1+1)
152=(1+1)(1+1)(1+1)(1+(1+1)(1+1+1)(1+1+1))
153=(1+1+1)(1+1+1)(1+(1+1)(1+1)(1+1)(1+1))
154=1+(1+1+1)(1+1+1)(1+(1+1)(1+1)(1+1)(1+1))
155=(1+1+1+1+1)(1+(1+1)(1+1+1)(1+1+1+1+1))
156=(1+1)(1+1)(1+1+1)(1+(1+1)(1+1)(1+1+1))
157=1+(1+1)(1+1)(1+1+1)(1+(1+1)(1+1)(1+1+1))

real    0m3.896s
user    0m4.892s
sys     0m0.066s

```

Given enough time, it would produce these solutions for the next test cases:

```
444=(1+1)(1+1)(1+1+1)(1+(1+1)(1+1)(1+1+1)(1+1+1))
1223=1+1+(1+1+1)(1+1+(1+1+1)(1+1+1))(1+(1+1)(1+1)(1+1+1)(1+1+1))

```
> 7 votes

# Answer
# Julia, 229 bytes

```
n->(F=i->K[i]>0?E[i]:"("E[i]")";C=[1;3:n+1];K=0C;E=fill("1",n);for s=1:n for i=1:s÷2 (D=C[i]+C[s-i])<C[s]?(C[s]=D;E[s]=E[i]"+"E[s-i];K[s]=0):s%i>0||(D=C[i]+C[j=s÷i])<C[s]&&(C[s]=D;E[s]=F(i)F(j);K[s]=1)end;println("$s="E[s])end)

```

This is actually pretty fast. Assigning the function to `f` and running `@time f(15535)` gives the output (last two lines only)

```
15535=1+(1+1+1)(1+1+1)(1+(1+1+1)(1+(1+(1+1)(1+1+1))(1+(1+1+1)(1+1+1)(1+1+1)(1+1+1))))
32.211583 seconds (263.30 M allocations: 4.839 GB, 4.81% gc time)

```

and for `@time f(45197)`, it gives

```
45197=1+1+(1+1+1)(1+1+1+1+1)(1+(1+1)(1+1)(1+1+1)(1+(1+1)(1+1+1+1+1)(1+(1+1)(1+1)(1+1)(1+1+1))))
289.749564 seconds (2.42 G allocations: 43.660 GB, 4.91% gc time)

```

So, what's the code doing? Simple - `C` holds the current one-`C`ount for the number, `K` is an indicator array keeping track of whether the expression is, fundamentally, a sum or a product, for the purposes of dealing with bracketing, and `E` holds the `E`xpression itself. Working its way up from `s=1` through to `n`, the code searches for the minimal representation of number `s` in terms of lower values, by looking for either a sum or a product. If it's a product, then it checks the two components and puts brackets around them if they're sums. That check is done in function `F`, to save bytes (because it has to be done twice, for the two factors).
> 4 votes

# Answer
# Haskell, 208 bytes

```
import Data.List;f n=mapM putStrLn[show x++"="++m x|x<-[1..n]];m 1="1";m n=head$sortOn(filter(>'0'))[let b=m$div n x;q=last b>'0'in concat["(",m x,")",['('|q],b,[')'|q]]|x<-[2..n-1],mod n x<1]++[m(n-1)++"+1"]

```

Try it online!
> 0 votes

---
Tags: code-golf, math, arithmetic
---


# Question
Title: AoCG2021 Day 4: Infinite Elves and infinite houses 2
Part of **Advent of Code Golf 2021** event. See the linked meta post for details.

Related to AoC2015 Day 20, Part 1.

*Here's why I'm posting instead of Bubbler and why not emanresuA*

---

To keep the Elves busy, Santa has them deliver some presents by hand, door-to-door. He sends them down a street with infinite houses numbered sequentially: 1, 2, 3, 4, 5, and so on.

Each Elf is assigned a number, too, and delivers presents to houses based on that number. Instead of giving out presents at fixed intervals, Santa decides to give them out in longer and longer intervals because apparently he's short of supplies right now. Ignore the fact that the total number of presents delivered is the same after all :P

* The first Elf (number 1) delivers presents to the houses numbered 1, 1+2, 1+2+3, 1+2+3+4, 1+2+3+4+5, ... (1, 3, 6, 10, 15, ...)
* The second Elf (number 2) delivers presents to the houses numbered 2, 2+3, 2+3+4, 2+3+4+5, 2+3+4+5+6, ... (2, 5, 9, 14, 20, ...)
* Elf number 3 delivers presents to houses 3, 3+4, 3+4+5, ... (3, 7, 12, 18, 25, ...)
* ...

There are infinitely many Elves, numbered starting with 1. Each Elf delivers exactly 1 present at each house.

So, the first nine houses on the street end up like this:

* House 1 gets 1 present (by Elf 1).
* House 2 gets 1 present (by Elf 2).
* House 3 gets 2 presents (by Elves 1 and 3).
* House 4 gets 1 present (by Elf 4).
* House 5 gets 2 presents (by Elves 2 and 5).
* House 6 gets 2 presents (by Elves 1 and 6).
* House 7 gets 2 presents (by Elves 3 and 7).
* House 8 gets 1 present (by Elf 8).
* House 9 gets 3 presents (by Elves 2 (2+3+4), 4 (4+5), and 9).

So the lowest-numbered house that gets at least 3 presents is House 9.

Given a positive number `n`, what is the lowest house number that will get at least `n` presents?

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
n -> answer
1 -> 1
2 -> 3
3 -> 9
4 -> 15
5 -> 45
6 -> 45
7 -> 105
8 -> 105
9 -> 225
10 -> 315
12 -> 315
17 -> 1575
25 -> 10395

```

# Answer
> 18 votes
# Pari/GP, 32 bytes

```
n->i=1;while(numdiv(i)<n,i+=2);i

```

Try it online!

House \\$i\\$ gets a present from elf \\$j\\$ \\$\iff\\$ \\$i=\frac{k(j+k-1)}{2}\\$ for some \\$k \ge 0\\$ \\$\iff\\$ \\$k=\frac{\sqrt{(2j-1)^2+8i}-2j+1}{2}\\$ for some \\$k\\$ \\$\iff\\$ \\$(2j-1)^2+8i=l^2\\$ for some \\$l\\$ \\$\iff\\$ \\$8i=(l+2j-1)(l-2j+1)\\$ for some \\$l\\$ \\$\iff\\$ \\$m-8i/m=4j-2\\$ for some divisor \\$m\\$ of \\$8i\\$.

So house \\$i\\$ gets \\$n\\$ presents \\$\iff\\$ \\$8i\\$ has \\$n\\$ divisors \\$d\\$ such that \\$d\equiv 2 \pmod{4}\\$ \\$\iff\\$ \\$i\\$ has \\$n\\$ odd divisors.

But \\$i\\$ and \\$2i\\$ has exactly the same number of odd divisors. So we only need to consider the odd numbers, whose divisors are all odd.

# Answer
> 10 votes
# JavaScript (ES7), 65 bytes

```
f=(n,k)=>(g=n=>n&&!((4*n*--n+8*k+1)**.5%1)+g(n))(k)>=n?k:f(n,-~k)

```

Try it online!

### How?

The formula giving the \\$x\\$-th house visited by Elf number \\$n\\$ is:

$$H\_n(x) = \frac{x(x+2n-1)}{2}$$

We want to know whether Elf number \\$n\\$ is going to visit some house \\$k\\$, i.e. if there's some \\$x\>0\\$ such that \\$H\_n(x)=k\\$. It means that we have to check if the following quadratic equation has a positive integer solution:

$$\frac{1}{2}x^2+\left(n-\frac{1}{2}\right)x-k=0$$

The determinant is:

$$\Delta = \left(n-\frac{1}{2}\right)^2+2k=n^2-n+2k+\frac{1}{4}$$

Leading to:

$$4\Delta = 4n^2-4n+8k+1 = 4n(n-1)+8k+1$$ $$2\sqrt{\Delta} = \sqrt{4n(n-1)+8k+1}$$

Leading to a unique positive value of \\$x\\$:

$$x=\frac{\sqrt{\Delta}+1}{2}-n$$

But the only thing we're interested in is to know whether this \\$x\\$ is an integer. So we just test whether \\$\sqrt{4n(n-1)+8k+1}\\$ is an integer (which — if it is — is always odd).

Hence the JavaScript test:

```
!((4 * n * --n + 8 * k + 1) ** 0.5 % 1)

```

---

# JavaScript (ES6), 57 bytes

This one is a port of alephalpha's great method.

```
f=(n,i=1)=>eval("for(d=n,k=i;k;)d-=i%k--<1")>0?f(n,i+2):i

```

Try it online!

# Answer
> 6 votes
# 05AB1E, 9 bytes

Another port of alephalpha's approach.

```
∞·<.ΔÑg›_

```

Try it online!

A direct brute force approach is a byte longer:

```
∞.ΔLŒOy¢›_

```

Try it online!

```
∞           -- infinite list of positive integers
 ·<         -- double and decrement each; this yields the odd integers
   .Δ       -- find the first value that satisfies:
     Ñg     --   the number of divisors ...
       ›_   --   ... is not less than the input

∞.Δ         -- find the first positive integer y that satisfies:
   L        --   range from 1 to y
    ŒO      --   the sums of each contiguous sublist
            --   these are all of the form sum(a..b) for 1<=a<b<=y
      y¢    --   count the occurrences of y in the sums
        ›_  --   is this not less than the input?

```

# Answer
> 6 votes
# , 42 bytes

Or **\>=4.1, 35 bytes** by replacing the word `function` with `\`.

```
function(n){while(sum(!T%%1:T)<n)T=T+2;+T}

```

Try it online!

Another port of @alephalpha's solution.

# Answer
> 5 votes
# Husk, ~~10~~ ~~9~~ 8 bytes

*Edit: -2 bytes thanks to hint from ovs*

```
ḟȯ≥⁰LḊİ1

```

Try it online!

An alternative Husk approach to rues' answer, here porting alephalpha's method.

# Answer
> 5 votes
# 05AB1E, 25 bytes

```
[N.µxtExNNn-+N·%>½}¾¹@i,q

```

Try it here!

**Decomposition:**

```
func(n) - Number of presents for a given house 'n'
xt                          # s_max = sqrt(2n)
  E           }             # for s in 1..s_max
   xNNn-+N·                 # n, 2n+s-s^2, 2s
           %>               # if 2n-s^2+s % 2s = 0
             ½              # increment present counter
               ¾            # return present counter

main
[                           # loop n=0..infinity
 N                          # push house number to stack
  .µ                        # reset present counter to zero
    xtExNNn-+N·%>½}¾        # func(n)
                    ¹@      # if func(n) >= p:
                      i,q   # print N, quit

```

**Explanation:**

I wanted to find a mathematical approach rather than a computational one, and I'm decently pleased with what I found. Found through very unscientific means, but works for all numbers I've tested.

Making a scatter plot between elf number \\$r\\$ and house number \\$h\\$ reveals some nice patterns. Distinct straight lines are formed, which I have named 'series'. Where these series have integer pairs \\$(r,h)\\$, a house receives one present. An equation was formed to define these series by number: $$ n = sr + \frac{s^2-s}{2} $$ Solving for \\$r\\$ gives: $$ r = \frac{2n-s^2+s}{2s} $$ Integer solutions for \\$r\\$ mean that elf \\$r\\$ visited house \\$n\\$ on series \\$s\\$. $$ (2n-s^2+s) \equiv 0 \pmod {2s} $$ means a present was left. All that remains is to iterate over all series for a house to count a number of presents. A maximum series number is defined: $$ s\_{max}= \lfloor \sqrt{2n} \rfloor $$ derived approximately from the h-intercept of each series being $$ r = \frac{s(s+1)}{2} $$ This ensures that \\$r \geq 1\\$. Iterate over series \\$1\\$ though \\$\sqrt{2n}\\$ for each house to determine number of presents. Iterate over houses with this function until finding one with sufficient presents!

# Answer
> 4 votes
# Charcoal, 45 bytes

```
Ｎθ≔⁰ηＷ‹№υηθ«≦⊕η≔⟦⟧υＦη«≔⁰ζＷ‹ζη«≦⊕κ≧⁺κζ»⊞υζ»»Ｉη

```

Try it online! Link is to verbose version of code. Explanation: Brute force because I'm too tired to work out a formula.

```
Ｎθ

```

Input `n`.

```
≔⁰η

```

Start at house `0`.

```
Ｗ‹№υηθ«

```

Repeat until `n` visits have been found.

```
≦⊕η

```

Try the next house.

```
≔⟦⟧υ

```

Start building up the list of houses visited by the elves.

```
Ｆη«

```

Loop over enough elves so that the last elf visits the house. (Note that these elves are 0-indexed.)

```
≔⁰ζ

```

Start at house `0`.

```
Ｗ‹ζη«

```

Repeat until the current house has been reached or passed.

```
≦⊕κ

```

Increase the gap between houses.

```
≧⁺κζ

```

Visit the next house.

```
»⊞υζ

```

Save the house the elf ended up visiting.

```
»»Ｉη

```

Output the found house.

Porting @alephalpha's method takes 22 bytes:

```
Ｎθ≔¹ηＷ‹ＬΦη¬﹪η⊕κθ≧⁺²ηＩη

```

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

```
Ｎθ

```

Input `n`.

```
≔¹η

```

Start at house `1`.

```
Ｗ‹ＬΦη¬﹪η⊕κθ

```

While the current house has fewer than `n` divisors (which must all be odd)...

```
≧⁺²η

```

... visit the next house but one.

```
Ｉη

```

Output the found house.

# Answer
> 4 votes
# Rust, 65 64 bytes

```
|n|{let mut i=1;while(1..=i).filter(|j|i%j<1).count()<n{i+=2};i}

```

Try it online!

* -1 byte by using `<1` instead of `==0` (thanks @Kevin Cruijssen)

# Answer
> 3 votes
# Wolfram Language (Mathematica), 52 32 bytes

```
1//.i_/;0~DivisorSigma~i<#:>i+2&

```

Try it online!

*-20 bytes thanks to att! Also thanks to ovs.*

Based off alephaleph's excellent insight, and probably not a great Wolfram golf but I couldn't resist those builtins. I'll look forward to att setting me straight.

# Answer
> 3 votes
# Python 3, 62 bytes

```
f=lambda n,v=1:v*(sum(v%-~u<1for u in range(v))>=n)or f(n,v+2)

```

Try it online!

---

# Python 3, 76 bytes

```
lambda n:next(v for v in range(3**n)if sum(v%u<1for u in range(1,v+1,2))>=n)

```

Try it online!

# Answer
> 3 votes
# Husk, ~~14~~ 12 bytes

Fixed a bug and saved 3 bytes thanks to Dominic Van Essen!

```
ḟo≥⁰S#ȯṁ∫ṫḣN

```

Try it online!

# Answer
> 3 votes
# Ruby, 66 bytes

```
->n,*r{w=[];1.step.find{|x|w+=r=[0,*r].map{|y|y+x};w.count(x)>=n}}

```

Try it online!

# Answer
> 2 votes
# Japt, 11 bytes

```
@>Xâ Ê*Xu}f

```

Try it

Port of @alephalpha answer.

# Answer
> 2 votes
# TI-Basic, 32 bytes

```
Input N
1
While N>sum(seq(not(IfPart(Ans/I)),I,1,Ans
Ans+2
End
Ans

```

Port of alephalpha's solution. Output is stored in `Ans` and displayed.

# Answer
> 1 votes
# Python3, 162 bytes:

```
r=range
q=lambda h,n,l:any(i==h for i in l if i and l.count(i)>=n)
f=lambda n,h=1:h if(v:=q(h,n,[sum(r(x,y+1))for x in r(1, h+1)for y in r(1, h+1)]))else f(n,h+1)

```

A basic brute-force approach.

Try it online.

# Answer
> 1 votes
# Java, 73 bytes

```
n->{int r=1,c=1,j;for(;c<n;)for(r+=2,c=j=1;j<r;)if(r%j++<1)c++;return r;}

```

Port of *@alephalpha*'s Pari/GP answer.

Try it online.

**Explanation:**

```
n->{              // Method with integer as both parameter and return-type
  int r=1,        //  Result-integer `r`, starting at 1
      c=1,        //  Count-integer, starting at 1
      j;          //  Temp integer, uninitialized
  for(;c<n;)      //  Loop as long as the count is smaller than the input:
    for(r+=2,     //   Increase `r` by 2
        c=j=1;    //   Reset the count to 1,
        j<r;)     //   Loop `j` in the range [1,r):
      if(r%j++<1) //    If `r` is divisible by `j`:
                  //    (and increase `j` by 1 afterwards with `j++`)
        c++;      //     Increase the count by 1
  return r;}      // After the nested loops: return the result

```

# Answer
> 1 votes
# TypeScript Types, 302 bytes

```
//@ts-ignore
type a<N,M=[]>=N extends M["length"]?M:a<N,[...M,0]>;type b<N,E,C,M=[]>=M extends N?[...C,0]:M extends[...N,...0[]]?C:b<N,[...E,0],C,[...M,...E]>;type c<N,M=[0],C=[0]>=N extends M?C:c<N,[...M,0],b<N,M,C>>;type d<N,M=[0]>=c<M>extends[...N,...0[]]?M["length"]:d<N,[...M,0]>;type M<X>=d<a<X>>

```

Try It Online!

## Ungolfed / Explanation

```
type NumToTuple<N,M=[]> = N extends M["length"] ? M : NumToTuple<N,[...M,0]>
type CheckElf<HouseNum, NumToAdd, PresentCount, Sum=[]> =
  Sum extends HouseNum
    // If Sum == HouseNum, return ElfCount + 1
    ? [...PresentCount, 0]
    : Sum extends [...HouseNum, ...0[]]
      // Otherwise, if Sum >= HouseNum, return ElfCount
      ? PresentCount
      // Othwerise, add NumToAdd to Sum, increase NumToAdd, and recurse
      : CheckElf<HouseNum, [...NumToAdd, 0], PresentCount, [...Sum, ...NumToAdd]>
type CountPresents<HouseNum, ElfNum=[0], PresentCount=[0]> =
  HouseNum extends ElfNum
    // If HouseNum == ElfNum, return PresentCount
    ? PresentCount
    // Otherwise, check this elf, add one to ElfNum, and recurse
    : CountPresents<HouseNum, [...ElfNum,0], CheckElf<HouseNum, ElfNum, PresentCount>>
type FindHouse<PresentMin, HouseNum=[0]> =
  CountPresents<HouseNum> extends [...PresentMin,...0[]]
    // If the number of presents at this house is >= the minumum, return this house number
    ? HouseNum["length"]
    // Otherwise, check the next house number
    : FindHouse<PresentMin,[...HouseNum,0]>
type Main<X> = FindHouse<NumToTuple<X>>

```

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


title: Excludivisible numbers

text:
# Question
Title: Excludivisible numbers
Given an integer `N`, output the `N`th positive number `K` with the following property in decimal base:

For each digit `I` at position `P` of `K`, the number formed from `K` by removing the `P`th digit (i.e. `I`) is divisible by `I`.

### Example and remarks

`324` is such a number:

* `3` divides `24`
* `2` divides `34`
* `4` divides `32`

**Note 1:** we assume that the empty number is divisible by anything, like `0`. Therefore `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8` and `9` are valid.

**Note 2:** `K` cannot contain the digit `0`, since you cannot divide by `0`.

### Inputs and outputs

* You may take the input as a function argument, through `STDIN`, etc.
* You may return the output from a function, through `STDOUT`, etc.
* You may index those numbers starting from `0` (in which case `N >= 0`) or from `1` (in which case `N > 0`), whichever suits you more.

### Test cases

Those examples are indexed from `0`, so if you indexed from `1`, then add `1` to the numbers in the `N` column.

```
N    Output
0    1
4    5
8    9
15   77
16   88
23   155
42   742
47   1113
121  4244
144  6888
164  9999

```

### Scoring

This is , so the shortest answer in bytes wins.

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

```
DLR©œ^€®ịDḌḍ@DPȧµ#Ṫ

```

Input is 1-indexed. Try it online!

### How it works

```
DLR©œ^€®ịDḌḍ@DPȧµ#Ṫ  Main link. No arguments.

                µ    Convert the chain to the left into a link.
                 #   Read n from STDIN and execute the link to the left for
                     k = 0, 1, 2, ... until n value return a truthy value.
D                      Convert D to base 10 (digit array).
 LR                    Construct the range from 1 to the length of the digit array.
   ©                   Copy the range to the register.
       ®               Yield the value of the register.
    œ^€                Take the multiset difference of each element of the range
                       and the range itself.
        ịD             Index into the digit array.
          Ḍ            Convert each list of digits to integer.
                       This yields all numbers with one suppressed digit.
           ḍ@D         Test each of these numbers for divisibility by the
                       suppressed digit from the digit array.
              P        Take the product of the resulting Booleans.
               ȧ       Logical AND with k (k would return 1).
                  Ṫ  Tail; extract the last (nth) element.

```
> 4 votes

# Answer
# Pyth, 20

```
e.f!s.e.x%s.D`Zksb1`

```

Try it here or run the Test Suite

N is 1-indexed for this answer.

Uses largely the same logic as my python script. Notable differences are using `.D` to delete the digit from the string during the test and using exception handling to deal with zero digits.
> 4 votes

# Answer
# Pyth, 26 bytes

```
e.f&!/J`Z\0!s%VsM.DLJUJjZT

```

Test suite.

```
e.f&!/J`Z\0!s%VsM.DLJUJjZT
e.f                          The n-th number (Z) where:
    !/J`Z\0                      Z does not contain "0"
   &                             and
           !s                    the following does not contain zero:
               sM.DLJUJ              generate the set of the digits removed
                       jZT           all the digits
             %V                      modulus in parallel
                                     if Z is 324,
                                     the first set would be [24,34,32]
                                     the second set would be [3,2,4]
                                     the third set would be [24%3, 34%2, 32%4]

```
> 2 votes

# Answer
## JavaScript (ES6), ~~82~~ ~~78~~ 76 bytes

```
f=(n,k=0)=>n?f(n-!eval(/0/.test(++k)+`${k}`.replace(/./g,"|'$`$''%$&")),k):k

```

Input is 1-indexed. Works by building up a string of the form `false|'24'%3|'34'%2|'32'%4` and evaluating it. Strings are used because they are still syntactically valid in the single-digit case.

The recursion limits this to about n=119. Iterative version for ~~88~~ ~~84~~ 82 bytes:

```
n=>{for(k=0;n;n-=!eval(/0/.test(++k)+`${k}`.replace(/./g,"|'$`$''%$&")));return l}

```

Edit: Saved 2 bytes thanks to @Dennis♦.
> 2 votes

# Answer
# Python 2, 93 bytes

```
n=input();r=0
while n:r+=1;k=t=1;exec't&=(r/k/10*k+r%k)%(r/k%10or r)<1;k*=10;'*r;n-=t
print r

```

*Very* inefficient. Input is 1-indexed. Test it on Ideone.

### Alternate version, 100 bytes

The above code performs roughly **10x** divisibility tests where only **x** are required. At the cost of only **7 extra bytes**, efficiency can be improved dramatically, either by replacing `*r` with `*len(`r`)` or by refactoring the code as follows.

```
n=input();r=0
while n:
 r+=1;k=t=1
 for _ in`r`:t&=(r/k/10*k+r%k)%(r/k%10or r)<1;k*=10
 n-=t
print r

```

This handles all test cases with ease, even on Ideone.
> 2 votes

# Answer
# Ruby, 90

```
f=->n,s=?0{0while s.next![?0]||s[1]&&/t/=~s.gsub(/\d/){eval"#$`#$'%#$&>0"};n<1?s:f[n-1,s]}

```

Similar approach to Neil's Javascript answer, but significantly longer due to a lack of implicit type conversion (except that booleans do get converted into strings by `gsub`, which is nice).
> 2 votes

# Answer
# Ruby, 109 bytes

```
->n{i=s=1;n.times{s=?0;s="#{i+=1}"while s[?0]||(0...x=s.size).any?{|i|(s[0,i]+s[i+1,x]).to_i%s[i].to_i>0}};s}

```
> 1 votes

# Answer
## Hoon, 246 bytes

```
=+
x=0
|=
n/@
=+
k=<x>
=+
%+
levy
%+
turn
(gulf 0 (dec (lent k)))
|=
a/@
=+
(trim +(a) k)
=+
(rash (snag a p) dit)
?:
=(- 0)
|
=(0 (mod (fall (rust (weld (scag a p) q) dem) x) -))
(curr test &)
?:
=(- &)
?:
=(0 n)
x
$(n (dec n), x +(x))
$(x +(x))

```

Ungolfed:

```
=+  x=0
|=  n/@
=+  k=<x>
=+  %+  levy
  %+  turn  (gulf 0 (dec (lent k)))
  |=  a/@
  =+  (trim +(a) k)
  =+  (rash (snag a p) dit)
  ?:  =(- 0)
    |
  =(0 (mod (fall (rust (weld (scag a p) q) dem) x) -))
(curr test &)
?:  =(- &)
  ?:  =(0 n)
    x
  $(n (dec n), x +(x))
$(x +(x))

```

This...is really terrible. I feel dirty for posting this.

Set `k` to the string form of the current number, map over the list `[0...(length k)-1]` splitting the string at that index (`a`). Get the `a` character, parse it to a number, and if it's `0` return no. Get the prefix of `a` and weld it to the other half of the split, parse to a number, check if the index divides it evenly.

`++levy` returns yes iff calling the function on all the elements of the list is also yes. In this case, the function `++test` curried with yes, so it checks that all of the characters in `k` work.

If we're at the 0th value, we return the current number, or else we recurse with n decremented (and increment `x`)
> 1 votes

# Answer
# Lua, 199 bytes

```
n,m=1,...function e(n)for i=1,#n do x=n:sub(1,i-1)..n:sub(i+1)s=n:sub(i,i)if x==""or s=="0"or x%s~=0 then return x==""end end return true end while m+0>0 do n=n+1 m=m-(e(""..n)and 1 or 0)end print(n)

```

Try it online!
> 0 votes

---
Tags: code-golf, number, arithmetic, integer
---


title: Let's do some "deciph4r4ng"

text:
# Question
Title: Let's do some "deciph4r4ng"
In this challenge, your task is to decipher a string. Luckily, the algorithm is pretty simple: reading from left to right, each encountered digit ***N*** (0 to 9) must be replaced with the character which is ***N+1*** positions before it.

### Example

The input string `"Prog2am0in6"` would be decoded this way:

Hence, the expected output is `"Programming"`.

### Clarifications and rules

* The input string will contain ASCII characters in the range 32 - 126 exclusively. You can assume that it will never be empty.
* The original deciphered string is guaranteed not to contain any digit.
* Once a character has been decoded, it may in turn be referenced by a subsequent digit. For instance, `"alp2c1"` should be decoded as `"alpaca"`.
* References will never wrap around the string: only previous characters can be referenced.
* You can write either a full program or a function, which either prints or outputs the result.
* This is code golf, so the shortest answer in bytes wins.
* Standard loopholes are forbidden.

### Test cases

```
Input : abcd
Output: abcd

Input : a000
Output: aaaa

Input : ban111
Output: banana

Input : Hel0o W2r5d!
Output: Hello World!

Input : this 222a19e52
Output: this is a test

Input : golfin5 3s24o0d4f3r3y3u
Output: golfing is good for you

Input : Prog2am0in6 Puz0les7&1Cod74G4lf
Output: Programming Puzzles & Code Golf

Input : Replicants 4re3lik448ny3oth8r5mac6in8.8T64y'r371it9376a1b5n1fit7or2a1h2z17d.
Output: Replicants are like any other machine. They're either a benefit or a hazard.

```

# Answer
> 12 votes
# Jelly, ~~9~~ 7 bytes

```
~ịṭṭµ@/

```

Try it online!

### How it works

```
~ịṭṭµ@/  Main link. Argument: s

    µ    Combine the four links to the left into a chain (arity unknown).
     @   Swap the chains arguments. This makes it dyadic.
      /  Reduce s by the chain with swapped arguments. It will be called with
         right argument r (the result of the previous call, initially the first
         character) and left argument c (the next character of s).
~            Bitwise NOT of c. This maps a digit 'd' to ~d = -(d+1), but all
             non-digit characters 'D' to 0.
  ṭ          Tack; append c to r.
 ị           Index; select the character of the result to the right at the
             index from the result to the left. Indexing is 1-based and modular,
             so 0 is the last character, -1 the second to last, etc.
   ṭ         Tack; append the resulting character to r.

```

# Answer
> 13 votes
# Java 7, ~~81~~ 80 bytes

```
void a(char[]a){for(int i=0;++i<a.length;)if(a[i]>47&a[i]<58)a[i]=a[i-a[i]+47];}

```

Try it online!

Saved 1 byte thanks to Anders Tornblad. The first character cannot be a digit so it doesn't need to be checked meaning we can preincrement before checking our terminate condition.

# Answer
> 12 votes
## Haskell, 55 bytes

```
o#c|c>'/',c<':'=o!!read[c]:o|1<2=c:o
reverse.foldl(#)[]

```

Usage example: `reverse.foldl(#)[] $ "Prog2am0in6 Puz0les7&1Cod74G4lf"` -\> `"Programming Puzzles & Code Golf"`. Try it online!

Reduce the string to a reverse copy of itself with the numbers replaced by the corresponding chars. "reverse", because this way we have easy access to the string so far when indexing the numbers. Reverse it again.

# Answer
> 11 votes
# C, 46 bytes

```
f(char*s){for(;*s++;)*s=s[(*s-52)/6?0:47-*s];}

```

Try it online!

---

# C,  ~~52~~   ~~49~~  48 bytes

*Thanks to @l4m2 for saving a byte!*

```
f(char*s){for(;*s++;)*s>47&*s<58?*s=s[47-*s]:0;}

```

Edits the input string directly.

Try it online!

**Alternative 50-byte version:**

```
f(char*s){for(;*s++;)*s=abs(*s-57)>9?*s:s[47-*s];}

```

**Recursive version, 48 bytes:**

```
f(char*s){*s>47&*s<58?*s=s[47-*s]:0;*s++&&f(s);}

```

# Answer
> 9 votes
# 05AB1E, 11 bytes

```
vydiÂyèëy}J

```

Try it online!

**Explanation**

```
v            # for each character y in input
 ydi         # if y is a digit
    Â        #    push a reversed copy of the string we've built up so far
     yè      #    push the character at index y in the reversed string
       ë     # else
        y    #    push y
         }   # end if
          J  # join stack to a single string
             # output top of the stack at the end of the loop

```

# Answer
> 7 votes
# JavaScript (ES6), 59 53 bytes

```
f=x=>/\d/.test(x)?f(x.replace(/\d/,(m,o)=>x[o+~m])):x

```

Saved 7 bytes thanks to fəˈnɛtɪk.

```
f=x=>/\d/.test(x)?f(x.replace(/\d/,(m,o)=>x[o+~m])):x

console.log(f("Prog2am0in6"));
console.log(f("abcd"));
console.log(f("a000"));
console.log(f("ban111"));
console.log(f("Hel0o W2r5d!"));
console.log(f("this 222a19e52"));
console.log(f("golfin5 3s24o0d4f3r3y3u"));
console.log(f("Prog2am0in6 Puz0les7&1Cod74G4lf"));
console.log(f("Replicants 4re3lik448ny3oth8r5mac6in8.8T64y'r371it9376a1b5n1fit7or2a1h2z17d."));
```

# Answer
> 5 votes
## Retina, 37 bytes

Byte count assumes ISO 8859-1 encoding.

```
\d
$*«»
r1+`(?<=(.)(?<-2>.)*)(«)*»
$1

```

Try it online!

### Explanation

```
\d
$*«»

```

Replace each digit **d** with **d** `«`s, followed by one `»`. We need the latter a) to be able to recognised positions where **d = 0** and b) as a separator between adjacent digits.

```
r1+`(?<=(.)(?<-2>.)*)(«)*»
$1

```

Repeatedly (`+`) match the regex on the first line from right to left (`r`) and then replace the left-most match (`1`) with the substitution on the second line.

The regex itself matches one of our now unary digits and counts the number of `«`s in group 2. The lookbehind then matches **d** characters with `(?<-2>.)*` before capturing the referred-to character in group 1. The string of `«`s and `»` is then replaced with the captured character.

# Answer
> 5 votes
# MATL, ~~21~~ ~~19~~ ~~17~~ 16 bytes

```
"@t4Y2m?UQ$y]]&h

```

Try it at **MATL Online!**

**Explanation**

```
        % Implicitly grab input as a string
"       % For each character in the input
  @     % Push that character to the stack
  t     % Make a copy of it
  4Y2   % Push the pre-defined array '0123456789' to the stack
  m     % Check if the current character is part of this array (a digit)
  ?     % If it is
    UQ  % Convert it to a number and add 1 (N)
    $y  % Make a copy of the element N-deep in the stack. MATL uses one-based indexing
        % So 1$y is the element at the top of the stack, 2$y is the next one down, etc.
  ]     % End of if statement
        % Non-digit characters remain on the stack as-is
]       % End of for loop
&h      % Horizontally concatenate the entire stack to form a string
        % Implicitly display the result

```

# Answer
> 4 votes
## JavaScript (ES6), 51 bytes

```
f=
s=>s.replace(/\d/g,(c,i)=>a[i]=a[i+=~c]||s[i],a=[])
```

```
<input oninput=o.textContent=f(this.value)><pre id=o>
```

`a` is used to store the replaced digits to deal with digits referring to other digits.

# Answer
> 3 votes
# Perl 5, 34 bytes

33 bytes of code + `-p` flag.

```
s/\d/substr$_,-$&-1+pos,1/e&&redo

```

Try it online!

`s/\d/.../e` replace the first digit by `...` evaluated as Perl code. (with `...` being `substr$_,-$&-1+pos,1` in that case. `substr$_,-$&-1+pos,1` returns the substring of `$_` of length `1` at index `-$&-1+pos`, where `$&` is the number just matched, and `pos` is the index of the start of the match. We just need to `redo` if the replace was successful in order to replace every digit. (and the result is implicitly printed thanks to `-p` flag).

---

Old approach, 47 bytes:

44 bytes of code + `-F` flag.

```
map{$F[$i]=$F[$i-$_-1]if/\d/;++$i}@F;print@F

```

Try it online!

Quite straight forward actually. `-F` flag splits the inputs on each character into `@F`. `map{...}@F` iterates through `@F` (ie. every character of the input). If the character if a digit (`/\d/`), then we replace it by the character at index `$i-$_-1`. The `$i` is the current index variable (that we maintain by incrementing at each character seen).

# Answer
> 3 votes
# JavaScript ES6, ~~61~~ 59 bytes

Thanks @Luke for golfing off 8 bytes

```
x=>[...x].map((p,i,a)=>a[i]=/\d/.test(p)?a[i-1-p]:p).join``

```

Try it online!

# Answer
> 3 votes
# 05AB1E, ~~27~~ 17 bytes

```
vyDdiU)DRXèU`X}}J

```

Try it online!

```
vy             }  # For each character
  Dd              #   Push is_number
    i         }   #   If it is
     U            #     Save save it
      )DR         #     Wrap the (reversed) stack into an array
         Xè       #     Get the character at the saved index
           U`X    #     Flatten the whole stack
                J # Join

```

# Answer
> 2 votes
# Python 2, ~~75~~ 71 bytes

```
s='';j=-1
for i in input():s+=s[j-int(i)]if'/'<i<':'else i;j+=1
print s

```

Try it Online!

**Edit:** Fixed for ascii values between 32-47 **;** Fixed for double decoding (eg. "alp2c1" to "alpaca")

# Answer
> 2 votes
# CJam, 13 bytes

```
q{_A,s#)$\;}/

```

Online demo.

This solution uses CJam's built-in "copy *n*-th item on the stack" operator `$` to implement the decoding. It starts by reading the input (with `q`) and then looping over the characters from the input string and dumping them onto the stack (with `{}/`). However, inside the loop body it also duplicates each character after it has been put on the stack (with `_`) and checks if it's a digit by looking up its position with `#` in the string `"0123456789"`, conveniently represented as `A,s`.

The result of this lookup is either the digit's numeric value or, if the character is not a digit, -1. The `)` operator then increments that value by one, and `$` replaces it with the character current at that many positions below the top of the stack. Finally, `\;` just removes the copy of the current input character that we made with `_` from the stack, as it's no longer needed.

# Answer
> 2 votes
# Befunge-98, ~~45~~ 43 bytes

```
::::#@~\1p:1g::'9`!\'/`*j;'/--1g\1p\1g#;,1+

```

Try it online!

The idea:

1. For each char in the input string,
    1. Write it to line 2
    2. If it is not a number, just output it
    3. Otherwise, look up the correct value, rewrite it, then output it

```
::::            ; There's a counter on the stack, duplicate it 4 times  ;
    #@~         ; Get the next char of input, exiting if there is none  ;
       \1p      ; At the location (counter, 1), write the input char    ;
          :1g   ; Re-obtain the char. Stack is now [counter * 4, input] ;

::                ; Stack: [counter * 4, input * 3]      ;
  '9`!\'/`*       ; If !(input > '9') and (input > '/')  ;
                  ; IE If ('0' <= input && input <= '9') ;
           j;...; ; Then execute the ...                 ;

; Stack: [counter * 4, input] ;
; The ... branch:             ;

'/-             ; input -> int. (input -= '/')             ;
   -            ; counter - int(input) - 1                 ;
                ; Stack: [counter * 3, lookupPosition ]    ;
    1g          ; Get the char that we want to find        ;
      \1p\1g#   ; Overwrite the current char (not the old) ;

; Both branches: ;
,1+             ; Print the number and increment the counter ;

```

---

I wasn't able to get this version shorter, but this one is 44 bytes:

```
s #@~\3p:3g::'9`!\'/`*j;'/--3g#;:10g3p,1+:::

```

Thought I'd share it because of the neat trick with `s` \- but storing the counter on the stack leads to that 1 char improvement

# Answer
> 2 votes
# Python 2, 59 bytes

```
s=''
for c in input():s+=c['/'<c<':':]or s[~int(c)]
print s

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog Classic), ~~25~~ 23 bytes

-2 bytes thanks to @FrownyFrog

```
((⊂⌷⊢)⍣≡⍳∘≢-11|⎕d∘⍳)⊃¨⊂

```

Try it online!

uses `⎕io←1`

( below stands for an intermediate value in the evaluation)

`⎕d` is the string `'0123456789'`

`⎕d⍳⍵` finds the (1-based in this case) indices of 's chars in `⎕d`; for a non-digit the index is 11

`11|⍵` is modulo - the 11s become 0s

`≢⍵` is the length of

`⍳≢⍵` is `1 2 ...` till `≢⍵`

so, `(⍳≢⍵)-11|⎕d⍳⍵` gives us a vector *i* of the indices where we should look to get the resulting characters; however some of those indices may redirect to yet other (smaller) indices. To compute the transitive closure (i.e. the effective indices), we index the vector into itself (`⊂⌷⊢`, a train equivalent to `(⊂i)⌷i` or `i[i]`) and repeat that until it stabilises (`⍣≡` is known as the *fixed point* operator).

finally we index into the original string: `(...)⊃¨⊂`

# Answer
> 2 votes
# PHP 7.1 ~~67~~ 59 bytes

```
while(_&$c=$argn[$i++])$t.=($c^"0")<"
"?$t[~+$c]:$c;echo$t;

```

Takes input from STDIN; run as pipe with `-nR` or try it online.

* `_&$c=$s[$i++]` loop through string (`_&$c` will result in something that is not `"0"`; so the only character that can break the loop is the empty string = end of input)
* `$c^"0"` toggle bits 5 and 6 in the ascii code
* `<"\n"` check if result is \< chr(10)
* if so, it is a digit: print previous character by index (and copy to current index)
* else print this character

Thanks @Christoph for saving 12%

# Answer
> 2 votes
# Vim macro/keystrokes, ~~49~~ 29 bytes

`^M` represent the return character (0x0A, 1 byte).

```
qaqqa/\d^Myl@=@"+1^Mhylnvp@aq@a

```

## Explanation

```
qaq                                 clear register a
   qa                               record into a
     /\d^M                          move the cursor to the next digit
          yl                        yank the digit
            @=@"+1^Mh               move the cursor left that number of characters plus one
                     yl             yank the char
                       n            go back to the digit
                        vp          replace the digit with the yanked char
                          @a        recursive call will execute until the search for a digit fails
                            q       stop recording
                             @a     run the macro

```

# Answer
> 1 votes
# Python 2,~~83~~ 80 bytes

```
r=input()
for i in r:
 if'/'<i<':':r=r.replace(i,r[r.find(i)+~int(i)],1)
print r

```

Try it online!

* saved 3 bytes but checking ascii instead of is digit! Thanks to math\_junkie!

# Answer
> 1 votes
# Japt, 24 bytes

```
£Xn >J?U=UhYUgJ+Y-X):PÃU

```

Try it online!

### Explanation:

```
£Xn >J?U=UhYUgJ+Y-X):PÃU
£                     Ã    Iterate through the input (implicit U)
                             X becomes the iterative item, Y becomes the index
 Xn                          Try parseInt(X)
    >J                       > -1
                               In this case, this checks if X is a digit
      ?                      If true:
       U=                      Set U to
         UhY                     U with the char at index Y set to:
            UgJ+Y-X               The index at -1+Y-X
                   ):        Else:
                     P         variable P (just a no-op in this case)
                       U   Finally, return U

```

# Answer
> 1 votes
# Ruby, ~~56~~ 46 bytes

```
->s{i=0;s[i]=s[i+~s[i].to_i]while i=s=~/\d/;s}

```

Try it online!

# Answer
> 1 votes
# Python 2, 58 bytes

```
lambda s:reduce(lambda t,c:t+(c+t)['/'<c<':'and~int(c)],s)

```

This is essentially a port of my Jelly answer, plus the digit check from @xnor's Python answer.

Try it online!

# Answer
> 1 votes
# Röda, 51 bytes

```
f a{x=0;a|{|y|a[x]=a[x+47-ord(y)]if[y=~`\d`];x++}_}

```

Try it online!

# Answer
> 1 votes
# JavaScript ES6, 54 bytes

```
f=r=>[...r].reduce((a,s,i)=>a+(/\d/.test(s)?a[i+~s]:s))

```

```
f=r=>[...r].reduce((a,s,i)=>a+(/\d/.test(s)?a[i+~s]:s))

console.log(f("Prog2am0in6"));
console.log(f("abcd"));
console.log(f("a000"));
console.log(f("ban111"));
console.log(f("Hel0o W2r5d!"));
console.log(f("this 222a19e52"));
console.log(f("golfin5 3s24o0d4f3r3y3u"));
console.log(f("Prog2am0in6 Puz0les7&1Cod74G4lf"));
console.log(f("Replicants 4re3lik448ny3oth8r5mac6in8.8T64y'r371it9376a1b5n1fit7or2a1h2z17d."));
```

# Answer
> 1 votes
# \>\<\> (Fish), 108 bytes (= 9 x 12 grid)

```
01-r>:0(\
"/"&::;?/
)?\v    \
":/v!?(":
")\ :>:"0
 !?\
${/  \ -1
&>\ ~{:&$
\ \ :"0"=
/\- 1}$/?
:v&//}~/~
 \o}\&$/

```

Try it here to see the fish swimming around.

* Append -1 to the input stack then reverse the stack.
* Loop: If top value is -1 then end (we've cycled through all characters). Otherwise:
* Put the top character in the register; check to see whether it's in the range "0" to "9". If so:
    + rotate the stack the appropriate number of places
    + get the character being pointed to
    + rotate back and replace the number with the character from the register
* Output; resume loop.

# Answer
> 1 votes
# 8086 machine code, 35 bytes

```
00000000  be 82 00 ac 98 50 2c 30  3c 09 77 0c 4e 89 f7 4e  |.....P,0<.w.N..N|
00000010  29 c6 58 ac aa 89 fe 50  5a b4 02 cd 21 80 fa 0d  |).X....PZ...!...|
00000020  75 e1 c3                                          |u..|
00000023

```

# Answer
> 1 votes
# oK, 39 bytes

```
{x{x[y 0]:x@-/y}/(!#x),'0|{x*11>x}x-47}

```

Try it online!

# Answer
> 1 votes
# , 20 bytes

```
{~[:{~^:_#\-2+_1".,.

```

Try it online

```
                  ,.  Each character on a separate row
              _1".    Convert to numbers, replacing non-numbers with -1
                         (it becomes one row again)
            2+        Add 2.
         #\           Prefix lengths (range 1..length)
           -          Subtract
  [:{~^:_             Index into itself as long as it changes the result
{~                    Index into the original string

```

Credit to ngn for the inspiration.

### 22 bytes

```
(],,{~1{._1-_1".[)/@|.

```

This is a port of the Jelly answer.

```
                    |. The string backwards, because reduce is right-to-left.
            _1".[      The next character as a number (d), -1 if it's not a number,
                          and a space character produces an empty array.
         _1-           -1-d
      1{.              Take 1. If we have a nothing
                          at this point, that makes it a 0.
   ,                   Prepend the next character to the result of the previous call.
    {~                 Select the character. 0 is the first, _2 is second to last.
 ],                    Append the result.

```

In both solutions the version that TIO uses interprets a single `.` as the number 0, so the last test fails. Older versions (≤7) seem to work correctly.

Try it online!

# Answer
> 1 votes
# Japt v2.0a0, 16 bytes

```
r\d@=hYUgY-°X¹gY

```

Try it

---

## Explanation

```
                     :Implicit input of string U
r                    :Replace
 \d                  :  RegEx /\d/g
   @                 :  Pass each match X at index Y through a function
     hY              :    Set the character at index Y in U
       UgY-°X        :    To the character at index Y-++X
    =        ¹       :    Reassign to U
              gY     :    Get the character at index Y

```

# Answer
> 1 votes
# C# (.NET Core), 138 bytes

```
string d(string x){var e=x.ToCharArray();for(int i=0;++i<e.Length;){if(char.IsDigit(e[i]))e[i]=e[i-((e[i]-'0')+1)];}return new string(e);}

```

Try it online!

# Answer
> 0 votes
# PHP, 79 Bytes

```
for(;++$i<strlen($a=&$argn);)is_numeric($l=$a[$i])?$a[$i]=$a[$i-$l-1]:0;echo$a;

```

# Answer
> 0 votes
# PowerShell, 98 82  76 71 bytes

```
switch -r(($n=($args|% t*y))){\d{$n[$j]=$n[$j-$_+47]}.{$j++}};$n-join''

```

Try it online!

Suggestions welcome!

**EDIT** It looks like powershell will redefine `$i` when I set it on the right side of the equation in the `if` statement. I did not realize it looked at that first - saved 1 byte

**EDIT 2** Found another way to find the current index by using `$j` as an index that iterates for each foreach pass - saved 15 bytes and copied method from @AdmBorkBork for creating character arrays \[found here\]\[2\]! - saved another 6 bytes

**EDIT 3** Changed to a switch statement and collapsed unnecessary spaces in the output

# Answer
> 0 votes
## REXX, 118 bytes

```
a=arg(1)
do n=1 to length(a)
  c=substr(a,n,1)
  if datatype(c)=num then do
    a=overlay(substr(a,n-1-c,1),a,n)
    end
  end
say a

```

# Answer
> 0 votes
Currently 4 JavaScript solutions

```
x=>[...x].map((p,i,a)=>a[i]=1+p>9?a[i-1-p]:p).join``
r=>[...r].reduce((a,s,i)=>a+(1+s>9?a[i+~s]:s))
s=>s.replace(a=/\d/g,(c,i)=>a[i]=a[i+=~c]||s[i])
x=>f=x!=(x=x.replace(/\d/,(m,o)=>x[o+~m]))?f():x

```

# Answer
> 0 votes
# , 105 bytes

```
function(S,s=el(strsplit(S,"")))for(k in 1:nchar(S))cat(s[k]<-"if"(s[k]%in%0:9,s[k-strtoi(s[k])-1],s[k]))

```

Try it online!

# Answer
> 0 votes
# Lua, 111 bytes

```
s=...z=s:gmatch("()%d")c=z()g=s.sub while c do v=c-g(s,c,c)-1 s=g(s,1,c-1)..g(s,v,v)..g(s,c+1)c=z()end print(s)

```

Try it online!

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


# Question
Title: ASCII Art of the Day #3 - Chinese Shrines
In today's episode of AAOD, we are going to construct a Chinese Shrine of varying heights.

Consider the following examples for height (`N`) `1` to `6`

`N = 1`:

```
       .
       |
  .   ]#[   .
   \_______/
.    ]###[    .
 \__]#.-.#[__/
  |___| |___|
  |___|_|___|
  ####/_\####
     |___|
    /_____\

```

`N = 2`:

```
         .
         |
    .   ]#[   .
     \_______/
  .    ]###[    .
   \___________/
.     ]#####[     .
 \___]#.---.#[___/
  |__|_|   |_|__|
  |__|_|___|_|__|
  #####/___\#####
      |_____|
     /_______\

```

`N = 3`:

```
           .
           |
      .   ]#[   .
       \_______/
    .    ]###[    .
     \___________/
  .     ]#####[     .
   \_______________/
.      ]#######[      .
 \____]#.-----.#[____/
  |__|__|     |__|__|
  |__|__|_____|__|__|
  ######/_____\######
       |_______|
      /_________\

```

`N = 4`:

```
             .
             |
        .   ]#[   .
         \_______/
      .    ]###[    .
       \___________/
    .     ]#####[     .
     \_______________/
  .      ]#######[      .
   \___________________/
.       ]#########[       .
 \_____]##.-----.##[_____/
  |__|__|_|     |_|__|__|
  |__|__|_|_____|_|__|__|
  ########/_____\########
         |_______|
        /_________\

```

`N = 5`:

```
               .
               |
          .   ]#[   .
           \_______/
        .    ]###[    .
         \___________/
      .     ]#####[     .
       \_______________/
    .      ]#######[      .
     \___________________/
  .       ]#########[       .
   \_______________________/
.        ]###########[        .
 \______]###.-----.###[______/
  |__|__|___|     |___|__|__|
  |__|__|___|_____|___|__|__|
  ##########/_____\##########
           |_______|
          /_________\

```

`N = 6`:

```
                 .
                 |
            .   ]#[   .
             \_______/
          .    ]###[    .
           \___________/
        .     ]#####[     .
         \_______________/
      .      ]#######[      .
       \___________________/
    .       ]#########[       .
     \_______________________/
  .        ]###########[        .
   \___________________________/
.         ]#############[         .
 \_______]####.-----.####[_______/
  |__|__|__|__|     |__|__|__|__|
  |__|__|__|__|_____|__|__|__|__|
  ############/_____\############
             |_______|
            /_________\

```

and so on.

# Construction Details

I am sure most of the details about the pattern are clear. Here are some finer details:

* The door at the bottom of the shrine can at minimum be of `1` `_` width and at maximum be of `5` `_` width.
* There will always be two `.` directly above the pillars around the door (two vertical `|`).
* The stairs start with the same width as the door and increase like show in the pattern
* The `]##..##[` blocks above each roof level increase in size of `2` from top to bottom.
* The `\__...__/` roofs levels increase in size of `4` from top to bottom.
* The walls blocks around the door should at minimum contain `1` `_` and at maximum, `3` `_` between the two `|`. Priority goes to the outer wall blocks so that the one closest to the door gets a varying size for each level.
* The space between the `.` and the `]` (or `[`) is filled by `#` in the roof just above the doors.

# Challenge Details

* Write a function or full program that reads a positive integer greater than `0` via STDIN/ARGV/function argument or closest equivalent and outputs (to STDOUT or closest equivalent) the `N`th Chinese Shrine
* Trailing newline is optional.
* There should either be no trailing spaces or enough trailing spaces to pad the output in the minimum bounding rectangle.
* There should not be any leading spaces that are not part of the pattern.

# Leaderboard

**The first post of the series generates a leaderboard.**

To make sure that your answers show up, please start every answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

# Answer
# CJam, 200 bytes

```
-4'.-4'|]2/ri:M),{2af.-~[W'.I3+~']'#I)*][-2'\'_I2*4+*]]}fI~[~M)<']
M2m1e>'#*'.'-M3e<:D*][-3"|__"M*M2+M2*(e>:L<"_|"D~][_~~'_*][-3'#L)*
'/'_D*][L2+~'|'_D)*][L)~'/'_D2+*]]{{_0<{~S*}&}%s_W%1>"\/]""/\["erN}%

```

Newlines added to avoid scrolling. Try it online

**Brief explanation:**

The program builds the left half of the shrine (including the middle), then reverses it and replaces some characters to get the right half. A series of n spaces is represented as the number ~n (bitwise "not") during construction, and replaced with the actual spaces at the end.

The program starts with the top 2 lines, then for each roof level, it prepends all the previous lines with 2 spaces and adds the new roof (2 lines). The last roof is modified to add the "above door" part.

Next, the upper wall is built by repeating "|\__" and truncating at the right length, followed by a fixed "\_|" and spaces. The wall is then duplicated and the door spaces are replaced with underscores. Finally, the lower part is constructed line by line.
> 2 votes

# Answer
# Perl, ~~332 316~~ 294

```
$:=($w=<>)*2+6;$r=2x($m=$w>3?3:$w);$k=1x($w-3).b.4x$m;
y!a-f1-4!/.|\\[,#_ -!,/,/,s/(.*),(.*).{@{-}}/$2$1/,printf"%$:s%s
",y!/\\[!\\/]!r,(reverse=~s/.//r)for@x=(b,c,
(map{b33.3x$_.e.1x$_,"[#$k,"x/$w/.a__.22x$_}1..++$w),
_c.3x$m.f.($z=substr"|__"x$:,0,2*++$w),"_|$r,$z","d$r,".11x$w,c_.$r,d__.$r)

```

Try me.

# C, 371

```
d,i,w;char s[1<<24];m(){v(w,13);}p(){puts(s+1);}
v(i,j){s[w-i]=".|]\\#/"[j%7];s[w+i]=".|[/#\\"[j%7];
while(i--)s[w-i]=s[w+i]="# _-"[j/7];}
main(l){scanf("%d",&l);d=l>3?3:l;m(w=l*2+6);p(v(0,0));
for(v(0,1);i++<=l;v(i*2+2,17))p(),v(i*2+3,7),m(p(v(i,2)));v(l+2,2);p(v(d,21));
for(m(i=w-3);i>d+1;i-=3)v(i,15);p(v(d,8));p(v(d,15));
v(w-3,4);m(p(v(d,19)));p(v(d+1,15));p(v(d+2,19));}

```

Try me.

# JavaScript, 365

The above can be translated almost 1 to 1 into JavaScript:

```
s=[];r="";i=0;m=()=>v(w,13);p=()=>r+=s.join('')+"\n";
v=(i,j)=>{s[w-i]=".|]\\#/"[j%7];s[w+i]=".|[/#\\"[j%7];
while(i--)s[w-i]=s[w+i]="# _-"[j/7|0];};
f=l=>{d=l>3?3:l;m(w=l*2+6);p(v(0,0));
for(v(0,1);i++<=l;v(i*2+2,17))p(),v(i*2+3,7),m(p(v(i,2)));v(l+2,2);p(v(d,21));
for(m(i=w-3);i>d+1;i-=3)v(i,15);p(v(d,8));p(v(d,15));
v(w-3,4);m(p(v(d,19)));p(v(d+1,15));p(v(d+2,19));}

```

Use:

```
f(2);console.log(r)

```
> 6 votes

# Answer
# Python 2, ~~356~~ ~~352~~ ~~347~~ 344 bytes

```
n=input()
A,B,C,D,E,F,G,H,I='_ |\/#.]['
def p(*S):
 for s in S:print(5+2*n-len(s)/2)*B+s
p(G,C,'.   ]#[   .')
for i in range(n):b=B*(4+i);p(D+A*(7+4*i)+E,G+b+H+F*(3+2*i)+I+b+G)
d=2*min(3,n)-1
a=A*(2+i)
f=F*(1+i-d/2)
j=4+2*i-d/2
w=('|__'*n)[:j-1]+A+C
v=w[::-1]
p(D+a+H+f+G+'-'*d+G+f+I+a+E,w+B*d+v,w+A*d+v,F*j+E+A*d+D+F*j,C+A*(d+2)+C,E+A*(d+4)+D)

```

This basically builds the shrine line by line. The function `p` prints a string with the spaces needed to center it.

I used *python 2* to save lots of bytes, because the *python 3* map object doesn't trigger. I guess I should always golf in *python 2*, just saves a few more bytes (even if it's just to not have to parse the input to int). Hehehe, it's not like code's pretty for golfing in the first place.

Edit: and of course, I now don't need the map anymore...

Here's the code in ungolfed form:

```
n = int(input())

# A function to print strings centered
half_width = 5 + 2*n
def p(string):
    spaces = ' ' * (half_width - len(string) // 2)
    print(spaces + string)

# The rooftops
p('.')
p('|')
p('.   ]#[   .')
for i in range(n):
    p('\\' + '_'*(7 + 4*i) + '/')
    p('.{0}]{1}[{0}.'.format(' '*(i + 4), '#'*(3 + 2*i)))

# The bottom rooftop
door_width = 2 * min(3, n) - 1
# (11+4i - (3+2i) - 4) / 2 = (4 + 2i) / 2 = 2 + i
p('\{0}]{1}.{2}.{1}[{0}/'.format('_'*(2 + i), '#'*(1 + i - door_width // 2), '-'*door_width))

# The windows
w = '|__'*n
w = w[:4 + 2*i  - door_width // 2]
if w[-1] == '|':
    w = w[:-1] + '_'
w += '|'
p(w + ' '*door_width + w[::-1])
p(w + '_'*door_width + w[::-1])

# The foundation and the stairs
w = '#'*(4 + 2*i - door_width // 2)
p(w + '/' + '_'*(door_width) + '\\' + w)

# The remaining stairs
p('|' + '_'*(door_width + 2) + '|')
p('/' + '_'*(door_width + 4) + '\\')

```
> 5 votes

# Answer
# JavaScript (*ES6*), 440

**Edit** Fixed lintel bug

A function whith height as a parameter, output to console.

Using template string *a lot*, all newlines are significant and counted.

Run snippet to test in Firefox (with console output)

```
f=x=>{R=(n,s=0)=>' #_-'[s][Z='repeat'](n),M=c=>R(2)+'|__'[Z](z+1).slice(0,z-1)+'_|'+R(y,c)+'|_'+'__|'[Z](z+1).slice(1-z)
for(z=x+x+(x<2)+(x<3),y=x>2?5:x>1?3:1,l=-1,o=`${t=R(x+x+5)}.
${t}|
`;l++<x;)o+=`${t=R(x+x-l-l)}.${u=R(l+3)}]${R(l*2+1,1)}[${u}.
 ${t}\\${l-x?R(7+l*4,2):`${t=R(x+1,2)}]${u=R(x<3||x-2,1)}.${R(y,3)}.${u}[${t}`}/
`;console.log(`${o+M(0)}
${M(2)}
${R(2)}${t=R(z,1)}/${u=R(y,2)}\\${t}
${R(1+z)}|__${u}|
${R(z)}/____${u}\\`)}

// TEST
f(1),f(2),f(3),f(4),f(5),f(6)
```

```
Output 1 to 6 in console
```

**Ungolfed** version for interactive test:

```
// Not so golfed

f=x=>{
  R=(n,s=0)=>' #_-'[s].repeat(n); // base building blocks
  M=c=>R(2)+'|__'.repeat(z+1).slice(0,z-1)+'_|'+R(y,c)+'|_'+'__|'.repeat(z+1).slice(1-z); // manage door level

  z=x+x+(x<2)+(x<3); // door and stairs surroundings
  y=x>2?5:x>1?3:1; // door and stairs width

  o = `${R(x+x+5)}.\n${R(x+x+5)}|\n`; // top
  for(l=-1;l++<x;)
    o += `${ // even row
      t=R(x+x-l-l) // left padding
    }.${
      u=R(l+3)
    }]${
      R(l*2+1,1)
    }[${
      u
    }.\n ${ // end even row, start odd row
      t // left padding
    }\\${
      l-x?R(7+l*4,2)
      :`${t=R(x+1,2)}]${u=R(x<3||x-2,1)}.${R(y,3)}.${u}[${t}` // if last row before the door, insert lintel
    }/\n`;

  o += `${
    M(0) // door level row 1
  }\n${
    M(2) // door level row 2
  }\n${
    R(2)}${t=R(z,1)}/${u=R(y,2)}\\${t  // stairs row 1
  }\n${
    R(1+z)}|__${u  // stairs row 2
  }|\n${
    R(z)}/____${u // stairs row 3
  }\\`;

  out(o)
}

out=x=>O.innerHTML=x

f(3)
```

```
<input id=I value=3><button onclick='f(+I.value)'>-></button><br>
<pre id=O></pre>
```
> 4 votes

# Answer
# Vyxal, 280 bytes

```
d5+\.꘍,d5+\|꘍,(n-d:£\.꘍3n+\]꘍\#nd›*\[3n+\.꘍Ṡ,¥›\\꘍ndd7+\_*\/Ṡ,)\.?3+꘍\]\#?d›*\[?3+\.꘍Ṡ,ð\\?›\_*\]?2-1∴\#*\.?d‹5∵-\.?2-1∴\#*\[?›\_*\/Ṡ,3<[⟨0|⟨3⟩|⟨2|1⟩⟩$i|3/⌊d2w$ẋf`013`?3%iIJ';]\_*Ṅðpð+ð\|Vðdp:£3?∵꘍øm,¥3?∵\_*+øm,4<[3+|d]\#*:£ðdp\/\_?d‹5∵*\\¥Ṡ,¥L›\|꘍\_?d‹5∵⇧*\|Ṡ,¥L\/꘍\_?d‹5∵4+*\\Ṡ,

```

Try it Online! No, I'm not explaining this.
> 3 votes

# Answer
# Charcoal, 404 bytes

```
≔Ｎν≔⁺⁵×²νη≔× ⁻η⁻∕¹¦²¦¹τ⁺⁺⁺⁺⁺τ.¶τ|¶× ⁻η⁻∕¹²¦²¦¹“±∨N"G:Ｗ⮌+”Ｆν«≔⁺⁺\×_⁺⁷×⁴ι/ε≔× ⁻η⁻∕Ｌε²¦¹τ⁺⁺τε¶≔⁺⁺⁺⁺.× ⁺ι⁴]×#⁺³×²ι⁺⁺[× ⁺ι⁴.ε≔× ⁻η⁻∕Ｌε²¦¹τ⁺⁺τε¶»≔⁻×²⌊⟦³ν⟧¹δ≔∕δ²ζ≔×#⁺¹⁻νζσ≔⁺⁺⁺⁺⁺\×_⁺ν¹]σ.⁺×-δ⁺.⁺σ⁺[⁺×_⁺ν¹/ε≔× ⁻η⁻∕Ｌε²¦¹τ⁺⁺τε¶≔×|__νε≔⁻⁻⁺⁴×²νζ¹τ≔✂ε⁰τ¦¦ε≔Ｌεα≔⁻Ｌε¹β¿⁼✂εβα¦¦|«≔⁺✂ε⁰β¦¦_ε»≔⁺✂ε⁰α¦¦|ε≔⁺⁺ε× δ⮌εα≔⁺⁺ε×_δ⮌εβＭ⁼ν¹¦⁰⁺⁺⁺⁺  α¶¦  βＭ±⁼ν¹¦⁰Ｍ±Ｌα⁰≔×#⁻⁺⁴×²⁻ν·⁵ζε⁺¶⁺⁺ε⁺/⁺⁺×_δ\ε¶≔⁻⁻⁺⁴×²⁻ν·⁵ζ¹ψ⁺× ψ⁺|⁺×_⁺δ²|¶⁺× ⁻ψ¹⁺/⁺×_⁺δ⁴\

```

Try it online!
> 3 votes

# Answer
# Haskell, 473 bytes

```
g '\\'='/'
g '/'='\\'
g '['=']'
g ']'='['
g x=x
z=reverse
d=min 3
m n s=putStrLn$(6+2*n+1-length s)#' '++map g(z s)++tail s
n#c=replicate n c
t 0=".";t n=n#'#'++"["++(2+n)#' '++"."
r 0="|";r n=(2+2*n)#'_'++"/"
q n=d n#'-'++"."++max(n-2)1#'#'++"["++(n+1)#'_'++"/"
e i n=d n#i++"|_"++z(take(max(n+2)(2*n-1))(cycle"|__"))
b n=d n#'_'++"\\"++max(2*n)(3+n)#'#'
w i n=(d n+1+i)#'_'++["|","\\"]!!i
f n=mapM_(m n)$[u k|k<-[0..n],u<-[t,r]]++(t(n+1):map($n)[q,e ' ',e '_',b,w 0,w 1])

```
> 2 votes

# Answer
# Vyxal, ~~120~~ 113 bytes

```
3∵£\.\|?›ƛ⇧\.$꘍\[+\#n*+\\\_n›d*+";f÷?⇧Ẏ\]+?⇩1∴\#*+\.+¥-`|__`?:3>[d‹|⇧]Ẏ‛_|+¥꘍:ð\_VȮȧL‹\#*\/+‛|/fJ2ʀ¥+\_*+÷WvøMøĊ⁋

```

Try it Online!

Posting this as a separate answer because it's so golfed, and uses the latest version of Vyxal.

## Explanation

```
----------------- TOP ------------
3∵£                                  # Store min(input, 3) into the register for later use
   \.\|                              # Push a . and a |
       ?›ƛ                       ;   # Map 1...input+1 to
          ⇧\.$꘍                      # That+2 spaces after a dot
               \[+                   # Append a [
                  \#n*+              # Append that many #
                         \_n›d*      # That+1 underscores
                       \\      +"    # Appended to a \ and paired with the previous
                                  f÷ # All of that flattened and each pushed to the stack
------------------- Doorway ------------------
?⇧Ẏ                                            # To the last of what was pushed in the previous, take the first input+2 characters
   \]+                                         # Append a ]
      ?⇩1∴\#*+                                 # Append min(input-2,1) hashes
              \.+                              # Append a .
                 ¥-                            # Append min(input,3) -
                        ?:3>[d‹|⇧]             # Input*2-1 if input>3 else input+2
                   `|__`          Ẏ            # Repeat '|__' to that length
                                   ‛_|+        # Append '_|'
                                       ¥꘍      # Append min(input,3) spaces
                                         :ð\_V # Make a copy, and replace spaces with underscores

---------- Entrance ------------
ȮȧL‹\#*\/+
ȮȧL                      # Length of top part of doorway with whitespace removed
   ‹\#*\/+               # That-1 #, plus a /
          ‛|/fJ          # Append ['|','/']
               2ʀ¥+      # [a,a+a,a+2] where a = min(3,input)
                   \_*+  # That many underscores appended to each of previous
                       ÷ # Iterate out those on the stack

- Final magic bit -
W       # Get the stack
 vøM    # Palindromise each, mirroring brackets
    øĊ  # Center each
      ⁋ # Join on newlines

```
> 1 votes

# Answer
## C, 660 bytes

The pattern just seemed to be too irregular to come up with anything fancy, particularly in a language without string processing. So here is my brute force approach:

```
m,d,w,k,j;r(n,c){for(j=0;j++<n;)putchar(c);}c(char*s){for(;*s;)putchar(*s++);}f(n){m=n*2;d=n<3?m-1:5;w=m-d/2+2;r(m+5,32);c(".\n");r(m+5,32);c("|\n");for(;;){r(m-k*2,32);c(".");r(k+3,32);c("]");r(k*2+1,35);c("[");r(k+3,32);c(".\n");if(k==n)break;r(m-k*2+1,32);c("\\");r(k++*4+7,95);c("/\n");}c(" \\");r(n+1,95);c("]");r(n-d/2,35);c(".");r(d,45);c(".");r(n-d/2,35);c("[");r(n+1,95);c("/\n");for(k=0;k<2;){c("  ");for(j=0;j<w/3;++j)c("|__");c("|_|"-w%3+2);r(d,k++?95:32);c(!w%3?"|":w%3<2?"|_":"|_|");for(j=0;j<w/3;++j)c("__|");c("\n");}c("  ");r(w,35);c("/");r(d,95);c("\\");r(w,35);c("\n");r(w+1,32);c("|");r(d+2,95);c("|\n");r(w,32);c("/");r(d+4,95);c("\\\n");}

```

Before golfing:

```
#include <stdio.h>

void r(int n, int c) {
    for (int i = 0; i++ < n; )
        putchar(c);
}

void c(char* s) {
    for (; *s; ++s) putchar(*s);
}

int f(int n) {
    int m = n * 2;
    int d = n < 3 ? m - 1 : 5;
    int w = m - d / 2 + 2;

    r(m + 5, 32);
    c(".\n");

    r(m + 5, 32);
    c("|\n");

    for (int k = 0; ; ++k) {
        r(m - k * 2, 32);
        c(".");
        r(k + 3, 32);
        c("]");
        r(k * 2 + 1, 35);
        c("[");
        r(k + 3, 32);
        c(".\n");

        if (k == n) break;

        r(m - k * 2 + 1, 32);
        c("\\");
        r(k * 4 + 7, 95);
        c("/\n");
    }

    c(" \\");
    r(n + 1, 95);
    c("]");
    r(n - d / 2 , 35);
    c(".");
    r(d, 45);
    c(".");
    r(n - d / 2 , 35);
    c("[");
    r(n + 1, 95);
    c("/\n");

    for (int k = 0; k < 2; ++k) {
        c("  ");
        for (int j = 0; j < w / 3; ++j)
            c("|__");
        c("|_|" - w % 3 + 2);
        r(d, k ? 95 : 32);
        c(!w % 3 ? "|" : w % 3 < 2 ? "|_" : "|_|");
        for (int j = 0; j < w / 3; ++j)
            c("__|");
        c("\n");
    }

    c("  ");
    r(w, 35);
    c("/");
    r(d, 95);
    c("\\");
    r(w, 35);
    c("\n");

    r(w + 1, 32);
    c("|");
    r(d + 2, 95);
    c("|\n");

    r(w, 32);
    c("/");
    r(d + 4, 95);
    c("\\\n");

    return 0;
}

```

Not much to explain here. It just goes line by line, and generates the necessary count of each character. I tried to keep the code itself compact, but it still adds up. `d` is the width of the door, `w` the width of each brick wall.
> 0 votes

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