title: Pass on your radiation

text:
# Question
Title: Pass on your radiation
The task here is pretty simple. You should write a program that takes a string as input and outputs it (that is a cat program).

Additionally when the \\$n\\$th byte of your program is removed (without replacement) the augmented program should take a string as input and remove the \\$n\\$th character. If the input to your augmented program is less than \\$n\\$ characters long it should return it as is. For example the python program

```
x = input()
if "y" == "y":
  print(x)
else:
  print(x[:16] + x[17:])

```

Try it online!

will remove the \\$17\\$th character if its \\$17\\$th byte is removed (the first `y`).

## Scoring

Your answer's score will be the number of bytes for which removal does *not* cause the program to remove the corresponding byte. With better score being lower.

In our example above the total length is 68 bytes, with one byte (the \\$16\\$th one) augmenting the program correctly. That leaves a score of 67 bytes.

If the program were modfied to work in two places like so:

```
x=input()
u="az"
if u!="az":x=x[:13+(u<"c")]+x[14+(u<"c"):]
print(x)

```

Try it online!

Where removing the \\$14\\$th and \\$15\\$th characters (`a` and `z`) work properly. The score is 66 bytes or 68 - 2, since the program is 68 bytes long but two of those bytes work properly.

## Rules and clarifications

* There must be at least one byte which can be removed that causes the program to remove the corresponding character in the input. This means a cat program on its own is *not* a valid submission.
* Only one byte will be removed at a time. You do not have to worry about what happens when multiple bytes are removed from your program at the same time.
* You should support strings using printable ascii characters in addition to all characters that appear in your program itself. Input containing anything else is undefined behavior.

# Answer
> 24 votes
# Python 2, score:  ~~56 50~~  48 bytes - 6 = 42

This is more an attempt to allow to remove more than 1 or 2 characters than to achieve the lowest possible score. Given the scoring scheme, allowing one more byte to be removed this way would cost at least one extra byte, leaving the score unchanged at best.

You may remove the 3rd to the 8th character, i.e. any digit of \\$545454\\$.

```
n=545454;x=input();print x[:n%11]+x[n%11+n%9/4:]

```

Try it online!

### How?

Removing the \\$n\\$th digit from \\$545454\\$ and applying a modulo \\$11\\$ results in \\$n+1\\$. Applying a modulo \\$9\\$ instead allows to figure out whether the number was changed or not.

```
 pattern |    x   | x mod 9 | x mod 11
---------+--------+---------+----------
  545454 | 545454 |    0    |   (8)
  _45454 |  45454 |    4    |    2
  5_5454 |  55454 |    5    |    3
  54_454 |  54454 |    4    |    4
  545_54 |  54554 |    5    |    5
  5454_4 |  54544 |    4    |    6
  54545_ |  54545 |    5    |    7

```

# Answer
> 20 votes
# \>\<\>, 584 bytes, score 0

```
<|0!o? !@ !: !@ !: !- !1$ !i|!? !: !+ !@ !@ !- !) !* !e !e$ !* !+1+ !@ !( !3 !@ !* !* !d !f !: !+ !* !2 !$ != !g !2 !$ !@ != !g !1 !$ !@ !: !g !0 !: !: !: !: !:<0~!?g1*e e-10 ~!?g0-$0:-*e e0 0</
<|0!o? !@ !: !@ !: !- !1$ !i|!? !: !+ !@ !@ !- !) !* !e !e$ !* !+1+ !@ !( !3 !@ !* !* !d !f !: !+ !* !2 !$ != !g !2 !$ !@ != !g !1 !$ !@ !: !g !0 !: !: !: !: !:<0~!?g1*e e-10 ~!?g0-$0:-*e e0 0</
<|0!o? !@ !: !@ !: !- !1$ !i|!? !: !+ !@ !@ !- !) !* !e !e$ !* !+1+ !@ !( !3 !@ !* !* !d !f !: !+ !* !2 !$ != !g !2 !$ !@ != !g !1 !$ !@ !: !g !0 !: !: !: !: !:<0~!?g1*e e-10 ~!?g0-$0:-*e e0 0</

```

Try it online! Verification of perfect score (note times out)

The first zero score program. This is achieved by having three copies of the program on separate lines, with only non-irradiated versions being executed. The program checks for outliers (like newlines being removed), then checks each character to see if it is the same for all three lines. If one is different, we determine which line it is and offset the current index by a multiple of 195 (the length of each line). After determining which byte is irradiated (with no byte being `-1` and the first byte being `1`), we enter the output loop, decrementing the counter each time we output a character. When the counter hits zero, we skip that character, but don't reset the counter so it can be proven that only one byte of input is removed when the program is irradiated, and none when it is not.

The TIO link above has the program itself in the input, so it is easy to fiddle about in yourself. Simply try removing a byte from the program itself and the same byte will be removed from the output.

It shouldn't be too hard to golf, especially the loop in the middle that's just 60% no-ops, though I just want to post it since it is actually working and this isn't actually .

# Answer
> 14 votes
# sed, Perl 5 `-p`, Perl 6 `-p`, 6 bytes, score 5

```
#s/.//

```

Try it online!

Works as sed, Perl 5 and Perl 6 program. The 1st byte is removable.

# Answer
> 10 votes
# Jelly, 2 bytes, score = 1

```
ḷḊ

```

Try it online!

A full program that takes a string and prints a string. When the first byte is removed, removes the first byte of the input.

Achieving a lower score would mean finding a solution where removing *any* byte leads to the corresponding byte being removed from the string, which I think will be challenging.

## Explanation

```
ḷ  | Left argument of input string and:
 Ḋ | - Input string with first byte removed

```

With first byte removed:

```
Ḋ | Remove first byte

```

# Answer
> 7 votes
# Brainfuck, 11 bytes, score = 10

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

```

Try it online!

# Explanation

```
-+[,>]   This does nothing.
,[.,]    This reads and outputs the user's input until the program ends.

```

With first byte removed:

```
+[,>]    Reads the first character of user input, then 'discards' it by moving to a different cell.
,[.,]    This reads and outputs the user's input until the program ends.

```

# Answer
> 5 votes
# 05AB1E, score 2, 3 bytes

```
D¦r

```

Look ma, (sort of) no unicode!

The character to remove is the first one.

Try it online

Explanation:

```
D  push two copies of the input onto the stack
¦  remove the first character from the string on top of the stack. Alternatively, if D is removed, push the input with its first character removed onto the stack.
r  reverse the stack
implicitly, output the top of the stack

```

# Answer
> 5 votes
# , 93 bytes, score=87

```
T<-3.5->T;s=utf8ToInt(scan(,""));if(i<-match(2*T,c(0,-5,2,1,70,6,0,5),0))s=s[-i];intToUtf8(s)

```

Try it online!

Like Arnauld, I tried to get a few deletable bytes rather than optimize the score, and also to use different tricks depending on the byte removed. Characters 2, 3, 4, 5, 6 and 8 can be removed.

In the unaltered version, the code makes two attempts to assign a value to `T`, using both leftwards `<-` and rightwards `->` assignment. Since `T` is initialized as 1 (when coerced to integer), it can be assigned 7 different values, depending on the byte removed:

* `T<-3.5->T` leads to `T=3.5`
* `T-3.5->T` leads to `T=1-3.5=2.5`
* `T<3.5->T` leads to `T=1`, since `1<3.5` is true (the same would occur if we removed byte 7 - I searched for a way to have different behaviours when removing bytes 3 and 7 but couldn't manage)
* `T<-.5->T` leads to `T=.5`
* `T<-35->T` leads to `T=35`
* `T<-3.->T` leads to `T=3.`
* `T<-3.5-T` leads to `T=3.5-1=2.5`

The statement with `if` and `match` then removes the relevant character. The rest is the usual fluff required whenever R has to handle strings.

---

It is obviously possible to make the number `3.5` longer (e.g. `43.5`) and be allowed to remove the corresponding characters. For the sake of it, here is a different way of getting more removable characters:

# , 120 bytes, score=112

```
T<-3.5->T;s=utf8ToInt(scan(,""));if(i<-match(T+T,c(0,-5,2,1,70,6,0,5,rep(0,37),3.5,rep(0,47),-7),0))s=s[-i];intToUtf8(s)

```

Try it online!

In addition to the characters listed above, bytes 46 and 94 can be removed:

* byte 46: the first `T` in `T+T` becomes `+T`, which matches `3.5`
* byte 94: `-7` becomes `7`, which then matches `T+T=7`.

# Answer
> 5 votes
# Haskell, 31 - 1 = 30

*Removing the first byte works*

```
ss(x:b)=b
s x=x
main=interact s

```

Try it online!

## Explanation

In its default state this program defines two functions `ss` which is unused, and `s` which is the identity. It then declares that interaction is handled by `s`, making it a cat.

When we remove the first byte `ss` is renamed to `s`. Making it a special case of our function `s`, since this is the first declaration it takes highest precedence. So now `s` is defined such that if it can remove the first character it does so otherwise it falls back onto our old definition of `s`1 and becomes the identity. We still interact with `s` (although now modifed) so the entire program has the behavior of removing the first character if there is one.

---

1 This is important in the case of the empty string.

# Answer
> 4 votes
# Keg `-ir`, 3 bytes, score: 2

```
#_^

```

Try it online!

## Explanation

```
#_^ # A line comment
    # Copies the input to the output straightforwardly

```

```
    # Implicit reversed input
_   # Discard the first character in the string
 ^  # Reverse the stack

```

# Answer
> 4 votes
# 05AB1E, score 1, 2 bytes

Try it online!

First byte is removable.

# Answer
> 4 votes
# \[Python 3\], 9097 bytes, score 6

```
eEzfFzeEz=aAzcCzaAz=aAzbBz=bBzaAz=aAzcCz=eEzfFz=fFzaAz=eEzaAz=dDzaAz=exe=exc=xec=xecexec=aAz=aA=az=Az=aAz=fr='"1"#\nimport base64\n\ndef actual_source():\n\treturn open(eval("_"+"_file_"+"_") ).read()\n\ndef decode(s):\n\treturn str(base64.b64decode(s.replace("_", str() ) ), "utf-8" )\n\ndef encode(s):\n\ts=str(base64.b64encode(bytes(s, "utf-8") ),"utf-8")\n\tresult = str().join([cur if prev!=cur else "_"+cur for prev,cur in zip([None]+list(s),s)])\n\treturn result\n\ndef get_template():\n\treturn decode("aW1wb3J0IGJhc2U2NAoKZGVmIGFjdHVhbF9zb3VyY2UoKToKCXJldHVybiBvcGVuKGV2YWwoIl8iKyJfZmlsZV8iKyJfIikgKS5yZWFkKCkKCmRlZiBkZWNvZGUocyk6CglyZXR1cm4gc3RyKGJhc2U2NC5iNjRkZWNvZGUocy5yZXBsYWNlKCJfIiwgc3RyKCkgKSApLCAidXRmLTgiICkKCmRlZiBlbmNvZGUocyk6CglzPXN0cihiYXNlNjQuYjY0ZW5jb2RlKGJ5dGVzKHMsICJ1dGYtOCIpICksInV0Zi04IikKCXJlc3VsdCA9IHN0cigpLmpvaW4oW2N1ciBpZiBwcmV2IT1jdXIgZWxzZSAiXyIrY3VyIGZvciBwcmV2LGN1ciBpbiB6aXAoW05vbmVdK2xpc3QocykscyldKQoJcmV0dXJuIHJlc3VsdAoKZGVmIGdldF90ZW1wbGF0ZSgpOgoJcmV0dXJuIGRlY29kZSgiQjY0X0VOQ09ERURfUEFSVFMiKQoKZGVmIGdldF93cmFwZXIoKToKCXJldHVybiBkZWNvZGUoIldSQVAiKQoKZGVmIGdldF9wYXlsb2FkKCk6Cgl3cmFwZXIsIHRlbXBsYXRlID0gZ2V0X3dyYXBlcigpLCBnZXRfdGVtcGxhdGUoKQoJZW5fdGVtcGxhdGVfNjQgPSBlbmNvZGUodGVtcGxhdGUpCgl3cmFwZXJfNjQgPSBlbmNvZGUod3JhcGVyKQoJcmV0dXJuIHRlbXBsYXRlLnJlcGxhY2UoIkI2NF9FTkMiKyJPREVEX1B_BUlRTIiwgZW5fdGVtcGxhdGVfNjQpLnJlcGxhY2UoIldSIisiQVAiLCB3cmFwZXJfNjQpCgpkZWYgZ2V0X29yaWdpbmFsKCk6CglwYXlsb2FkID0gZ2V0X3BheWxvYWQoKQoJd3JhcGVyID0gZ2V0X3dyYXBlcigpCglyZXR1cm4gd3JhcGVyLnJlcGxhY2UoIjEyMyIsIHJlcHIocGF5bG9hZClbMTotMV0gKQoKZGVmIG1haW4ocyk6Cglmb3IgaSwgKGEsIGIpIGluIGVudW1lcmF0ZSg_gemlwKGdldF9vcmlnaW5hbCgpLCBhY3R1YWxfc291cmNlKCkgKSApOgoJCWlmIGEgIT0gYjoKCQkJcmV0dXJuIHNbOmldICsgc1tpICsgMTpdCglyZXR1cm4gcwoKaWYgbm90IChldmFsKCJfIisiX25hbWVfIisiXyIpICE9ICJfIisiX21haW5fIisiXyIpOgoJcHJpbnQobWFpbihpbnB1dCgpICkgKQ=_=")\n\ndef get_wraper():\n\treturn decode("ZUV6ZkZ6ZUV6PWFBemNDemFBej1hQXpiQno9YkJ6YUF6PWFBemNDej1lRXpmRno9ZkZ6YUF6PWVFemFBej1kRHphQXo9ZXhlPWV4Yz14ZWM9eGVjZXhlYz1hQXo9YUE9YXo9QXo9YUF6PWZyPSciMSIjXG4xMjMnIycjJwoxMjsKYkJ6PWJCPWJ6PUJ6PWJCej1mcj0nIjEiI1xuMTIzJyMnIycKMTI7CmNDej1jQz1jej1Dej1jQ3o9ZnI9JyIxIiNcbjEyMycjJyMnCjEyOwpleGU9ZXhjPXhlYz1leGVjCmREej1kRD1kej1Eej1kRHo9YUF6LGJCeixhQXo7CmVFemZGemVFej1nR3plRXo9YUF6Y0N6PWFBejxjQ3o7CmVFej1lRT1lej1Fej1lRXo9YUF6PGNDejsKZkZ6PWZGPWZ6PUZ6PWZGej1hQXo+Y0N6OwplRXpmRno9ZUV6fGZGejsKZ0d6PWdHPWd6PUd6PWdHej1lRXp8ZkZ6OwpleGVjKGREeltnR3pdKQ=_=")\n\ndef get_payload():\n\twraper, template = get_wraper(), get_template()\n\ten_template_64 = encode(template)\n\twraper_64 = encode(wraper)\n\treturn template.replace("B64_ENC"+"ODED_PARTS", en_template_64).replace("WR"+"AP", wraper_64)\n\ndef get_original():\n\tpayload = get_payload()\n\twraper = get_wraper()\n\treturn wraper.replace("123", repr(payload)[1:-1] )\n\ndef main(s):\n\tfor i, (a, b) in enumerate( zip(get_original(), actual_source() ) ):\n\t\tif a != b:\n\t\t\treturn s[:i] + s[i + 1:]\n\treturn s\n\nif not (eval("_"+"_name_"+"_") != "_"+"_main_"+"_"):\n\tprint(main(input() ) )'#'#'
12;
bBz=bB=bz=Bz=bBz=fr='"1"#\nimport base64\n\ndef actual_source():\n\treturn open(eval("_"+"_file_"+"_") ).read()\n\ndef decode(s):\n\treturn str(base64.b64decode(s.replace("_", str() ) ), "utf-8" )\n\ndef encode(s):\n\ts=str(base64.b64encode(bytes(s, "utf-8") ),"utf-8")\n\tresult = str().join([cur if prev!=cur else "_"+cur for prev,cur in zip([None]+list(s),s)])\n\treturn result\n\ndef get_template():\n\treturn decode("aW1wb3J0IGJhc2U2NAoKZGVmIGFjdHVhbF9zb3VyY2UoKToKCXJldHVybiBvcGVuKGV2YWwoIl8iKyJfZmlsZV8iKyJfIikgKS5yZWFkKCkKCmRlZiBkZWNvZGUocyk6CglyZXR1cm4gc3RyKGJhc2U2NC5iNjRkZWNvZGUocy5yZXBsYWNlKCJfIiwgc3RyKCkgKSApLCAidXRmLTgiICkKCmRlZiBlbmNvZGUocyk6CglzPXN0cihiYXNlNjQuYjY0ZW5jb2RlKGJ5dGVzKHMsICJ1dGYtOCIpICksInV0Zi04IikKCXJlc3VsdCA9IHN0cigpLmpvaW4oW2N1ciBpZiBwcmV2IT1jdXIgZWxzZSAiXyIrY3VyIGZvciBwcmV2LGN1ciBpbiB6aXAoW05vbmVdK2xpc3QocykscyldKQoJcmV0dXJuIHJlc3VsdAoKZGVmIGdldF90ZW1wbGF0ZSgpOgoJcmV0dXJuIGRlY29kZSgiQjY0X0VOQ09ERURfUEFSVFMiKQoKZGVmIGdldF93cmFwZXIoKToKCXJldHVybiBkZWNvZGUoIldSQVAiKQoKZGVmIGdldF9wYXlsb2FkKCk6Cgl3cmFwZXIsIHRlbXBsYXRlID0gZ2V0X3dyYXBlcigpLCBnZXRfdGVtcGxhdGUoKQoJZW5fdGVtcGxhdGVfNjQgPSBlbmNvZGUodGVtcGxhdGUpCgl3cmFwZXJfNjQgPSBlbmNvZGUod3JhcGVyKQoJcmV0dXJuIHRlbXBsYXRlLnJlcGxhY2UoIkI2NF9FTkMiKyJPREVEX1B_BUlRTIiwgZW5fdGVtcGxhdGVfNjQpLnJlcGxhY2UoIldSIisiQVAiLCB3cmFwZXJfNjQpCgpkZWYgZ2V0X29yaWdpbmFsKCk6CglwYXlsb2FkID0gZ2V0X3BheWxvYWQoKQoJd3JhcGVyID0gZ2V0X3dyYXBlcigpCglyZXR1cm4gd3JhcGVyLnJlcGxhY2UoIjEyMyIsIHJlcHIocGF5bG9hZClbMTotMV0gKQoKZGVmIG1haW4ocyk6Cglmb3IgaSwgKGEsIGIpIGluIGVudW1lcmF0ZSg_gemlwKGdldF9vcmlnaW5hbCgpLCBhY3R1YWxfc291cmNlKCkgKSApOgoJCWlmIGEgIT0gYjoKCQkJcmV0dXJuIHNbOmldICsgc1tpICsgMTpdCglyZXR1cm4gcwoKaWYgbm90IChldmFsKCJfIisiX25hbWVfIisiXyIpICE9ICJfIisiX21haW5fIisiXyIpOgoJcHJpbnQobWFpbihpbnB1dCgpICkgKQ=_=")\n\ndef get_wraper():\n\treturn decode("ZUV6ZkZ6ZUV6PWFBemNDemFBej1hQXpiQno9YkJ6YUF6PWFBemNDej1lRXpmRno9ZkZ6YUF6PWVFemFBej1kRHphQXo9ZXhlPWV4Yz14ZWM9eGVjZXhlYz1hQXo9YUE9YXo9QXo9YUF6PWZyPSciMSIjXG4xMjMnIycjJwoxMjsKYkJ6PWJCPWJ6PUJ6PWJCej1mcj0nIjEiI1xuMTIzJyMnIycKMTI7CmNDej1jQz1jej1Dej1jQ3o9ZnI9JyIxIiNcbjEyMycjJyMnCjEyOwpleGU9ZXhjPXhlYz1leGVjCmREej1kRD1kej1Eej1kRHo9YUF6LGJCeixhQXo7CmVFemZGemVFej1nR3plRXo9YUF6Y0N6PWFBejxjQ3o7CmVFej1lRT1lej1Fej1lRXo9YUF6PGNDejsKZkZ6PWZGPWZ6PUZ6PWZGej1hQXo+Y0N6OwplRXpmRno9ZUV6fGZGejsKZ0d6PWdHPWd6PUd6PWdHej1lRXp8ZkZ6OwpleGVjKGREeltnR3pdKQ=_=")\n\ndef get_payload():\n\twraper, template = get_wraper(), get_template()\n\ten_template_64 = encode(template)\n\twraper_64 = encode(wraper)\n\treturn template.replace("B64_ENC"+"ODED_PARTS", en_template_64).replace("WR"+"AP", wraper_64)\n\ndef get_original():\n\tpayload = get_payload()\n\twraper = get_wraper()\n\treturn wraper.replace("123", repr(payload)[1:-1] )\n\ndef main(s):\n\tfor i, (a, b) in enumerate( zip(get_original(), actual_source() ) ):\n\t\tif a != b:\n\t\t\treturn s[:i] + s[i + 1:]\n\treturn s\n\nif not (eval("_"+"_name_"+"_") != "_"+"_main_"+"_"):\n\tprint(main(input() ) )'#'#'
12;
cCz=cC=cz=Cz=cCz=fr='"1"#\nimport base64\n\ndef actual_source():\n\treturn open(eval("_"+"_file_"+"_") ).read()\n\ndef decode(s):\n\treturn str(base64.b64decode(s.replace("_", str() ) ), "utf-8" )\n\ndef encode(s):\n\ts=str(base64.b64encode(bytes(s, "utf-8") ),"utf-8")\n\tresult = str().join([cur if prev!=cur else "_"+cur for prev,cur in zip([None]+list(s),s)])\n\treturn result\n\ndef get_template():\n\treturn decode("aW1wb3J0IGJhc2U2NAoKZGVmIGFjdHVhbF9zb3VyY2UoKToKCXJldHVybiBvcGVuKGV2YWwoIl8iKyJfZmlsZV8iKyJfIikgKS5yZWFkKCkKCmRlZiBkZWNvZGUocyk6CglyZXR1cm4gc3RyKGJhc2U2NC5iNjRkZWNvZGUocy5yZXBsYWNlKCJfIiwgc3RyKCkgKSApLCAidXRmLTgiICkKCmRlZiBlbmNvZGUocyk6CglzPXN0cihiYXNlNjQuYjY0ZW5jb2RlKGJ5dGVzKHMsICJ1dGYtOCIpICksInV0Zi04IikKCXJlc3VsdCA9IHN0cigpLmpvaW4oW2N1ciBpZiBwcmV2IT1jdXIgZWxzZSAiXyIrY3VyIGZvciBwcmV2LGN1ciBpbiB6aXAoW05vbmVdK2xpc3QocykscyldKQoJcmV0dXJuIHJlc3VsdAoKZGVmIGdldF90ZW1wbGF0ZSgpOgoJcmV0dXJuIGRlY29kZSgiQjY0X0VOQ09ERURfUEFSVFMiKQoKZGVmIGdldF93cmFwZXIoKToKCXJldHVybiBkZWNvZGUoIldSQVAiKQoKZGVmIGdldF9wYXlsb2FkKCk6Cgl3cmFwZXIsIHRlbXBsYXRlID0gZ2V0X3dyYXBlcigpLCBnZXRfdGVtcGxhdGUoKQoJZW5fdGVtcGxhdGVfNjQgPSBlbmNvZGUodGVtcGxhdGUpCgl3cmFwZXJfNjQgPSBlbmNvZGUod3JhcGVyKQoJcmV0dXJuIHRlbXBsYXRlLnJlcGxhY2UoIkI2NF9FTkMiKyJPREVEX1B_BUlRTIiwgZW5fdGVtcGxhdGVfNjQpLnJlcGxhY2UoIldSIisiQVAiLCB3cmFwZXJfNjQpCgpkZWYgZ2V0X29yaWdpbmFsKCk6CglwYXlsb2FkID0gZ2V0X3BheWxvYWQoKQoJd3JhcGVyID0gZ2V0X3dyYXBlcigpCglyZXR1cm4gd3JhcGVyLnJlcGxhY2UoIjEyMyIsIHJlcHIocGF5bG9hZClbMTotMV0gKQoKZGVmIG1haW4ocyk6Cglmb3IgaSwgKGEsIGIpIGluIGVudW1lcmF0ZSg_gemlwKGdldF9vcmlnaW5hbCgpLCBhY3R1YWxfc291cmNlKCkgKSApOgoJCWlmIGEgIT0gYjoKCQkJcmV0dXJuIHNbOmldICsgc1tpICsgMTpdCglyZXR1cm4gcwoKaWYgbm90IChldmFsKCJfIisiX25hbWVfIisiXyIpICE9ICJfIisiX21haW5fIisiXyIpOgoJcHJpbnQobWFpbihpbnB1dCgpICkgKQ=_=")\n\ndef get_wraper():\n\treturn decode("ZUV6ZkZ6ZUV6PWFBemNDemFBej1hQXpiQno9YkJ6YUF6PWFBemNDej1lRXpmRno9ZkZ6YUF6PWVFemFBej1kRHphQXo9ZXhlPWV4Yz14ZWM9eGVjZXhlYz1hQXo9YUE9YXo9QXo9YUF6PWZyPSciMSIjXG4xMjMnIycjJwoxMjsKYkJ6PWJCPWJ6PUJ6PWJCej1mcj0nIjEiI1xuMTIzJyMnIycKMTI7CmNDej1jQz1jej1Dej1jQ3o9ZnI9JyIxIiNcbjEyMycjJyMnCjEyOwpleGU9ZXhjPXhlYz1leGVjCmREej1kRD1kej1Eej1kRHo9YUF6LGJCeixhQXo7CmVFemZGemVFej1nR3plRXo9YUF6Y0N6PWFBejxjQ3o7CmVFej1lRT1lej1Fej1lRXo9YUF6PGNDejsKZkZ6PWZGPWZ6PUZ6PWZGej1hQXo+Y0N6OwplRXpmRno9ZUV6fGZGejsKZ0d6PWdHPWd6PUd6PWdHej1lRXp8ZkZ6OwpleGVjKGREeltnR3pdKQ=_=")\n\ndef get_payload():\n\twraper, template = get_wraper(), get_template()\n\ten_template_64 = encode(template)\n\twraper_64 = encode(wraper)\n\treturn template.replace("B64_ENC"+"ODED_PARTS", en_template_64).replace("WR"+"AP", wraper_64)\n\ndef get_original():\n\tpayload = get_payload()\n\twraper = get_wraper()\n\treturn wraper.replace("123", repr(payload)[1:-1] )\n\ndef main(s):\n\tfor i, (a, b) in enumerate( zip(get_original(), actual_source() ) ):\n\t\tif a != b:\n\t\t\treturn s[:i] + s[i + 1:]\n\treturn s\n\nif not (eval("_"+"_name_"+"_") != "_"+"_main_"+"_"):\n\tprint(main(input() ) )'#'#'
12;
exe=exc=xec=exec
dDz=dD=dz=Dz=dDz=aAz,bBz,aAz;
eEzfFzeEz=gGzeEz=aAzcCz=aAz<cCz;
eEz=eE=ez=Ez=eEz=aAz<cCz;
fFz=fF=fz=Fz=fFz=aAz>cCz;
eEzfFz=eEz|fFz;
gGz=gG=gz=Gz=gGz=eEz|fFz;
exec(dDz[gGz])

```

This program has the general structure

```
a="payload"
b="payload"
c="payload"
exec([a,b][b==c])

```

where "payload" is the program we want to execute. The comparison in the `exec` call makes sure that we run an unmodified copy of the payload. Within the payload, we open the source of `__file__` and compare it to the unmodified source (which is determined using a quine). This gives us the information we need to delete the correct character from the output.

The base64 encoded segments are the inputs used when making the quine. They are base64 encoded to avoid needing to escape nested quotes. The program is written so that it has no repeating characters, allowing almost any deletion to be detected.

### The 6 characters that can't be deleted are:

* The parentheses and brackets in the last line (`([])`), as deleting them will cause a syntax error.
* The `x` in both instances of `exec`, as this produces the variable `eec` which is not defined.

If I did define `eec`, I would introduce a pair of duplicated characters, and would not be able to distinguish between those deletions. If the challenge cared about deletions of *characters* instead of *bytes* then I could define `eᵉc` in the appropriate places to reduce the score to 4.

### Radiation Resistance tricks

`eEzfFzeEz=aAzcCzaAz=...` This line defines all the variables that the program could later try to read, to avoid crashing with a NameError.

`bBz=bB=bz=Bz=bBz=` when I want to be able to read a value, I define it (`bBz`) twice, and also define the mangled versions of it once each. When the variable is later accessed, at least one of the original definitions was undamaged, and damaging the later access will result in reading one of the shortened versions of the variable. No variable shorter than 2 characters is used as deleting a single variable would cause

`bBz=fr='"1"#\n` This acts as a no-op when the payload is executed, and results in any radiation to the start of the string merely storing a bad value in `bBz`.

* If the single quote is deleted, `"1"` is assigned, and the rest of the string is commented out.
* If the last `=` is deleted, the string becomes a raw format string, but is still valid syntax.
* Other deletions mangle some variable names, but redundant assignment fixes this.

At the end of the strings `'#'#'` is used. As written this is the end of one string followed by a comment. If the first `'` is removed, it the next `#'` become part of the string, and the remaining 2 characters become a comment. If the first `#` is removed, then the program has 2 strings in a row, so they are concatenated. Damage to the last 2 characters is just a change to the comment text.

`12;` and `;` are added to allow the deletion of newlines to join statements without issue.

`dDz=aAz,bBz,aAz;` This line stores the A and B in a tuple. If either comma is deleted, we still store a tuple of size two. The 3rd tuple element will never be accessed. Deleting the `=` has no effect, as `dDzaAz` was initialized to the same value as `aAz`.

`a != c` is converted to `e = a<c; f = a>c; g = e|f` so that characters in the comparison operator can be deleted without crashing the program. Then redundant comparisons are added so that damaging any one of the comparisons produces the right result.

`exec(dDz[gGz])` we can execute a known-good payload by indexing into a tuple.

# Answer
> 3 votes
# Python 3, 33 - 1 = 32 bytes

The removable byte is the 23rd one (`~`).

```
x=input();print(x[:22-~0]+x[23:])

```

Try it online!

This sort of evolved out of Arnauld's answer, but only seeks to get one removable character.

## Explanation

In python `~` is a "bitwise not", which basically subtracts the value from 1. So `~0` is equivalent to `-1`. This makes `22-~0` the same as `23`. So normally our program takes everything up to the 23rd character and then adds everything after. However when we remove the `~` `22-~0` becomes `22-0` equivalent to `22`. This makes us take the first *22* characters and everything after the 23rd, skipping the 23rd character.

# Answer
> 3 votes
# Shakespeare Programming Language, 236 bytes, score 235

-16 bytes thanks to Jo King.

New lines added for readability. Byte 196 can be removed. Exits with error but the output is correct.

```
,.Ajax,.Page,.
Act I:.Scene I:.
[Exeunt][Enter Ajax and Page]
Ajax:Open mind.
Page:You be the sum ofyou a cat.
     Be you as big as the square ofthe sum ofa big big big big cat a big pig?
     If soLet usScene VI.

Scene VI:.
Ajax:Speak mind.Let usAct I.

```

Try it online!

Page reads bytes from input and outputs them, one at a time. Ajax is a counter indicating how many bytes have been read. Page's `if` statement tests `Ajax == 196`. In the basic version, the `if` statement is useless: in all cases, we proceed to Scene VI. If byte 196 has been removed, the statement becomes `If soLet usScene I.` so we skip Scene VI and the corresponding input does not get output.

This uses the fact that SPL doesn't require scenes to use consecutive numbers.

Looking for other strategies, I checked all the words allowed in SPL: the only useful pair of words which are one deletion apart is `Helen`/`Helena`, which are both legal characters. I might try to use this to get a solution where two different bytes can be removed.

# Answer
> 2 votes
# Charcoal, 6 bytes, score 5

```
ΦＳ⁻κ±⁴

```

Try it online! Explanation:

```
 Ｓ      Input string
Φ       Filtered
   κ    Current index
  ⁻     Subtract
     ⁴  Literal `4`
    ±   Negated

```

Since adding 4 to the index is always a truthy result, this is a cat program. Removing the `±` at index `4` results in the following program:

```
ΦＳ⁻κ⁴

```

Try it online! It deletes the character at index `4` (0-indexed).

# Answer
> 2 votes
# C (gcc), ~~54~~ 53 bytes, score ~~52~~ 51

Bytes 27 or 28 (from the first `++c`), or both, may be removed.

**Explanation:**

There is a counter that increments by 2 each iteration (one in the loop condition, one in the body) in the unmodified program, but removing one of the `+`s turns the first increment into a no-op. As the only way to get an odd number is in the modified program, only it will remove the 27th byte. Both bytes can be removed because `+c` is the same as `c`.

```
c;main(a){for(;a=~getchar(++c);)++c-27&&putchar(~a);}

```

Try it online!

# Answer
> 1 votes
# GNU Sed 7 bytes, score=6

Full program

`b;s/.//`

Program with first byte removed

`;s/.//`

Input is a printable ASCII string, with no newlines.

# Answer
> 1 votes
# JavaScript, 52 bytes, score 51

The 37th byte, `1`, is removable.

```
s=prompt()
console.log(s.slice(0,36+01)+s.slice(37))
```

---

# JavaScript, 56 bytes, score 55

The 24th byte, `1`, is removable.

```
s=prompt()
console.log(01?s:s.replace(/^(.{24})./,'$1'))
```

# Answer
> 1 votes
# Symbolic Python, 11 bytes, score 10

```
__=_[_==_:]

```

Try it online!

The first `_` is removable. Basically, the program sets `__` to the input without the first character, which doesn't affect the IO variable `_`, so it outputs what is inputted. If you remove the `_`. it does set the variable, so the first character is removed. Try it online!

# Answer
> 1 votes
# , 14 - 1 = 13 bytes

```
1(]}.~1-1-:[)]

```

Try it online!

Removing the first byte works.

# how

* `1(...)]` A fork with the constant `1` as the left tine and the input as the right `]`.
* `(]}.~1-1-:[)` One minus `1-` the value "does the input equal the left fork tine?" `1-:[`.
    + This will always be 0 in the unaltered program.
    + It will always be 1 in the program-with-byte1-removed. No string matches the integer `1`.
    + This works because removing that first `1` turns the fork into a hook, which is like a fork whose left tine is the original input.
* `]}.~` Remove from the beginning `}.~` of the original input `]` that number of characters -- ie, the 1 or 0 calculated in the previous step.

# Answer
> 1 votes
# Vyxal, score 1

```
,Ḣ

```

Try it Online!

```
,  # Print
 Ḣ # Remove first character, ignored

Ḣ  # Remove first character, implicitly printed

```

# Answer
> 0 votes
# Pyth, 2 bytes - Score: 1

```
&t

```

Try it online!

This implicitly expands to: `imp_print((tail(Q) and Q))`
Removing the '&' let's the tail function print (All but the first element)

# Answer
> 0 votes
# Python 3, score = 27, 262 bytes

```
x="a,b=sorted(x,key=len);d=[3,123][x!=(a,b)];n=sum(i is j for i,j in zip(a,b) );s=input();print(s[:d+n]+s[d+n+(a!=b):]) ","a,b=sorted(x,key=len);d=[3,123][x!=(a,b)];n=sum(i is j for i,j in zip(a,b) );s=input();print(s[:d+n]+s[d+n+(a!=b):]) "
exec(max(x,key=len))

```

Try it online!

redundancy is good

---
Tags: code-challenge, source-layout, radiation-hardening, self-referential
---


title: Implement Casio's M

text:
# Question
Title: Implement Casio's M
## The task

Most Casio calculators featured a variable `M`, which has 3 operators related to it: `M`, `M+`, and `M-`

`M`, as you can expect, returns the value stored in the variable.

`M+` takes the number on the left and add it to `M`.

`M-` does the same thing as `M+`, but subtract instead.

To make the challenge just a bit more difficult, we will add an extra operator: `MR`, which is short for `Memory reset`. As you can guess from the name, it resets the variable `M` back to 0.

Your task is to parse a string of Casio `M` expression, then print the value of `M`.

Here's an example:

```
9M+9M+

```

Here, we add `9` to variable `M` twice, so the output will be `18`.

## Specifications

* `M` will be `0` when first initialized
* For this challenge, you don't need to handle basic arithmetics, just those operators.
* However, you do need to handle implicit multiplications, so `9M` will become `81` for `M = 9`
* If the expression given is invalid, you can return any value of your choice
* `M+` and `M-` must not have an operator behind them (except for `M`), so cases like `MRM+` and `9M+M+` are invalid, but `9M+MM+` is valid.

## Input/Output

The input should be a string and the output is either the variable `M` or an invalid value of your choice.

## Testcases

```
Input -> Output
9M+9M+ -> 18
9MR9M+ -> 9
9M+MM+ -> 18
9M-9M-9M+ -> -9
9M+MMM+ -> 90
81M+81M+56M-35M-12M+ -> 83
9M+MRM+ -> Invalid
9M+M+  -> Invalid
9 -> 0 (Explanation: does not modify M with an operator)
9M+MM -> 9 (Same as the above test case)
2M+2M2MM+ -> 18

```

# Answer
# Python3, 287 bytes:

```
import re
R=re.findall
V=lambda m,x,k=1:k if[]==x else V(m,x[1:],k*(int(x[0])if x[0].isdigit()else m))
E=lambda x,M=0:M if[]==x else E(x[1:],M+[-1,1][x[0][1][-1]!='-']*V(M,R('\d+|M',x[0][0]))*(x[0][1]!='MR'))
f=lambda x:''.join(map(''.join,k:=R('([M\d]+)(M(?:\-|\+)|MR)',x)))==x and E(k)

```

Try it online!
> 5 votes

# Answer
# Python, ~~172~~ ~~179~~ ~~174~~ ~~169~~ ~~164~~ ~~156~~ 153 bytes

```
def f(x,M=0):
 try:exec(s("M(?=\d|M)","M*",s("(\d|M)M","\\1*M",s("R=","*=0M",s("(.*?)(M[-+R])",r"\2=\1;",x))))+"\nprint(M)")
 except:0
import re
s=re.sub

```

Attempt This Online!

-3 bytes thanks to @The Thonnu

---

# Python, ~~148~~ ~~155~~ ~~150~~ ~~145~~ ~~140~~ 137 bytes

```
lambda x,M=0:exec(s("M(?=\d|M)","M*",s("(\d|M)M","\\1*M",s("R=","*=0M",s("(.*?)(M[-+R])",r"\2=\1;",x))))+"\nprint(M)")
import re
s=re.sub

```

Attempt This Online!

Shorter version which throws an error for invalid expressions.

+7 bytes to both versions due to bug in code.
> 4 votes

# Answer
# Retina, 248 bytes

```
\d+|M
¶$&
\d+
*
{`^(.*)¶(_*¶)?MR|^.*¶M[-+](¶.*)*

+`^(.*)(¶-?_*¶?)M(?!.)
$1$2$1
^(.*¶-?)(_*)¶(-?)(_*)(?!.)
$1$3$.2*$4
--

^(.*)¶(.*)¶M([-+])
$1$3$2
\+-
-
--
+
^(_*)\+|^(-_*)-|^-(_*)\+\3|^(-_*?)(_*)\+\5
$1$2$4
)`(_+)-\1(\B)?
$#2*-
L$`^(-?)(_*)
$1$.2

```

Try it online! Link includes test cases. Explanation:

```
\d+|M
¶$&

```

Insert newlines before each number or memory operation. The newline before the very first operation serves to set the initial memory to zero.

```
\d+
*

```

Convert all the numbers to unary.

```
{`
)`

```

Repeat until all of the numbers and memory operations have been processed.

```
^(.*)¶(_*¶)?MR|^.*¶M[-+](¶.*)*

```

`MR` will reset just the memory and `M-` or `M+` in an invalid place will clear everything resulting in an output of zero.

```
+`^(.*)(¶-?_*¶?)M(?!.)
$1$2$1

```

`M` either immediately after an `MR`, `M-` or `M+`, or with a number in between, will read the memory.

```
^(.*¶-?)(_*)¶(-?)(_*)(?!.)
$1$3$.2*$4
--

```

Two values (at least one of which will have been the result of a memory read) will multiply together.

```
^(.*)¶(.*)¶M([-+])
$1$3$2
\+-
-
--
+
^(_*)\+|^(-_*)-|^-(_*)\+\3|^(-_*?)(_*)\+\5
$1$2$4
(_+)-\1(\B)?
$#2*-

```

`M+` and `M-` after the value will add it to or subtract it from the memory.

```
L$`^(-?)(_*)
$1$.2

```

Convert the final memory to decimal, ignoring any pending value.
> 3 votes

# Answer
# Charcoal, ~~78~~ 72 bytes

```
≔¹ηＦ⪪⁺RθM«¿⊙ι№-+Rκ«≡§ι⁰-¿υ≧⁻Πυζ≔⁰η+¿υ≧⁺Πυζ≔⁰η≔⁰ζ≔⟦⟧υ≔Φιλι»⊞υζ¿ι⊞υＩι»¿ηＩζ

```

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

```
≔¹η

```

Start by assuming the expression is valid.

```
Ｆ⪪⁺RθM«

```

Split the input on `M` and loop over the parts, however prefix an `R` to the first part to get a free memory reset.

```
¿⊙ι№-+Rκ«

```

If this part contains a `-`, `+` or `R`, then:

```
≡§ι⁰

```

Switch over the first character in the part.

```
-¿υ≧⁻Πυζ≔⁰η

```

If it's a `-` then subtract the product of the stack from the memory, but if the stack is empty then mark the expression as invalid.

```
+¿υ≧⁺Πυζ≔⁰η

```

Similarly for `+`.

```
≔⁰ζ

```

Otherwise, this is an `R`, so clear the memory.

```
≔⟦⟧υ

```

Clear the stack.

```
≔Φιλι

```

Remove the leading character from the part.

```
»⊞υζ

```

Otherwise, push the memory to the stack.

```
¿ι⊞υＩι

```

If the part isn't empty then push its value to the stack.

```
»¿ηＩζ

```

If the expression was valid then output the memory.
> 3 votes

# Answer
# 05AB1E, ~~52~~ 47 bytes

```
0U…+-RS©D¶«.:¶¡ε®'Mì„X+…Xs-‚…)\0ª'U«:'M„XP:.V}X

```

Try it online or verify all test cases.

**Explanation:**"

```
0U            # Set variable `X` to 0 (it's 1 by default)
…+-RSD¶«.:¶¡  # Split the (implicit) input after each "+"/"-"/"R":
…+-RS         #  Push triplet ["+","-","R"]
     ©        #  Store it in variable `®` (without popping)
      D       #  Duplicate it
       ¶«     #  Append a newline to the values in the pair
         .:   #  Replace all "+"/"-"/"R" with "+\n"/"-\n"/"R\n" respectively in the
              #  (implicit) input
           ¶¡ #  Then split on newlines
ε             # Map over each substring:
              # (used as a foreach, where all will have their own separated stack):
 ®            #  Push triplet ["+","-","R"] from variable `®`
  'Mì        '#  Prepend an "M" in front of each
 „X+          #  Push string "X+"
     ‚        #  Pair it with
 …Xs-         #  String "Xs-"
     ª        #  And also append
 …)\0         #  String ")\0"
      'U«    '#  Append an "U" after all three: ["X+U","Xs-U",")\0U"]
 :            #  Replace all "M+"/"M-"/"MR" with "X+U"/"Xs-U"/")\0U" respectively
 'M„XP:      '#  Then replace all remaining "M" with "XP"
 .V           #  Execute it as 05AB1E code (see below)
}X            # After the map: push value `X`
              # (which is output implicitly as result)

```

```
)\0U          # MR:
)             #  Wrap the entire stack into a list
 \            #  Discard it
  0U          #  Reset `X` to 0

X+U           # M+:
X+            #  Add `X` to the top value
  U           #  Pop and store it as new value `X`

Xs-U          # M-:
X             #  Push `X`
 s            #  Wrap the top two values on the stack
  -           #  Subtract the value from `X`
   U          #  Pop and store it as new value `X`

XP            # Remaining M:
X             #  Push value `X`
 P            #  Get the product of all values on the stack (for the current group)

```
> 3 votes

# Answer
# Vyxal `D`, 40 bytes

```
⁽±ḊƛǍ[f;f(nw‛MR‛¥⁼½dĿ÷Ė‟n±ß¥£!3=ß*)¥D⌊=*

```

Test suite. Returns blank in the case of an invalid expression.

**Explanation:**

```
⁽±Ḋ                                      # group digits and non-digits together, preserving order
   ƛǍ[f;                                 # split into list of chars for non-digit items
        f                                # flattened
         (                        )      # for each item:
          nw                             #  item, wrapped in a single list
            ‛MR                          #  literal "MR"
               ‛¥⁼½d                     #  list ["¥¥","⁼⁼"] (D flag: do not decompress string)
                    Ŀ                    #  transliterate
                     ÷Ė                  #  unwrap and execute the item:
                                         #    M: push register twice
                                         #    R: always 0, also makes stack length to 1
                                         #    + & -: add and subtract respectively
                                         #      concatenates with input if stack is insufficient
                                         #    <number>: push <number> as int
                       ‟                 #  rotate the item to the back of stack
                        n±ß¥             #  if the current item is numeric, push register
                                         #    (preventing the number from being stored)
                            £            #  store to register
                             !3=ß*       #  if stack length == 3, multiply
                                   ¥     # push register
                                    D⌊=* # multiply depending on being an integer
                                         # implicit output

```
> 3 votes

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

```
s=>eval(s.replace(/\d+|M[-+R]?/g,b=>`_${c?"*":""}=${b<":"?(d=c++,b):d&&b[1]?"m=``//":`m${(d=b[1])||";a"}=_;${c=!d,b>"M-"&&"m=0"}`};`,m=c=d=0)+"m")

```

Try it online!

Creates a program based on the input and then evaluates it. Returns the empty string for invalid inputs. My favorite aspect of this solution is using `b<":"` to separate numeric strings from the other kinds of strings that can appear here.

---

# JavaScript (Node.js), 138 bytes

```
s=>eval(s.replace(/\d+|M[-+R]?/g,b=>`_${c?"*":""}=${b<":"?(d=c++,b):d&&b[1]||`m${(d=b[1])||";a"}=_;${c=!d,b>"M-"&&"m=0"}`};`,m=c=d=0)+"m")

```

Try it online!

Similar to @Mukundan314's reasoning, this version throws an error instead of returning a specific value.
> 2 votes

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


title: Next number with k fives

text:
# Question
Title: Next number with k fives
### Challenge:

Your program will take two integers `n` and `k` as input, and output the smallest integer greater than (but not equal to) `n` that contains at least `k` occurrences of the digit `5`.

You can assume `1 ≤ k ≤ 15` and `1 ≤ n < 10**15`.

This is a challenge. Your program must run on TIO for all of the test cases and complete within 10 seconds in total.

## General rules:

* This is , so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for *any* programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. The function parameters may be taken in either order, but please specify in your answer.
* Default Loopholes are forbidden.
* You must add a link with a test for your code (i.e. TIO).
* The answer header should list the score in bytes but also the total time taken for all test cases on TIO
* If your language is not on TIO, the code should finish far under 10 seconds on your machine so that you're confident it's fast enough on any reasonable computer.
* Adding an explanation for your answer is highly recommended.

### Test Cases:

```
(n, k) ->  output
(53, 2) -> 55
(55, 1) -> 56
(65, 1) -> 75
(99, 1) -> 105
(555, 3) -> 1555
(557, 1) -> 558
(5559, 3) -> 5565
(6339757858743, 5) -> 6339757859555
(99999999999999, 15) -> 555555555555555

```

### Program Example:

This program is correct.

# Answer
> 6 votes
# , ~~85~~ ~~84~~ ~~76~~ 74 bytes, 0.250s on TIO

```
f=function(n,k,m=nchar(gsub("[^5]","",n+1))-k)`if`(m<0,f(n+.1^m/50,k),n+1)

```

Try it online!

-1 byte thanks to Robert S.
-8 bytes thanks to Giuseppe.

The `nchar(gsub(...))` part counts the number of `5`s.

A simple recursive solution would be to increment by 1 until the answer is found, but this would not meet the time restriction. To meet the time restriction, this function makes use of the fact that if there are p missing 5s, we can increment by `2*10^(p-2)` (represented as the golfier `.1^m/50`, with `m=-p`).

Note that when p=1, the increment becomes 0.2. This is OK, since after 5 steps we come back to an integer, and none of the decimal numbers encountered in the mean time have an extra 5. If instead we were to increment by `5*10^(p-2)` or by `1*10^(p-2)`, then we would find f(24, 1)=24.5 instead of 25 for example.

# Answer
> 3 votes
# Jelly, 37 bytes 0.113 s on TIO

```
»DL‘Ɗ}©5xḌ_DḌÐƤ;®ŻṬ€UḌ¤+⁹D=5S>ʋƇ⁸’¤ḟṂ

```

Try it online!

This works by

1. working out the maximum of the number of digits in the input plus one and `k`, and making a number with that many fives
2. Subtracting the input from that number
3. Generating all of the suffixes of that number
4. Also generating all the powers of ten from 1 up to the next one greater than the input
5. Adds each of the numbers in 3 and 4 to the input
6. Removes answers with too few 5’s
7. Filters out the input from the answers
8. And returns the minimum

# Answer
> 2 votes
# 05AB1E, ~~33~~ ~~32~~ 31 bytes

```
sg>‚à©5s×α.s0š®Ý°0šâO+IKʒ5¢¹@}ß

```

Port of *@NickKennedy*'s amazing approach in his Jelly answer, so make sure to upvote him!!

Takes \\$k\\$ as first input; \\$n\\$ as second.

Try it online or verify all test cases.

**Explanation:**

```
sg>                # Get the length+1 of the second (implicit) input-integer
   ‚à              # Pair it with the first input-integer, and leave the maximum
     ©             # Store this maximum in the register (without popping)
      5s×          # Create an integer (actually, create a string..) with that many 5s
         α         # Take the absolute difference with the second (implicit) input
          .s       # Get the prefixes of that number
            0ª     # Prepended with an additional 0
    ®              # Get the maximum from the register again
     Ý             # Create a list in the range [0, max]
      °            # Raise 10 to the power of each integer
       0ª          # And also prepend an additional 0 to this list
              â    # Then create each possible pair of these two lists
               O   # Sum each pair
                +  # Add the second input to each sum
IK                 # Then remove the second input from this list (if present)
  ʒ                # And filter this list by:
   5¢              #  Count the amount of 5s in the integer
     ¹@            #  And check if this count is larger than or equal to the first input
       }ß          # After the filter: only leave the lowest number
                   # (which is output implicitly as result)

```

# Answer
> 2 votes
# Stax, 17 bytes (6.861 total seconds on TIO)

```
≈ª╞¥é£ôñτ←╝α┴╢JLd

```

Run and debug it

This program takes `k` and `n` on standard input separated by space. Stax doesn't have a convenient way to run multiple test cases on TIO, so I ran each input separately and added up the time. 99% of the time is in the interpreter process startup. Using the javascript interpreter on staxlang.xyz, all test cases run in 50 milliseconds.

Last test case on Try it online!

**Procedure**:

1. Increment input
2. If there are enough `5`s, terminate and print
3. `t`= number of trailing `5`s in the number
4. Add `10 ** t`
5. Goto 2

# Answer
> 1 votes
# Python 3, ~~144~~ ~~98~~ ~~86~~ 75 bytes

```
f=lambda N,k,d=1:k>str(-~N).count("5")and f(N+-(-~N//d+5)%10*d,k,d*10)or-~N

```

Try it online!

This is \\$\mathcal{O}(k)\\$, (system time .008 on TIO) and has golfed well with some advice from ASCII-only.

The algorithm is to round up each digit (starting from the least-significant one) to the nearest value of 5 until the new number's decimal representation has the desired count.

The original approach used an abortable (D=iter(range(k)) and list(D) at work here) list comprehension, but @ASCII-only has convinced me that will never win code-golf. I dislike recursion, but if the algorithm is written to minimize recursion-depth, then a future compiler/interpreter will be smart enough to re-implement it as a while loop.

# Answer
> 1 votes
# Perl 5 `-pl`, 44 bytes

```
$k=<>;$_++;s/.*?(?=5*$)/1+$&/e while$k>y/5//

```

Try it online!

Finds what the number is without its trailing 5s. Increments that portion by 1. Continues until sufficient 5s are in the number. Takes about .012s on TIO to run all test cases.

# Answer
> 0 votes
# PHP, ~~109~~ 97 bytes, (\< 0.03s on TIO)

```
function($n,$k){++$n;do if(count_chars($n)[53]>=$k)return$n;while($n+=10**strspn(strrev($n),5));}

```

Try it online!

Based on @recursive's algorithm.

# Answer
> 0 votes
# Retina, 63 bytes

```
.+$
*
^.+
$.(*__
/((5)|.)+¶(?<-2>_)+$/^+`^.*?(?=5*¶)
$.(*__
1G`

```

Try it online! Takes `n` and `k` on separate lines, but link includes header that converts the test suite into the appropriate format. Explanation:

```
.+$
*

```

Convert `k` to unary.

```
^.+
$.(*__

```

Increment `n`. The `*` repeats its right argument (here the first `_` character) the number of times given by its left argument (which, as here, defaults to the match). This results in a string of that length. The `$(` (the `)` is implied) then concatenates that with the second `_` and the `.` causes the resulting length to be taken. (Actually Retina 1 is cleverer than that and just performs the calculation on the underlying lengths in the first place.)

```
/((5)|.)+¶(?<-2>_)+$/

```

Test whether enough `5`s can be found in `n` to match the `_`s of the unary representation of `k`. This test has been golfed and would be three times faster with `^` added after the initial `/` and faster still if `[^5]` was used instead of `.`.

```
^+`

```

Until the test passes...

```
^.*?(?=5*¶)
$.(*__

```

... increment `n` but exclude trailing `5`s.

```
1G`

```

Delete `k`.

# Answer
> 0 votes
# C (gcc), ~~159~~ ~~158~~ ~~152~~ ~~150~~ 149 bytes, ~0.04 s

Outputs the answer to STDOUT, with leading zeroes.

-3 byte thanks to ceilingcat

```
m,j;f(n,k)long n;{char*t,s[17];for(t=s+sprintf(s,"%016ld",++n),m=n=0;m<k&--t>s;m<k&&*t-53?n=*t>53,*t=53:0)for(*t+=n,m=j=17;j--;)m-=s[j]!=53;puts(s);}

```

Try it online!

# Answer
> 0 votes
# Ruby, 41 bytes

```
->n,k{(n+1..).find{_1.to_s.count(?5)>=k}}

```

Attempt This Online!

---
Tags: code-golf, restricted-time
---


title: Collapsing numbers

text:
# Question
Title: Collapsing numbers
Let's define the a function on natural numbers \\$n\\$, written as base 10 digits \\$d\_k\\; d\_{k-1}\\; \dotsc\\; d\_1\\; d\_0\\$, as follows:

As long as there are equal adjacent digits \\$d\_i\\;d\_{i-1}\\$, replace them by their sum \\$d\_i+d\_{i-1}\\$ from left to right. If there were any such digits, repeat the same procedure.

In other words, in each iteration we greedily take all pairs of equal adjacent digits and replace them by their sum at the same time (using the left-most pair if they overlap).

## Example

Let's take \\$\texttt{9988}\\$ for example:

1. The first adjacent digits which are equal are the two \\$\texttt{9}\\$
2. So we replace them by \\$\texttt{9 + 9} = \texttt{18}\\$ which gives us \\$\texttt{1888}\\$
3. Since we're still in the first left-right traversal and there were still two \\$\texttt{8}\\$s we need to first replace these
4. So we get \\$\texttt{1816}\\$
5. Something changed, so we need to do another iteration
6. But there are no such digits, so we stop

Therefore the \\$9988^\text{th}\\$ number in that sequence is \\$1816\\$.

## Challenge

The first 200 terms are:

```
0,1,2,3,4,5,6,7,8,9,10,2,12,13,14,15,16,17,18,19,20,21,4,23,24,25,26,27,28,29,30,31,32,6,34,35,36,37,38,39,40,41,42,43,8,45,46,47,48,49,50,51,52,53,54,10,56,57,58,59,60,61,62,63,64,65,12,67,68,69,70,71,72,73,74,75,76,14,78,79,80,81,82,83,84,85,86,87,16,89,90,91,92,93,94,95,96,97,98,18,10,101,102,103,104,105,106,107,108,109,20,21,4,23,24,25,26,27,28,29,120,121,14,123,124,125,126,127,128,129,130,131,132,16,134,135,136,137,138,139,140,141,142,143,18,145,146,147,148,149,150,151,152,153,154,20,156,157,158,159,160,161,162,163,164,165,4,167,168,169,170,171,172,173,174,175,176,24,178,179,180,181,182,183,184,185,186,187,26,189,190,191,192,193,194,195,196,197,198,28

```

Your task is to generate that sequence, either

* given \\$n\\$, return the \\$n^\text{th}\\$ number in that sequence,
* given \\$n\\$, return the first \\$n\\$ numbers in that sequence
* or generate the sequence indefinitely.

You may choose your submission to use either \\$0\\$\- or \\$1\\$-indexing, but please specify which.

## Test cases

You may use the above given terms, however here are some larger ones:

```
222 -> 42
1633 -> 4
4488 -> 816
15519 -> 2019
19988 -> 2816
99999 -> 18189
119988 -> 21816
100001 -> 101
999999 -> 181818

```

# Answer
# Python 3, 128 bytes

```
def t(z):j=z and(z[0]==z[1:2])+1;return[str(int(z[0])*j),*t(z[j:])]if j else''
def c(n):r="".join(t(n));return r!=n and c(r)or r

```

Try it online!
> 6 votes

# Answer
# Python 2, ~~97~~ ~~96~~ 93 bytes

```
def f(n):r=re.sub(r'(.)\1',lambda m:`int(m.group(1))*2`,n);return r!=n and f(r)or r
import re

```

Try it online!

---

Non regex version:

# Python 2, ~~133~~ ~~130~~ ~~122~~ ~~112~~ 98 bytes

```
def f(n):
 r='';s=n
 while s:a=1+(s[0]==s[1:2]);r+=`int(s[0])*a`;s=s[a:]
 return r!=n and f(r)or r

```

Try it online!
> 5 votes

# Answer
# Jelly, 11 bytes

```
DŒg+2/€FVµ¡

```

This is an unnecessarily slow, full program.

Try it online!

### Alternate version, 12 bytes

```
DŒg+2/€FVµƬṪ

```

One byte longer, but much faster. Works as a program or a function.

Try it online!

### How it works

```
DŒg+2/€FVµƬṪ  Main link. Argument: n (integer)

         µ    Combine the previous links into a chain. Begin a new one.
D               Decimal; yield n's digit array in base 10.
 Œg             Group adjacent, identical digits into subarrays.
   +2/€         Map non-overlapping, pairwise sum over the subarrays.
                If there is an odd number of digits in a subarray, the
                last digit will remain untouched.
       F        Flatten; dump all sums and digits into a single array.
        V       Eval; turn the result into an integer.
          Ƭ   Execute the chain 'til the results are no longer unique.
              Return all unique results.
           Ṫ  Tail; extract the last result.

```

The 11-byte version does the same, except it calls the link **n** times for input **n**, instead of calling it until a fixed point is reached.
> 5 votes

# Answer
# JavaScript, ~~48~~ ~~47~~ 46 bytes

Input and output as strings. Returns the `nth` term of the sequence.

```
f=s=>s-(s=s.replace(/(.)\1/g,x=>x/5.5))?f(s):s

```

Try it online

* 1 byte saved thanks to Arnauld
* 1 byte saved thanks to tsh
> 4 votes

# Answer
## Haskell, 70 bytes

```
until((==)=<<f)f
f(a:b:c)|a==b=show(2*read[a])++f c|1<2=a:f(b:c)
f a=a

```

Input is taken as a string.

Try it online!
> 4 votes

# Answer
# Retina, 16 bytes

```
+`(.)\1
$.(2*$1*

```

Try it online! Link includes test cases. Explanation:

```
+`

```

Repeat until the input stops changing.

```
(.)\1

```

Replace pairs of adjacent digits...

```
$.(2*$1*

```

... with twice the digit. (`$1*` generates a string of `$1` `_`s, `2*` duplicates that, and `$.(` takes the length. Actually, the Retina engine is cleverer than that and just doubles `$1`.)
> 4 votes

# Answer
# C# (.NET Core), ~~231~~, ~~203~~, ~~200~~, ~~196~~, 192 bytes

EDIT: Function is now at 185 bytes plus 18 for `using System.Linq;`

Thanks to BMO (for 1\>0 being equal to true plus newline removal) and Mr. XCoder (for f=!f statements)!

EDIT2: Down to 182 bytes plus 18 for `using System.Linq` thanks to dana for sharing a few golf tips!

EDIT3: Thanks to Embodiment of Ignorance for the int\[\] -\> var, removal of short circuit && -\> &, and changing up ToArray -\> ToList! (178 bytes + 18 using)

EDIT4: Embodiment of Ignorance dropped 4 bytes by changing an assignment. Dummy me shoulda counted! Thanks again :D

```
p=>{var f=1>0;while(f){var t=p.Select(n=>n-48).ToList();p="";f=!f;for(var j=0;j<t.Count;j++){if(j<t.Count-1&t[j]==t[1+j]){p+=t[j]+t[++j];f=!f;continue;}p+=t[j];}};return p;};

```

Try it online!
> 3 votes

# Answer
# Perl 6, 37 bytes

```
{($_,{S:g[(\d)$0]=2*$0}...*==*)[*-1]}

```

Try it online!

This is a function which generates the nth term of the sequence, given n as its argument.

`($_, { ... } ... * == *)` is the sequence of successive changes to the input number, generated by the bracketed expression (a simple regex substitution) and stopping when `* == *`, that is, when the last two numbers in the sequence are equal. Then the `[*-1]` takes just the final element of that sequence as the return value.
> 3 votes

# Answer
# Japt v2.0a0 `-h`, ~~15~~ 14 bytes

Returns the `nth` term of the sequence.

```
Æ=s_r/(.)\1/ÏÑ

```

Try it

This should work for 10 bytes but there seems to be a bug in Japt's recursive replacement method.

```
e/(.)\1/ÏÑ

```
> 2 votes

# Answer
# Wolfram Language 108 bytes

```
ToExpression[""<>ToString/@Total/@Flatten[Partition[#,UpTo@2]&/@Split@IntegerDigits@#,1]]&~FixedPoint~#&

```

## Explanation

`IntegerDigits` transforms the input number into a list of its digits.

`Split` groups consecutive repeated digits.

`Partition[#, UpTo@2]&/@` breaks runs of like digits into lists of, at most, lengths of 2.

`Flatten[...,1]` eliminates occasional overly-nested braces--e.g., {{2,2}} becomes {2,2}

`Total/@` sums totals of paired digits. Isolated digits need not be summed.

`ToString` converts the totals (and isolated digits) to strings.

`""<>` joins all the strings in the list.

`ToExpression` converts the outcome to an integer.

`...~FixedPoint~#&` applies the function until the result ceases to change.
> 2 votes

# Answer
# Perl 5 `-p`, 21 bytes

```
s/(.)\1/$1*2/ge&&redo

```

Try it online!
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler) with flag `/u:System.Text.RegularExpressions.Regex`, 70 bytes

```
s=>{for(;s[0]!=(s[0]=Replace(s[0],@"(.)\1",m=>m.Value[0]*2-96+"")););}

```

Outputs by modifying the input. Takes in a list containing one string for input.

Thanks to @dana for golfing an entire 23 bytes!

Try it online!
> 2 votes

# Answer
# Groovy, 63 bytes

```
{s->r=/(\d)\1/
while(s=~r)s=s.replaceAll(r){(it[1]as int)*2}
s}

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 11 bytes

```
Δγε2ôSO}˜J

```

Try it online or verify all test cases.

**Explanation:**

```
Δ             # Continue until the (implicit) input no longer changes:
 γ            #  Split the integer in chunks of the same adjacent digits
              #   i.e. 199999889 → [1,99999,88,9]
  ε     }     #  Map each to:
   2ô         #   Split it into parts of size 2
              #    i.e. 99999 → [99,99,9]
     €S       #   Split each part into digits
              #    i.e. [99,99,9] → [[9,9],[9,9],[9]]
       O      #   And take the sum of each part
              #    i.e. [[9,9],[9,9],[9]] → [18,18,9]
         ˜    #  Flatten the list
              #   i.e. [[1],[18,18,9],[16],[9]] → [1,18,18,9,16,9]
          J   #  Join everything together
              #   i.e. [1,18,18,9,16,9] → 118189169
              # (And output the result implicitly at the end)
              #  i.e. output = 28189169

```
> 2 votes

# Answer
# Clean, 118 bytes

```
import StdEnv,Data.List
$[a,b:t]|a==b=[1,(a*2)rem 10]%(1-a/5,1)++ $t=[a: $[b:t]]
$l=l

```

#

```
limit o iterate$o map digitToInt

```

Try it online!

Takes the first repeated value (`limit`) from the infinite list of applications (`iterate`) of a lambda performing a single step of the collapsing process. Input taken as a `[Char]`.
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 111 bytes

```
s=>{var t=s;do{s=t;t="";for(int i=0;i<s.Length;)t+=s[i]%48*(s[i++]!=(s+0)[i]?1:2*++i/i);}while(t!=s);return t;}

```

Try it online!

HUGE credit to @ASCIIOnly for golfing ~30 ;) At first we were both posting updates simultaneously, but at some point he clearly went to town!

-2 thanks to @EmbodimentOfIgnorance!

Less golfed code...

```
// s is the input as a string
s=>{
  // t is another string used
  // to hold intermediate results
  var t=s;
  // the algorithm repeatedly
  // processes s and saves the
  // result to t
  do{
    // copy the last result to s
    // and blank out t
    s=t;
    t="";
    // iterate over s
    for(int i=0;i<s.Length;)
      // append either 1 or 2 times
      // the current digit to t
      t+=s[i]%48*
        // compare the current digit
        // to the next digit. to prevent
        // an out-of-bounds exception,
        // append a 0 to s which either
        // gets ignored or collapses
        // to 0
        (s[i++]!=(s+0)[i]
          // if they are different, then
          // the multiplier is 1
          ?1
          // if they are the same, then
          // the multiplier is 2, and we
          // have to increment i
          :2*++i/i);
  }
  // continue this until the input
  // and output are the same
  while(t!=s);
  return t;
}

```
> 1 votes

# Answer
# Red, ~~84~~ ~~83~~ 80 bytes

```
func[n][if parse s: form n[to some change[copy d skip d](2 * do d)to end][f s]s]

```

Try it online!

Returns the `nth` term of the sequence.

## Explanation:

```
Red[]
f: func [ n ] [
    if parse s: form n [  ; parse the input converted to a string
        to some change [  ; find and change one or more
            copy d skip   ; digit (in fact any character, no predefined character classes)
            d             ; followed by itself
        ] (2 * do d)      ; with its doubled numeric value
        to end            ; go to the end of the string
    ] [ f s ]             ; call the function with the altered string if parse returned true
    s                     ; finally return the string
]

```
> 1 votes

# Answer
# Scala, 84 bytes

```
s=>{var t=s
while(t!=(t="(\\d)\\1".r.replaceAllIn(t,m=>s"$m"(0)*2-96+""),t)._2){}
t}

```

Try it online!
> 1 votes

# Answer
# Husk, 15 bytes

```
→U¡ödṁoṁodΣC2gd

```

Try it online!
> 0 votes

# Answer
# Ruby `-p`, ~~39~~ 34 bytes

-5 bytes thanks to Steffan

```
$_.gsub!(/(.)\1/){$1.to_i*2}&&redo

```

Attempt This Online!
> 0 votes

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


# Question
Title: Find how "smooth" a number is based on binary
I haven't been on PP&CG for a while, so I thought I would post something!

Your task is to find how "smooth" a *natural* number is. Your method is to:

1: Convert the number to binary
2: Find the number of changes / switches
3: Find the length of the string (in binary)
4: Divide length by changes

So, an example. 5.
Starting at step one, we wind up with 101 for binary.
Step two is where we count the "switches". This is how many times a digit changes, so 100001 would count 2 switches. 101 counts 2, too.
Step three has a length of three in binary. Step four gives us 3/2, or 1.5.
Doing this for 10 is also simple: Step one results with 1010, two with three, three with four, and a final result has 1.33333333... repeating.

If the inputs output infinity (examples: `1`, `3`, and `7`), you need to output something that tells you infinity, like \\$\infty\\$ or `Infinity`.

Now, you might ask, "*what about scoring?*" or something like that: You are scored in characters, so feel free to use a lot of code golfing languages. (*I'm looking at you, Jelly*)
If you round the output "smoothness factor" to 3 decimal places (4/3 is now 1.333, 5/3 is 1.667) your score is now x0.95, and being able to not only return a smoothness factor but also be able to compare two numbers (etc: putting in 5 and 10 returns \> because 5's smoothness factor is greater than 10's) multiplies your value by x0.7. Command-line flags don't count for anything.
Have fun!

This challenge **ends** the 19th of March.
Current placeholders: The functional language holder, with 45 chars, Nahuel Fouilleul, and the code golf language holder, with 7 chars, Luis Mendo.

# Answer
> 1 votes
# Perl 5 (`-p -Mbignum`), 45 bytes

```
$_=sprintf"%b",$_;$_=y///c/(s/(.)(?!\1)//g-1)

```

TIO

# Answer
> 4 votes
# MATL, 7 characters

```
Btnwdz/

```

Try it online!

### Explanation

```
B    % Convert to binary
t    % Duplicate
n    % Number of elements
w    % Swap
d    % Consecutive differences
z    % Number of nonzeros
/    % Divide

```

# Answer
> 3 votes
# Japt, 8 bytes

*NULL for infinity*

```
¤Ê/¢ä¦ x

```

Try it online!

# Answer
> 3 votes
# Jelly, 8 bytes, score 8

Maybe there is a terser way... edit: I don't think there is.

```
BL÷BITLƲ

```

Infinity is given as `inf`.

**Try it online!**

...other 8's are possible too, for example `BµITL÷@L` or `BL÷BnƝSƊ`.

# Answer
> 2 votes
# JavaScript (ES6),  ~~46 44~~  40 bytes / characters

Returns `Infinity` if there's no bit flip.

```
n=>(g=s=>n&&1+g(x=s-(n^(n>>=1))%2))``/~x

```

Try it online!

### Commented

```
n => (                  // n = input integer
  g = s =>              // g = recursive function taking the number s of bit switches
    n &&                //   stop if n is equal to 0
    1 +                 //   otherwise, add 1 to the final returned value
    g(                  //   and do a recursive call to g:
      x =               //     update s and save the result in x:
        s -             //       subtract 1 from s if ...
        (n ^ (n >>= 1)) //       ... there is a bit switch; and shift n to the right
        % 2             //       NB: an extra bit switch is counted on the last bit
    )                   //   end of recursive call
)``                     // initial call to g with s = [''], which is coerced to 0
                        // as soon as something is subtracted from it
/ ~x                    // divide the result of g by -(x + 1), which compensates for
                        // the extra switch

```

# Answer
> 2 votes
# 05AB1E, 8 bytes/characters

```
bgIbγg</

```

Try it online or verify all test cases.

Or alternatively:

```
b©g®¥ÄO/

```

Try it online or verify all test cases.

Outputs `0.0` for the `INF` cases.

---

With both bonuses **score: 11.97 (18 bytes/characters * 0.95 * 0.7)**:

```
εbgybγg</3.ò}DÆ.±)

```

Outputs `1` if the first input is larger than the second; `-1` if vice-versa; `0` if they are equal.
NOTE: Because I output `0.0` for the `INF` cases, they are considered lower than non-infinity test cases. Let me know if this has to be fixed..

Try it online.

**Explanation:**

```
ε       # Map both values of the (implicit) input-list:
 b      #  Get the binary-string of the current value
  g     #  And get the length of this string
 yb     #  Get the binary-string of the current value again
   γ    #  Split it into chunks of equal adjacent digits
    g<  #  Get the amount of chunks, and subtract 1
 /      #  Divide both numbers
 3.ò    #  Round the number to 3 decimal values
}D      # After the map: duplicate the resulting list
  Æ     # Reduce the duplicated list by subtraction
   .±   # And get the sign of that result
     )  # Then wrap it into a list with the mapped values
        # (and output the result implicitly)

```

# Answer
> 1 votes
# Kotlin, ~~83~~ 82 bytes

```
{s->s.toString(2).run{length.toFloat()/(0..length-2).count{this[it]!=this[it+1]}}}

```

Try it online!

# Answer
> 1 votes
# 1. Python 3, 131 bytes (154 with file header)

Hi. I know that my code is way longer than others, but I will try it ;) Indentation by tabs.

Script takes sequence of numbers in aguments and prints "smoothness" for each argument on own line. If number of changes is 0, prints "inf".

```
$ ./script.py 12
4.0

$ ./script.py 12 5 6
4.0
1.5
3.0

$ ./script.py `seq 5`
None
2.0
None
3.0
1.5

```

file header

```
#!/usr/bin/env python3

```

code

```
import sys
for n in sys.argv[1:]:
    b=bin(int(n))[2:];c=0;l=b[0]
    for o in b:
        if o!=l:c+=1
        l=o
    print(len(b)/c if c>0 else"inf")

```

## Input single number from STDIN: 102+23 bytes (code + file header)

```
n=input();b=bin(int(n))[2:];c=0;l=b[0]
for o in b:
    if o!=l:c+=1
    l=o
print(len(b)/c if c>0 else"inf")

```

# Answer
> 1 votes
# , 56 bytes

```
length(y<-(x=scan())%/%2^(0:log2(x))%%2)/sum(diff(y)!=0)

```

Try it online!

# Answer
> 1 votes
# Charcoal, 24 characters

```
≔⍘Ｎ²θ≔⁺№θ10№θ01η¿ηＩ∕Ｌθη∞

```

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

```
≔⍘Ｎ²θ

```

Input the number and convert it to base 2 as a string.

```
≔⁺№θ10№θ01η

```

Calculate the number of of switches by counting the occurrences of `10` or `01` in the string.

```
¿ηＩ∕Ｌθη∞

```

If the total is nonzero then output the smoothness otherwise print Infinity.

# Answer
> 1 votes
# Ruby, 42 bytes

```
->n{1.0*(w=(n^n/2).digits 2).size/~-w.sum}

```

Try it online!

### How?

First step: bitwise XOR of x and x/2. The result will have a bit set to 1 for every switch in the input number plus 1, and so we just need to get the number of digits in base 2, and their sum. Then add some parentheses, and make it a float.

# Answer
> 0 votes
# Python 3, 105 chars

```
def s(n):b=bin(n)[2:];l=len(b);c=sum([0if b[i]==b[i+1]else 1for i in range(l-1)]);return l/c if c>0else-1

```

Returns -1 in the case of an infinity.

# Answer
> 0 votes
# Python 3.8 (pre-release), 60 bytes

Port of G B's Ruby answer.

```
lambda l:(c:=(b:=bin(l^l>>1)).count('1'))>1and(len(b)-2)/~-c

```

Try it online!

---

# Python 2, 68 bytes

Returns false if the value is infinite.

```
k=input()
n=s=0
while k:l=k%2;n+=1.;k/=2;s+=l^k%2
print s>1and n/~-s

```

Try it online!

# Answer
> 0 votes
# J-uby, 42 bytes

```
~:digits&2|:/%[:+@|Q,:chunk+I|A|:+@|:pred]

```

Attempt This Online!

# Answer
> 0 votes
# , 30 bytes

Outputs infinity `0w` for 1, 3, 7 etc.

```
{count[b]%-1+/differ b:2 vs x}

```

# k, 21 bytes

```
{(#x)%-1+/~~':x:2\:x}

```

---
Tags: code-golf, binary, base-conversion
---


title: Phonemic Abugida

text:
# Question
Title: Phonemic Abugida
# Characters

Let’s call these Unicode characters **English IPA consonants**:

```
bdfhjklmnprstvwzðŋɡʃʒθ

```

And let’s call these Unicode characters **English IPA vowels**:

```
aeiouæɑɔəɛɜɪʊʌː

```

(Yes, `ː` is just the long vowel mark, but treat it as a vowel for the purpose of this challenge.)

Finally, these are **primary and secondary stress marks**:

```
ˈˌ

```

> Note that `ɡ` (U+0261) is not a lowercase g, and the primary stress marker `ˈ` (U+02C8) is not an apostrophe, and `ː` (U+02D0) is not a colon.

# Your task

Given a word, stack the vowels on top of the consonants they follow, and place the stress markers beneath the consonants they precede. (As the question title hints, such a writing system, where consonant-vowel sequences are packed together as a unit, is called an abugida.) Given the input `ˈbætəlʃɪp`, produce the output:

```
æə ɪ
btlʃp
ˈ

```

> A **word** is guaranteed to be a string of consonants, vowels, and stress marks, as defined above. There will never be consecutive stress marks, and they will always be placed at the start of the word *and/or* before a consonant.

# Test cases

There may be consecutive vowels. For example, `kənˌɡrætjʊˈleɪʃən` becomes

```
      ɪ
ə  æ ʊeə
knɡrtjlʃn
  ˌ   ˈ

```

If a word starts with a vowel, print it on the “baseline” with the consonants: `əˈpiːl` becomes

```
 ː
 i
əpl
 ˈ

```

A test case with an initial, stressed vowel: `ˈælbəˌtrɔs` becomes

```
  ə ɔ
ælbtrs
ˈ  ˌ

```

A long word: `ˌsuːpərˌkaləˌfrædʒəˌlɪstɪˌkɛkspiːæləˈdoʊʃəs` becomes

```
               æ
ː              ː ʊ
uə aə æ əɪ ɪɛ  iəoə
sprklfrdʒlstkkspldʃs
ˌ  ˌ ˌ   ˌ  ˌ    ˈ

```

A nonsense example with an initial diphthong, lots of vowel stacking, and no stress markers: `eɪbaeioubaabaaa` becomes

```
 u
 o
 i a
 eaa
ɪaaa
ebbb

```

# Reference implementation

Your program should produce the same output as this Python script:

```
consonants = 'bdfhjklmnprstvwzðŋɡʃʒθ'
vowels = 'aeiouæɑɔəɛɜɪʊʌː'
stress_marks = 'ˈˌ'

def abugidafy(word):
    tiles = dict()
    x = y = 0

    is_first = True
    for c in word:
        if c in stress_marks:
            tiles[x + 1, 1] = c
        elif c in consonants or is_first:
            y = 0
            x += 1
            tiles[x, y] = c
            is_first = False
        elif c in vowels:
            y -= 1
            tiles[x, y] = c
            is_first = False
        else:
            raise ValueError('Not an IPA character: ' + c)

    xs = [x for (x, y) in tiles.keys()]
    ys = [y for (x, y) in tiles.keys()]
    xmin, xmax = min(xs), max(xs)
    ymin, ymax = min(ys), max(ys)

    lines = []
    for y in range(ymin, ymax + 1):
        line = [tiles.get((x, y), ' ') for x in range(xmin, xmax + 1)]
        lines.append(''.join(line))
    return '\n'.join(lines)

print(abugidafy(input()))

```

Try it on Ideone.

# Rules

* You may write a function or a full program.
* If your program has a Unicode character/string type, you can assume inputs and outputs use those. If not, or you read/write from STDIN, use the UTF-8 encoding.
* You may produce a string containing newlines, or a list of strings representing rows, or an array of Unicode characters.
* Each row of output may contain any amount of trailing spaces. If you produce a string, it may have a single trailing newline.
* Your program should produce the correct output for arbitrarily long words with arbitrarily long vowel chains, but may assume that the input word is always valid.
* If there are no stress markers, your output may optionally include a final empty row (containing nothing, or spaces).
* The shortest answer (in bytes) wins.

# Answer
> 2 votes
# NARS2000 APL, 138 bytes

```
⍉⌽⊃E,⍨¨↓∘' '¨∨/¨∊∘M¨E←(1+(W∊M←'ˌˈ')++\W∊'bdfhjklmnprstvwzðŋɡʃʒθ')⊂W←⍞

```

# Answer
> 2 votes
# Python, 222 bytes

(202 characters)

```
import re
def f(s):y=[w[0]in'ˈˌ'and w or' '+w for w in re.split('([ˈˌ]?[bdfhjklmnprstvwzðŋɡʃʒθ]?[aeiouæɑɔəɛɜɪʊʌː]*)',s)[1::2]];return[[x[i-1:i]or' 'for x in y]for i in range(max(len(w)for w in y),0,-1)]

```

Returns an array of unicode characters with an array for each row (containing single spaces for each space required)

Not sure where one can get decent output online yet (and I haven't even got the tools to test it properly here either).
I have loaded a version to **ideone** that just uses English consonants and vowels with `,` and `.` as stress marks, where I have fudged the test cases to conform.

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

```
f=
s=>(a=s.match(/[ˈˌ]?.[aeiouæɑɔəɛɜɪʊʌː]*/g).map(s=>/[ˈˌ]/.test(s)?s:` `+s)).map(s=>(l=s.length)>m&&(t=s,m=l),m=0)&&[...t].map(_=>a.map(s=>s[m]||` `,--m).join``).join`
`
;
```

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

# Answer
> 1 votes
# Go, 609 bytes

```
import."strings"
type P struct{x,y int}
func M(s[]int)(m,n int){for _,e:=range s{if e<=m{m=e};if e>=n{n=e}};return}
func f(s string)(L string){T,x,y,F,R:=make(map[P]rune),0,0,1>0,ContainsRune
for _,r:=range s{if R("ˈˌ",r){T[P{x+1,1}]=r}else if R("bdfhjklmnprstvwzðŋɡʃʒθ",r)||F{y=0;x++;T[P{x,y}],F=r,1<0}else if R("aeiouæɑɔəɛɜɪʊʌː",r){y--;T[P{x,y}],F=r,1<0}}
var u,v[]int
for k:=range T{u,v=append(u,k.x),append(v,k.y)}
for y,Y:=M(v);y<Y+1;y++{o:=[]string{}
for x,X:=M(u);x<X+1;x++{if r,ok:=T[P{x,y}];ok{o=append(o,string(r))}else{o=append(o," ")}}
L+=TrimPrefix(Join(o,"")," ")+"\n"}
return}

```

Attempt This Online!

A direct port of the reference implementation.

## Ungolfed Explanation

```
// map of x-y coords to a character
type tile map[P]rune

func (t tile) Xs() (o []int) {
	for k := range t {
		o = append(o, k.x)
	}
	return
}
func (t tile) Ys() (o []int) {
	for k := range t {
		o = append(o, k.y)
	}
	return
}

// coordinate pair
type P struct{ x, y int }

func min[T int](s []T) T {
	var m T
	for _, e := range s {
		if e <= m {
			m = e
		}
	}
	return m
}
func max[T int](s []T) T {
	var m T
	for _, e := range s {
		if e >= m {
			m = e
		}
	}
	return m
}

func f(s string) string {
	C, V, S := "bdfhjklmnprstvwzðŋɡʃʒθ", "aeiouæɑɔəɛɜɪʊʌː", "ˈˌ" // constant strs
	tiles := make(tile)                                          // the actual map
	x, y := 0, 0                                                 // (x0,y0) is the leftmost center
	isFirst := true                                              // is this character the first of a line?
	for _, r := range s {                                        // for each char...
		if strings.ContainsRune(S, r) {                          // if it's stress...
			tiles[P{x + 1, 1}] = r                               // put it underneath the next syllable
		} else if strings.ContainsRune(C, r) || isFirst {        // if it's a consonant or the first letter...
			y = 0
			x++
			tiles[P{x, y}] = r                                   // place on the baseline
			isFirst = false
		} else if strings.ContainsRune(V, r) {                   // if's a vowel...
			y--
			tiles[P{x, y}] = r                                   // place 1 above the baseline at the current x
			isFirst = false
		}
	}

	// get the ranges for outputting into a string
	xs, ys := tiles.Xs(), tiles.Ys()
	xmin, xmax := min(xs), max(xs)
	ymin, ymax := min(ys), max(ys)

	lines := []string{}
	for y := ymin; y < ymax+1; y++ {             // for each vowel at height y...
		line := func() (o []string) {
			for x := xmin; x < xmax+1; x++ {     // for each syllable on that vowel height...
				if r, ok := tiles[P{x, y}]; ok { // get the char
					o = append(o, string(r))
				} else {
					o = append(o, " ")           // use a space if there is no vowel there
				}
			}
			return
		}()
		lines = append(lines, strings.TrimPrefix(strings.Join(line, ""), " ")) // add to the output
	}
	return strings.Join(lines, "\n") // return the string
}

```

Attempt This Online!

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


# Question
Title: Round the digits last digit, over and over
# Challenge:

Given two inputs, **x** and **y**, round **x** to one less significant figure, then repeat until it has **y** number of unrounded digits left. (the decimal point does not count as a digit)

# Input & Output

Input can be a combination of strings and integers, e.g. you can have the input as a string and the output as an int, or vice versa.
The input number will never have 15 digits total, and the y will never be greater than the input number's length and will always be greater than 0.
Example:

```
x = 32.64712, y = 3
    32.64712 -> 32.6471 -> 32.647 -> 32.65 -> 32.7  (Three unrounded digits left)

x = 87525, y = 2
    87525 -> 87530 -> 87500 -> 88000 (Two unrounded digits left)

x = 454, y = 3
    454 -> 454 (Three unrounded digits left)

```

(steps shown just to clarify, you only need to output the last value.)

# Rules

* Trailing 0's are allowed
* 5's round up
* Standard loopholes apply

This is , so you should strive for the shortest answer.

# Answer
# Python 2, ~~101~~ ~~97~~ ~~92~~ ~~91~~ 85 bytes

```
lambda x,y:reduce((lambda n,l:int(n/.1**l+.5)*.1**l),range(15,y+~len(`int(x)`),-1),x)

```

Try it online!

---

Alternative : If Python's round would round "half up" instead of "half to even":

# Python 2, 57 bytes

```
lambda x,y:reduce(round,range(15,y-len(`int(x)`)-1,-1),x)

```

Try it online!
> 1 votes

# Answer
## JavaScript (ES6), 58 bytes

```
f=
(x,n,y=x.toPrecision(n))=>y>x?y:(x*9/8-y/8).toPrecision(n)
```

```
<div oninput=o.textContent=f(+x.value,+n.value)><input id=x><input id=n type=number min=1 max=15 value=3><pre id=o>
```

Arithmetic solution. The given procedure rounds numbers up if they are greater than 4/9 of the next value, so if rounding doesn't increase the number, try again with a slightly greater value.
> 1 votes

# Answer
# Perl 6, 59 bytes

```
{($^a,{.round(10**($++-15))}...^0|any 10 X**^30-15)[*-$^b]}

```

Try it online!

Anonymous code block that takes two numbers and returns a number.

### Explanation:

```
{                                                         }  # Anonymous code block
 (                          ...                   )  # Create a sequence
  $^a,   # With the first element as the input
      {                    }  # With each element being
       .round(10**($++-15))   # The previous element rounded by another digit
                                0                   # Until 0
                                 |                  # or
                                  any 10 X**^30-15  # Any available power of 10
                               ^  # Ignoring the last number
                                                   [*-   ]  # Index from the end
                                                      $^b   # The second number

```
> 0 votes

# Answer
# , 79 bytes

Unfortunately, R uses "round to even" when rounding off a .5

```
function(x,y){for(i in nchar(gsub('\\.','',x)):y){x=signif((x*100+1)/100,i)};x}

```

Try it online!
> 0 votes

# Answer
# Ruby, 103 bytes

This is ugly and presumably there are better ways (alas `sprintf`’s `%g` rounds to even), but it works.

```
g=->m,n{m.to_s.size>n ?g[(m/10.0).round,n]:m}
->x,n{_,s,_,e=x.to_d.split
"0.#{g[s.to_i,n]}".to_f*10**e}

```

Attempt This Online!
> 0 votes

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


title: Alpha-Numerical Bowtie

text:
# Question
Title: Alpha-Numerical Bowtie
Output this exact text:

```
1                i
12              hi
123            ghi
1234          fghi
12345        efghi
123456      defghi
1234567    cdefghi
12345678  bcdefghi
123456789abcdefghi
12345678  bcdefghi
1234567    cdefghi
123456      defghi
12345        efghi
1234          fghi
123            ghi
12              hi
1                i

```

A single trailing newline is acceptable, but no other formatting changes are allowed.

### Rules and I/O

* No input
* Output can be given by any convenient method.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# C, ~~87~~ ~~85~~ ~~81~~ 80 bytes

```
j;main(i){for(;++i<19;)for(j=19;j--;)putchar(j?j<i^j<20-i?32:106-j-j/10*39:10);}

```

Try it online!

### Explanation

```
j; // same as int j;
main(i){ // same as int main(int i){, where i = argc (1 with no arguments)
  for(;++i<19;) // loop over rows, i = 2..18
    for(j=19;j--;) // loop over chars, j = 19..0
      putchar(j?j<i^j<20-i?32:106-j-j/10*39:10); // output characters:
      //      j?                           :10 // on last char (j=0), output \n
      //        j<i                            // check for top/left half
      //            j<20-i                     // check for bottom/left half
      //           ^                           // 1 if only one half matched
      //                  ?32:                 // if so, output space
      //                      106              // char code for j
      //                         -j            // get desired letter
      //                           -j/10*39    // subtract 39 for j>9 (numbers)
}

```
> 13 votes

# Answer
# Python 2, 73 bytes

```
i=9
exec"i-=1;a=abs(i);print'123456789'[:9-a]+'  '*a+'abcdefghi'[a:];"*17

```

Try it online!
> 8 votes

# Answer
# 05AB1E (legacy), 15 bytes

```
A9£Sāì9LÂì×ζRû»

```

Try it online!

-2 thanks to Kevin Cruijssen.
> 6 votes

# Answer
# , 64 bytes

```
for(i in abs(8:-8))cat(intToUtf8(c(57-8:i,32*!!-i:i,97+i:8,13)))

```

Try it online!

* -3 bytes thanks to @Giuseppe
* -5 bytes thanks to @J.Doe
> 6 votes

# Answer
# Python 2, 80 bytes

```
j=i=1
exec"print'123456789'[:i]+'  '*(9-i)+'abcdefghi'[-i:];i+=j;j-=2*(i>8);"*17

```

Try it online!
> 4 votes

# Answer
# QBasic, 72 bytes

Based on Taylor Scott's submission.

```
FOR y=-8TO 8
z=ABS(y)
?"123456789abcdefghi";
LOCATE,10-z
?SPC(2*z)"
NEXT

```

### Basic explanation

On each line, we print the full string `123456789abcdefghi`. Then we *go back* and overwrite part of it with spaces.

### Full explanation

With code slightly ungolfed:

```
FOR y = -8 TO 8           ' Loop for 17 rows
 z = ABS(y)               ' z runs from 8 to 0 and back to 8
 ? "123456789abcdefghi";  ' Print the full string and stay on the same line (important!)
 LOCATE , 10-z            ' Go back to column 10-z on that line
 ? SPC(2*z); ""           ' Print 2*z spaces
                          ' (SPC keeps the cursor on the same line unlesss you print
                          ' something after it, so we'll use the empty string)
NEXT                      ' Go to the next y value

```
> 3 votes

# Answer
# Japt, ~~24~~ 19 bytes

Returns an array of lines

```
9õ Ôê1 Ëç°TsH)êÃû y

```

Test it

```
9õ Ôê1 Ëç°TsH)êÃû y
9õ                      :Range [1,9]
   Ô                    :Reverse
    ê1                  :Mirror
       Ë                :Map
        ç               :  Repeat
         °T             :    Prefix increment T (initially 0)
           s            :    Convert to base
            H           :    32
             )          :  End repeat
              ê         :  Palindromise
               Ã        :End map
                û       :Centre pad each with spaces to the length of the longest
                  y     :Transpose

```

(It did indeed, 4 year ago Shaggy, it did indeed!)
> 2 votes

# Answer
# T-SQL, 108 bytes

```
DECLARE @ INT=8a:
PRINT STUFF('123456789abcdefghi',10-abs(@),2*abs(@),SPACE(2*abs(@)))
SET @-=1IF @>-9GOTO a

```

Returns are for readability only.

Tried lots of other variations, including number tables, this was the shortest.
> 2 votes

# Answer
# 05AB1E, 20 bytes

```
9LJη.BA9£.sí.Bí)øJû»

```

Try it online!
> 2 votes

# Answer
# Canvas, 13 bytes

```
９Ｒ［］ｚ９ｍ±［］±＋─

```

Try it here!
> 2 votes

# Answer
# Japt, 20 bytes

```
9Æ9Ç>YÃê1 Ë?S:°EsH
ê

```

Japt Interpreter

Output as an array of arrays of characters. The `-R` flag isn't necessary to work, it just makes the output look nicer.

Explanation:

```
9Æ9Ç                    create a 9x9 2D array
    >YÃ                 fill bottom left triangle with "false", upper right with "true"
       ê1               mirror horizontally
          Ë?S           replaces "true" with a space
             :°EsH      replaces "false" with the horizontal index + 1 converted to base 32
                  \n    Store the result in U (saves bytes by not closing braces)
                    ê   palindromize vertically

```
> 2 votes

# Answer
# PowerShell 5.1, ~~70~~ ~~69~~ ~~64~~ 57 Bytes

Thanks Mazzy for -7 bytes

```
1..9+8..1|%{-join(1..$_+'  '*(9-$_)+' ihgfedcba'[$_..1])}

```

Turns out gluing it together manually saves a byte. Making it all one mega-join also saves 5 more. ~~Also works by turning a range of ints into a char\[\] to get the a-i.~~ Using a range over the actual letters is 5 bytes better.
> 2 votes

# Answer
# Julia 1.0, 73 bytes

```
[1:9;8:-1:1].|>i->println(join(1:9)[1:i]*" "^(18-2i)*"abcdefghi"[10-i:9])

```

Try it online!
> 2 votes

# Answer
# MATL, 47 bytes

```
9l$lRtH2$PhO18Y"yPvv1=49:57 97:105h19T3$X"32b(c

```

Try it online!
> 2 votes

# Answer
# Vyxal, 14 bytes

```
9ʀṘǔmkrf*ꜝøṗ↵§

```

Try it online!

**Explanation**

A transposition approach.

```
9ʀ             # range from 0 to 9 inclusive
  Ṙ            #  reversed
   ǔ           #  rotated right (last item goes to first)
    m          #  and concatenated with its reverse
     kr        # string of digits, lowercase alphabet, and uppercase alphabet
       f       #  into a list of characters
        *      # repeat (vectorises)
         ꜝ     # remove empty strings in the list
          øṗ   # palindromise each item, center, and join by newlines
            ↵  # split on newlines
             § # vertically join

```
> 2 votes

# Answer
# Stax, 18 bytes

```
â4+╤jo♂▐▀3bkWíæß╝╖

```

Run and debug it

Explanation:

```
9R$|[|<Va17T|]r|>\|pm Full program
9R$                   Produce "123456789"
   |[|<               Left-aligned prefixes (["1        ", "12       ", ...])
       Va17T          Produce "abcdefghi"
            |]        Suffixes (["abcdefghi", "bcdefghi", ...])
              r|>     Reverse and left-align (["        i", "       hi", ...])
                 \    Zip both arrays (["1                i", "12              hi", ...])
                  |p  Palindromize array
                    m Map over array, printing each with a newline

```
> 1 votes

# Answer
# Charcoal, ~~22~~ 17 bytes

```
Ｇ↗↓←⁹β←Ｇ↖↓⁹⭆χι‖Ｏ↓

```

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

```
Ｇ↗↓←⁹β

```

Draw a lower right triangle and fill it using the lowercase alphabet. (The fill is based on tiling the plane with the alphabet and then copying the drawn area.)

Move left to draw the numeric triangle.

```
Ｇ↖↓⁹⭆χι

```

Draw a lower left triangle and fill it using the digits. (Since the triangle is drawn to the left of the origin, the digits are taken right-justified, so only the digits 1 to 9 get used.)

```
‖Ｏ↓

```

Reflect to complete the bottom half.
> 1 votes

# Answer
# JavaScript (ES6), 76 bytes

```
f=(x=y=0)=>y<17?(x>y^x++<17-y?x.toString(36)+[`
`[x%=18]]:' ')+f(x||!++y):''

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Unicode), 30 bytes

```
(⊢⍪1↓⊖)(↑,\1↓⎕d),⌽↑,\⌽819⌶9↑⎕a

```

Try it online!

convert to a matrix (auto pads with spaces)

* `,\` the prefixes of
* `1↓` the first element dropped from
* `⎕d` this string `'0123456789'`
* This gives the character matrix

```
1
12
123
1234
12345
123456
1234567
12345678
123456789

```

`,` concatenated with

* the reversed
* matrixified
* `,\` prefixes of
* the reversed
* `819⌶` and lowercased
* `9↑` first 9 elements of
* `⎕a` this string `'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`
* This gives the character matrix

```
        i
       hi
      ghi
     fghi
    efghi
   defghi
  cdefghi
 bcdefghi
abcdefghi

```

and on this result

```
1                i
12              hi
123            ghi
1234          fghi
12345        efghi
123456      defghi
1234567    cdefghi
12345678  bcdefghi
123456789abcdefghi

```

perform the following train `(⊢⍪1↓⊖)`

the right argument

concatenated vertically with

`1↓` the first row dropped from (this avoids the repeating of the middle row)

the right argument reversed vertically

---

Other solutions

### 33 bytes

```
(⊢⍪1↓⊖)(↑,\⍕¨q),⌽↑,\⎕ucs 106-q←⍳9

```

Try it online!

### 33 bytes

```
(⊢⍪1↓⊖)(↑,\⍕¨q),⌽↑,\⌽⎕ucs 96+q←⍳9

```

Try it online!
> 1 votes

# Answer
# , ~~25~~, 21 bytes

```
¬19¬ai8ñHÄ/á
r ge.YGp

```

Try it online!

2-4 bytes saved thanks to nmjcman101!

Hexdump:

```
00000000: ac31 39ac 6169 38f1 48c4 2fe1 0a72 2067  .19.ai8.H./..r g
00000010: 652e 5947 70                             e.YGp

```
> 1 votes

# Answer
# , 44 bytes

```
(m]\u:49+i.9),.(m=.,}.@|.)]\&.(|."1)u:97+i.9

```

Try it online!

I tried to generate numerically a mask of 1 and zero to use for indexing, but the cost of getting rid of the extra row was high and I gave up:

```
   (9-.~i.18){0<:-/~(,|.)i.9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1
1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1
1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1
1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1
1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 0 0 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 0 0 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1
1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1
1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1
1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1
1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1
1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1

```
> 1 votes

# Answer
## Perl 5 \+ `-M5.010`, 49 bytes

```
say 1..9-abs,"  "x abs,(a..i)[-9+abs..-1]for-8..8

```

Try it online!
> 1 votes

# Answer
# QBasic, 87 bytes

An anonymous function that takes no input and outputs to the console.

```
For y=-8To 8:z=Abs(y):a$="123456789abcdefghi":?Mid$(a$,1,9-z)Spc(2*z)Mid$(a$,10+z):Next

```

This answer is technically a polyglot, and will function in VBA
> 1 votes

# Answer
# Befunge-93, 314 308 bytes

```
<p0+3*67p0+4*77p0+3*77p0-7*88p0-6*88"#v#v>"
"i        "11g1-21p56+1g1+56+1p28*1g1+28*1p  ^       >25*
"        1"92g1+82p56+2g1-56+2p28*2g1-28*2p91g00g`#v_^   >
"ihgfedcba "93p26*3g1-26*3p">^"88*7-0p88*7-4pv     >25*
"987654321 "14p26*4g1+26*4p26*4g12g`#v_            ^
                             >:#,_@#:<

```

Try it online!

Golfed 6 bytes by placing a `>` with the `p` instruction
> 1 votes

# Answer
## Matlab, 122 bytes

```
function[r]=f,s=[49:57,'a':'i'];r=[];for i=1:9,r=[r;s(1:i),repmat(' ',[1,18-2*i]),s(19-i:18)];end,r=[r;flip(r(1:8,:))];end

```

Try it Online!
> 1 votes

# Answer
# Deadfish~, 956 bytes

```
{iiiii}dc{dd}iii{c}cccccc{{i}ddd}iiic{{d}i}dddddc{iiii}dcic{dd}ii{c}cccc{{i}ddd}iicic{{d}i}dddddc{iiii}dcicic{dd}i{c}cc{{i}ddd}icicic{{d}i}dddddc{iiii}dcicicic{dd}{c}{{i}ddd}cicicic{{d}i}dddddc{iiii}dcicicicic{dd}dcccccccc{{i}ddd}dcicicicic{{d}i}dddddc{iiii}dcicicicicic{dd}ddcccccc{{i}ddd}ddcicicicicic{{d}i}dddddc{iiii}dcicicicicicic{dd}dddcccc{{i}ddd}dddcicicicicicic{{d}i}dddddc{iiii}dcicicicicicicic{dd}ddddcc{iiiiii}iiiiiicicicicicicicic{{d}i}dddddc{iiii}dcicicicicicicicic{iiii}cicicicicicicicic{{d}i}dddddc{iiii}dcicicicicicicic{dd}ddddcc{iiiiii}iiiiiicicicicicicicic{{d}i}dddddc{iiii}dcicicicicicic{dd}dddcccc{{i}ddd}dddcicicicicicic{{d}i}dddddc{iiii}dcicicicicic{dd}ddcccccc{{i}ddd}ddcicicicicic{{d}i}dddddc{iiii}dcicicicic{dd}dcccccccc{{i}ddd}dcicicicic{{d}i}dddddc{iiii}dcicicic{dd}{c}{{i}ddd}cicicic{{d}i}dddddc{iiii}dcicic{dd}i{c}cc{{i}ddd}icicic{{d}i}dddddc{iiii}dcic{dd}ii{c}cccc{{i}ddd}iicic{{d}i}dddddc{iiii}dc{dd}iii{c}cccccc{{i}ddd}iiic

```

Try it online!
> 1 votes

# Answer
# Haskell, 119 bytes

```
import Data.Char
main=putStr$do i<-[-8..8];[chr$if abs j>abs i then j+96-fromEnum(j<0)*38else 32|j<-[-9..9],j/=0]++"\n"

```

Try it online!
> 1 votes

# Answer
# Julia 1.0, 54 bytes

```
[8:-1:1;0:8].|>i->print.([1:9-i;" "^2i;'a'+i:'i';"
"])

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~81~~ 79 bytes

```
a=Table[" ",17,18];Do[a[[i;;-i,i]]=a[[1-i;;i-1,i]]=i~IntegerString~35,{i,18}];a

```

Try it online!

Throws a lot of ignorable errors.
> 0 votes

# Answer
# VBA, 75 bytes

An anonymous VBE immediate window function that takes no input and outputs to the console.

```
For y=-8To 8:z=Abs(y):a="123456789abcdefghi":Mid(a,10-z)=Space(2*z):?a:Next

```
> 0 votes

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

```
9R€z⁶Zµạ106Ọ$Ṡ¡€Uṭ)ŒḄ

```

Try it online!

Relies on the (likely) unintended behavior that when  (sign) acts on a character it yields Python's `None`. Because of this,  is a one byte check for whether it's argument is a nonzero integer since `None` is falsey in Python. If this behavior is changed then  works as well for one more byte.

Function that returns a list of lines.
> 0 votes

# Answer
# Java 8, ~~107~~ 102 bytes

```
v->{for(int i=1,j;++i<19;)for(j=19;j-->0;)System.out.printf("%c",j>0?j<i^j<20-i?32:106-j-j/10*39:10);}

```

Port of *@Pietu1998*'s C answer, so make sure to upvote him!
-5 bytes thanks to *@ceilingcat*.

Try it online.
> 0 votes

# Answer
# Python 2, ~~97~~ 94 bytes

```
i=o="123456789abcdefghi";c=8
while c:i=i[:c]+' '*(9-c)*2+i[-c:];o=i+'\n'+o+'\n'+i;c-=1
print o

```

Try it online!

Only posted as an alternative to using `eval()` and because I finally got it under 100. Basically starts with the middle row then works both up and down at the same time.
> 0 votes

# Answer
# Yabasic, 103 bytes

```
a$="123456789abcdefghi"
For y=-8To 8
z=Abs(y)
?Mid$(a$,1,9-z);
For i=1To z?"  ";Next
?Mid$(a$,10+z)Next

```

Try it online!
> 0 votes

# Answer
# C (gcc), ~~143~~ ~~142~~ ~~127+10=137~~ ~~136+10=146~~ 113+10=123 (compiler flags) bytes

-1 byte by replacing logical OR with bitwise operator.

-5 bytes thanks to Logern.

+9 bytes to fix the median line, that was output twice.

-23 bytes thanks to ceilingcat

```
char*s="123456789abcdefghi";G{for(;j<18;++j)putchar(i>j|j>17-i?s[j]:32);puts("");}f(){int i=0,j=0;for(;i++<8;)G;g(i+1,j);for(;i-->1;)G;}

```

Compiler flag:

```
-DG=g(i,j)

```

This macro factorizes the occurences of `g(i,j)`: function declaration and calls.

Try it online!

Different approach than Pietu1998's great answer, more straightforward (and readable), but higher score.

Entry point is function `f()`; function `g()` handles the printing of each consecutive line.

Could be made a full program by renaming `f` to `main`, but it would yet increase the score.

Pretty version, macro `G` expanded:

```
g(i, j) {
    for(; j < 18;++j)
        putchar(i > j | j > 17 - i ? "123456789abcdefghi"[j] : 32);
    puts(""); // Break the line; shorter than putchar(10) or printf("\n")
}
f(i, j) {
    for (i = j = 0; i++ < 8;) // Upper half of the tie
        g(i, j);
    for(; i; --i) // Median line and lower half
        g(i, j);
}

```
> 0 votes

# Answer
# Pascal (FPC), ~~110~~ 105 bytes

```
var i:int32;begin for i:=-8to 8do writeln('123456789'[1..9-abs(i)],'abcdefghi'[abs(i)+1..9]:abs(i)+9)end.

```

Try it online!
> 0 votes

# Answer
# PHP, 116 bytes

```
for(;++$i<18;)echo substr($s='123456789abcdefghi',0,$j=~-10-($k=abs(9-$i))).str_repeat(' ',$k*2).substr($s,-$j)."
";

```

Output

```
1                i
12              hi
123            ghi
1234          fghi
12345        efghi
123456      defghi
1234567    cdefghi
12345678  bcdefghi
123456789abcdefghi
12345678  bcdefghi
1234567    cdefghi
123456      defghi
12345        efghi
1234          fghi
123            ghi
12              hi
1                i

```

Sanbox

Cheers
> 0 votes

# Answer
# Lua, 103 bytes

```
for i=-8,8 do m=math.abs(i)print(("123456789"):sub(1,9-m)..(" "):rep(2*m)..("abcdefghi"):sub(m+1,9))end

```

Try it online!
> 0 votes

# Answer
# Raku, 81 bytes

```
for -8..8 {my \a=(.abs-9).abs;say (1..a).join~' 'x.abs*2~'abcdefghi'.substr(*-a)}

```

Try it online!
> 0 votes

# Answer
# ///, ~~163~~ 148 bytes

```
/w/lm//q/  //j/qqq//k/fghi
1234//l/qqq//m/q//n/dek567//o/i
12/1lwmolwho3llgho34wmk5wek56lnmmcn8mbcn89abcn8mbcnmmcdek56ldek5wekwmfgho3llgholwhi
1lwmi

```

Try it online!
> 0 votes

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