title: Create a Parrot Program

text:
# Question
Title: Create a Parrot Program
Given an input, output that input followed by a newline endlessly.

Input will be a string consisting only of printable ASCII characters (`0x20-0x7E`) and newlines (`0x0A`).

If input is length 0, endlessly output newlines.

This is so fewest bytes **in each language** wins!

# Answer
# Bash, 8 bytes

```
yes "$1"

```

Try it online!
> 12 votes

# Answer
# 05AB1E, 2 bytes

```
[,

```

Try it online!
> 10 votes

# Answer
# AutoHotkey, 20 Bytes

OP did not specify *how* the output should happen, said only it has to happen endlessly with a newline after it. AHK was not tailored for cmd interaction. So the output happens repeatedly in a `ToolTip` at mouse position:

```
loop
tooltip,%1%`n`n

```

I like AHK's `loop` feature. `loop` repeats the next block forever, `loop, 10` would repeat it 10 times. Sometimes I miss this feature in other languages like Python.

The escape character in AutoHotkey is ``` (so there are no problems with backslashes in Windows paths). For some reason, a trailing newline is ignored so it is needed twice. (`trayTip` might not have this "bug" but I cannot test it because running with wine)

## old answer:

```
loop
msgbox,%1%

```

I just realized that OP probably wont like this solution, the output happens with user-interaction and includes no newlines. I'll look for another way.
> 7 votes

# Answer
# JavaScript (ES6), 24 bytes

```
f=a=>f(a,console.log(a))

```

Try it online!
> 6 votes

# Answer
# Ohm, 3 bytes

```
∞┼,

```

Try it online!

It doesn't work with an empty input because Ohm is bad at input handling compared to other languages, but you can input "".

Explanation

```
∞     Infinite loop next code (until ";" or end of line)
 ┼    Get first input
  ,   Println

```
> 5 votes

# Answer
# sed, 5

```
:      # label (unnamed)
p      # print the pattern space
b      # branch back to the label

```

Unnamed labels is an undocumented "feature" in sed that works with version 4.2.2, but may not work in future versions.
> 5 votes

# Answer
# Jelly, 2 bytes

```
Ṅß

```

Try it online!

Print with a newline, repeat the whole link (program).
> 4 votes

# Answer
# brainfuck, 27 bytes

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

```

Try it online!
> 4 votes

# Answer
# Python 2, 21 bytes

```
def f(s):print s;f(s)

```

*Assumes no recursion limit*

**Try it online!**
> 4 votes

# Answer
# , 2 bytes

```
òÙ

```

You can't try this online for obvious reasons.

```
ò    'Recursively
 Ù   'Duplicate the current line downwards

```
> 4 votes

# Answer
# LibreLogo, 33 bytes

**Code:**

```
x=input " repeat [ label x bk 9 ]

```

**Explanation:**

```
x = input "               ; Input Stored in x as String
repeat [                  ; Endless Loop
    label x               ; Print x in Current Position
    bk 9                  ; Move Back 9 pt
]

```

**Result:**
> 4 votes

# Answer
# Ruby, ~~18~~ ~~17~~ 12 + 2 = 14 bytes

Run with the `-n` flag.

```
loop{$><<$_}

```

Edit: Thanks for @sethrin for the `-n` flag!
> 3 votes

# Answer
# Cubix, 6 bytes

```
AN/qvo

```

Test it here

```
  A
N / q v
  o

```
* `N/A` Push Newline(10) and input onto the stack
* `v` redirect into the loop
* `o/q` loop that outputs a character and pushes it to the bottom of the stack continuously

I was going to remove the EOI (-1) indicator from the stack, but it doesn't appear to affect the output any, so have left it saving bytes.
> 3 votes

# Answer
# Braingolf, ~~14~~ 12 bytes

```
#
V[R!&@v1+]

```

Try it online!

*-2 bytes thanks to totallyhuman*

## Explanation

```
#\nV[R!&@v1+]  Implicit input of string as charcodes
#\n            Push charcode of newline
   V           Create stack2
    [R...v1+]  While loop, runs endlessly
      !&@      Print entire stack1 as chars without popping

```
> 2 votes

# Answer
# Python 2, 25 bytes

```
s=input()
while 1:print s

```

Try it online!

Input is expected to be a Python literal (quotes for a string, square bracket or parentheses with comma-separated items for a list/tuple, etc.)

Python 3 would be +1 byte because `print` is a function, but also could do raw input without the 4-byte penalty for `raw_input()` in Python 2.
> 2 votes

# Answer
## Haskell, 14 bytes

```
cycle.(++"\n")

```

Try it online!

Append a newline to the input and make list of infinite copies of it.

Alternative version, also 14 bytes:

```
unlines.repeat

```
> 2 votes

# Answer
# Brachylog, 3 bytes

```
ẉ?↰

```

Try it online!

Port of my Jelly answer.
> 2 votes

# Answer
# PHP, 20 bytes

```
for(;;)echo"$argn
";

```
> 2 votes

# Answer
# C, 24 bytes

```
f(char*s){puts(s),f(s);}

```

Basically a recursive function that outputs the string before calling herself again. Its my second post on codegolf so please be nice :p
> 2 votes

# Answer
# Haskell, 21 bytes

```
putStr.cycle.(++"\n")

```
> 2 votes

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

```
i:0(?v
:o71.>~a{

```

Try it online!

As mentioned in the comments below my first attempt may have misunderstood the question so the newer 16 byte solution has been made, I have left the original below so people may see.

# \>\<\>, 13 bytes

```
<ov!?+1:i
oa<

```

Try it online!
> 1 votes

# Answer
# Japt, 5 bytes

```
OpU;ß

```

Try it online!

**Explanation**

```
OpU;     output the input with a newline
    ß    run the code again with the same input

```
> 1 votes

# Answer
# C#, 40 bytes

```
s=>{for(;;)System.Console.WriteLine(s);}

```
> 1 votes

# Answer
# MATL, 4 bytes

```
`GDT

```

**Try it Online**

**Explanation**

```
`     % Do...while loop
  G   % Grab input
  D   % Display it on a new line
  T   % Literal TRUE to create an infinite loop

```
> 1 votes

# Answer
# C, 26 bytes

```
f(char*s){for(;;)puts(s);}

```

A function, `f`, that takes a C-style string as a parameter, `s`. The body of the function loops repeatedly, passing the string to the library function `puts`, which outputs the string to the standard output (stdout) along with a trailing new-line.

Pretty simple stuff. The only hack here is taking advantage of default-int for the return value and then not actually returning a value. That doesn't matter in this case, though, since the function never returns (it just keeps printing forever)!

Try it online!
> 1 votes

# Answer
# CJam, 6 bytes

```
q{_n}h

```

Try it online!
> 1 votes

# Answer
# Pyth, 2 bytes

```
#

```

~~Unfortunately I can't remove `Q` :(~~

You need to run from command-line like this, so that this is competing:

```
python3 pyth.py -c "#
"

```

The interpreter has been fixed too.
> 1 votes

# Answer
# Groovy, 20 bytes

```
x={println it;x(it)}

```
> 1 votes

# Answer
# Java 8, 34 bytes

```
s->{for(;;System.out.println(s));}

```

Surprised there wasn't a Java answer yet.

Try it here. (Wait 60 second for it to time-out.)
> 1 votes

# Answer
# Perl 5, 27 bytes

```
while(1){print"$ARGV[0]\n"}

```

Try it online!
> 1 votes

# Answer
## SAS, 32 bytes

```
%macro t(s);%put&s;%t(&s);%mend;

```
> 1 votes

# Answer
## PowerShell, 17 bytes

This one taking a reasonable position towards the shorter end of the non-golf-langs:

```
$f={for(){$args}}

```

The infinite recursion approach works, at least for a while, but isn't as terse:

```
$f={($s="$args");& $f $s}

```
> 1 votes

# Answer
# T-SQL, 45 bytes

```
CREATE PROC r @ TEXT=NULL AS G:PRINT @ GOTO G

```

Usage

```
EXECUTE r 'Hello word!'

```
> 1 votes

# Answer
# Husk, 1 byte

Try it online!

In Husk,  builds an infinite list repeating its argument forever. If a full program produces a list of strings as result, they get printed by joining them with newlines. The wonderful thing about Husk's laziness is that computations involving infinite lists can be managed and used to produce useful output, like in this case :)
> 1 votes

# Answer
# Keg, `-pn`, 2 bytes

```
{⑩

```

Try it online!

Forever, print the top of the stack with a newline without popping it.
> 1 votes

# Answer
# Actually, 6 bytes

```
1W@;.@

```

Try it online!

Explanation:

```
1W@;.@  (implicit input)
1       push 1
 W      loop while top of stack is truthy:
  @       move input to top of stack
   ;.     duplicate and print
     @    move 1 to top of stack to continue loop

```
> 0 votes

# Answer
## QBIC, 3 bytes

```
{?;

```

Explanation

```
{      DO
 ?     PRINT
  ;    a string read from the cmd line
       DO is implicitly closed by EOF

```
> 0 votes

# Answer
# Go, 46 bytes

```
import."fmt"
func f(s string){for{Println(s)}}

```

Try it online!

## Recursive approach, 46 bytes

Surprisingly, a recursive approach led to the same byte count.

```
import."fmt"
func f(s string){Println(s);f(s)}

```

Try it online!
> 0 votes

# Answer
# tcl, 20

```
while 1 {puts $argv}

```

---

demo — on the green area type

```
tclsh main.tcl string you want to repeat

```

where `string you want to repeat` is the input for program.

**DO NOT USE BACKSPACE KEY ON GREEN AREA!** It will make browser go back in history.
> 0 votes

# Answer
# shortC, 7 bytes

```
AWJ@[1]

```

Explanation:

```
A        main function
 W       while loop
  J      print string with newline
   @[1]  first command line argument

```

Try it online!
> 0 votes

# Answer
# Chip, 19+3 = 22 bytes

+3 for flag `-z`, which adds an infinite stream of `0x00` bytes to the end of the input.

```
cCGgbbBAa
fF^~^dDEe

```

Try it online!

The behavior, in pseudocode:

```
out_byte := in_byte
if !(in_byte & 0x60) {
    out_byte |= 0x0A
}

```

Basically, if both bits `0x20` and `0x40` are unset, then either we have a newline character, or we've hit the end of the input. In either case, we just output a newline character and carry on.
> 0 votes

# Answer
# Aceto, 8 bytes

```
>v
np
rk

```

Uses sticky mode to avoid having to duplicate the string.
> 0 votes

# Answer
# OIL, 12 bytes

```
5

4

11
6
2

```

Read a value into the 0th line, print the value in the 0th line, print a newline, then jump to line 2.
> 0 votes

# Answer
# Reticular, 9 bytes

```
i1=v
1`p>

```

Try it online!

## Explanation:

```
i1=        Sets variable 1's value to a single line of input read from STDIN
   v       Change direction to down
   >       Change direction to right, wrap from end of line
1`p        1` fetches the value of variable 1, p prints it

```
> 0 votes

# Answer
# Python 3, 22 bytes

```
while 1:print(input())

```

Surprised not to have seen a python 3 answer yet.
> 0 votes

# Answer
## Vim, 6 bytes

Similar solution as the `V` answer.

```
Yqqp@q

```
> 0 votes

# Answer
# Python 3, 26 bytes

```
a=input()
while 1:print(a)

```

Try it online!

As simple as it gets.
> 0 votes

# Answer
# , 1 byte

It's not an infinitely-repeating built-in. That will be explained in the explanation.

```
I

```

# Explanation

With implicit inputs this becomes:

<pre><code>aPI

  I % An infinite loop with the following body:
a   % Take a single input from the arguments
 P  % Implicitly print the inputted argument on every iteration
    % (The above printing only occurs if the operand expression)
    % hasn't been printed before
```
</code></pre>
> 0 votes

# Answer
# Hy, 34 bytes

```
(setv a(input))(while 1(print a))

```

Try it Online!
> 0 votes

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


title: Filesystem-sort my directory please

text:
# Question
Title: Filesystem-sort my directory please
Sometimes lexicographical sorting of strings may cut it, but when browsing the filesystem, you really need better sorting criteria than just ASCII indices all the time.

For this challenge, given a list of strings representing filenames and folders in a directory, do a filesystem sort, explained below:

1. Split every string into an array of alternating digits (`0123456789`) and non-digits. If the filename begins with digits, insert an empty string at the beginning of the array.
2. For each element in the array, if the element is a string, lexicographically sort all the strings by that element in all lowercase or uppercase. If the element is a number, sort by numerical order. If any files are tied, continue to the next element for more specific sorting criteria.

Here is an example, starting with strings that are initially sorted lexicographically:

```
Abcd.txt
Cat05.jpg
Meme00.jpeg
abc.txt
cat.png
cat02.jpg
cat1.jpeg
meme03-02.jpg
meme03-1.jpeg
meme04.jpg

```

After step 1, you'll get this:

```
"Abcd.txt"
"Cat", 5, ".jpg"
"Meme", 0, ".jpeg"
"abc.txt"
"cat.png"
"cat", 2, ".jpg"
"cat", 1, ".jpeg"
"meme", 3, "-", 2, ".jpg"
"meme", 3, "-", 1, ".jpeg"
"meme", 4, ".jpg"

```

After step 2, you'll get this:

```
abc.txt
Abcd.txt
cat1.jpeg
cat02.jpg
Cat05.jpg
cat.png
Meme00.jpeg
meme03-1.jpeg
meme03-02.jpg
meme04.jpg

```

Here are the rules:

* You *may not* assume the list of input strings is sorted in any order
* You *may* assume that the input strings only contain printable ASCII characters
* You *may* assume that when the filenames are converted to all lowercase or all uppercase, there will be no duplicates (i.e., a case-insensitive filesystem)
* Input and output may be specified via any approved default method
* Standard loopholes apply

Here is an example implementation of the sorting algorithm if there is any confusion:

```
function sort(array) {
  function split(file) {
    return file.split(/(\D*)(\d*)/);
  }

  return array.sort((a, b) => {
    var c = split(a);
    var d = split(b);

    for (var i = 0; i < Math.min(c.length, d.length); i++) {
      var e = c[i].toLowerCase();
      var f = d[i].toLowerCase();

      if (e-f) {
        return e-f;
      }

      if (e.localeCompare(f) !== 0) {
        return e.localeCompare(f);
      }
    }

    return c.length - d.length;
  });
}

```

This is , so shortest answer wins!

# Answer
# Jelly, 26 bytes

```
VµŒlµœ&ØDµ?
e€ØDI0;œṗ⁸Ç€µÞ

```

**Try it online!** (The footer code, `ÇY`, just splits the resulting list of strings with line feeds for legibility)

### How?

```
VµŒlµœ&ØDµ? - Link 1, evaluate a substring: substring
 µ  µ    µ? - ... then / else / if ...
       ØD   - if:   decimal digit characters '0123456789'
     œ&     -       multi-set intersection, effectively "all digits"?
V           - then: eval, cast the digit strings to integers
  Œl        - else: convert to lowercase, cast the char strings to lowercase

e€ØDI0;œṗ⁸Ç€µÞ - Main link: list of filenames
            µ  - monadic chain separation
             Þ - sort the filenames by the key function, given a single filename:
  ØD           - decimal digit character yield, '0123456789'
e€             - exists in for €ach -> a list of 0s at chars and 1s at digits
    I          - increments -> 1s and -1s at changeover indexes - 1, 0s elsewhere, 0s
     0;        - prepend a zero -> 1s and -1s at changeover indexes, 0s elsewhere
         ⁸     - left argument, the filename
       œṗ      - partition at the truthy indexes (the 1s and -1s)
          Ç€   - call the last link (1) as a monad for €ach substring

```
> 2 votes

# Answer
# Bean, ~~116~~ ~~121~~ 118 bytes

Hexdump:

```
00000000 26 55 cd a0 62 80 40 a0 6f 53 d0 80 d3 d0 80 a0  &UÍ b.@ oSÐ.ÓÐ.
00000010 6f 20 80 0d 21 80 81 00 20 80 92 20 6f 53 d0 80  o ..!... .. oSÐ.
00000020 a0 78 20 80 83 40 a0 5d a0 5e 53 d0 80 d3 a0 62   x ..@ ] ^SÐ.Ó b
00000030 20 5d 20 80 8b 40 a0 5f a0 60 a0 65 a0 6e dd a0   ] ..@ _ ` e nÝ
00000040 61 50 84 d3 a0 62 20 5e 20 65 4e ce a0 5f 80 4c  aP.Ó b ^ eNÎ _.L
00000050 a0 60 8c 20 61 80 53 d0 80 d3 50 80 a0 60 20 80   `. a.SÐ.ÓP. ` .
00000060 b9 20 80 b3 53 50 80 a0 61 20 80 b9 a8 dc c4 aa  ¹ .³SP. a .¹¨ÜÄª
00000070 a9 a8 dc e4 aa 29                                ©¨Üäª)
00000076

```

Equivalent JavaScript (140 bytes, ignoring added whitespace for formatting):

```
f=s=>s.split(/(\D*)(\d*)/).concat(s),
_.sort(
  (a,b)=>f(a).reduce(
    (c,d,i,r,e=f(b)[i])=>
      c||d-e||d.toLowerCase().localeCompare(e.toLowerCase())
  )
)

```

Basically a golfed version of the example implementation given in the question.

Click here for the demo!
> 4 votes

# Answer
## JavaScript (ES6), ~~105~~ ~~110~~ ~~101~~ ~~97~~ 82 bytes

Assumes that each numeric element is up to 99 characters long.

```
a=>a.sort((a,b)=>(F=s=>s.toLowerCase().replace(/\d+/g,n=>n.padStart(99)))(a)>F(b))

```

### Test

```
let f =

a=>a.sort((a,b)=>(F=s=>s.toLowerCase().replace(/\d+/g,n=>n.padStart(99)))(a)>F(b))

console.log(f([
  'Abcd.txt',
  'Cat05.jpg',
  'Meme00.jpeg',
  'abc.txt',
  'cat.png',
  'cat1.jpeg',
  'cat02.jpg',
  'meme03-1.jpeg',
  'meme03-02.jpg',
  'meme04.jpg'
]).join('\n'))
```
> 3 votes

# Answer
# Perl 6,  ~~50 45~~  44 bytes

```
*.sort:{.lc~~/(\D*)*%%$0=(\d+)/;map {+$_//~$_},@0}

```

Try it

```
*.sort:{/(\D*)*%%$0=(\d+)/;map {+$_//.lc},@0}

```

Try it

```
*.sort:{/(\D*)*%$0=(\d+)/;map {+$_//.lc},@0}

```

Try it

## Expanded:

```
* # Whatever lambda ( this is the argument )

.sort: # sort by doing the following to each value

{  # bare block lambda with implicit parameter ｢$_｣
  /
    (      # stored in $0
      \D*                  # any number of non-digits
    )*                     # any number of times
    %                      # separated by
    $0 = ( # stored in $0
      \d+                  # at least one digit
    )
  /;

  map {
    +$_    # try to turn the element into a number
    //     # if that fails
    .lc    # lowercase it
  },
  @0       # for all the elements
}

```
> 1 votes

# Answer
# JavaScript (ES2020), 54 bytes

```
a=>a.sort(new Intl.Collator('en',{numeric:1}).compare)

```

Uses the `Intl.Collator` builtin to provide the natural sort order.

### Test

```
const f =

a=>a.sort(new Intl.Collator('en',{numeric:1}).compare)

console.log(f([
  'Abcd.txt',
  'Cat05.jpg',
  'Meme00.jpeg',
  'abc.txt',
  'cat.png',
  'cat1.jpeg',
  'cat02.jpg',
  'meme03-1.jpeg',
  'meme03-02.jpg',
  'meme04.jpg'
]))
```
> 0 votes

---
Tags: code-golf, sorting
---


title: KoTH: Wizard Battle

text:
# Question
Title: KoTH: Wizard Battle
In this challenge, all bots are wizards. At the beginning of each round, they create a wand which has a certain chance of successfully stunning another wizard. They then fight, by choosing one bot to attack in each turn. The last bot remaining wins.

### Results

500 games, 1000 rounds each

```
Revenge!: 132101.68886125216
JustEnough: 125373.84608578209
Copycat: 118350.98257686458
Climber: 100280
UpperMiddleClassHunter: 99618.4944296837
Golden: 92541.83731532418
Bully: 84120
TallPoppyLoper: 81359.05734216684
A Wizard Arrives Precisely When He Means To: 81218.40354787472
The Wild Card: 77687.08356861532
My First Bot: 74766.78481191777
Roulette Wheel: 67559.90399160102
Don't Kill Me: 58361.64359801064
Marginally Lower Threat: 40538.27420692073
Simple Threat Neutralizer: 13957
ThereCanOnlyBeOneStrongest: 13000
The Terminator: 3701
SimpleSimon: 3295
Peace Lover: 0
Pacifist: 0

```

### Game details

* A game consists of a number of rounds
* At the beginning of each round, all bots choose the success chance of their wand (0 to 1, inclusive, defaults to 0 if invalid)
* A round will last until one bot remains, or all remaining bots have a 0% chance of winning
    + In each turn, every bot must choose a bot to attack
    + If an attack succeeds (based on the wand's success chance), the bot who is attacked is eliminated for the rest of the round
* The last bot alive wins `1/sqrt(chance)` points (up to a maximum of 20), where `chance` is the wand's success chance
* If all remaining bots are eliminated in the same turn, no points are awarded
* The bot with the most points after a certain number of games wins

### Bot format

Each bot should consist of two JavaScript functions, the first of which is run once per turn. This function will be provided three arguments:

* Itself as an object (see below for format)
* An array containing all other non-eliminated bots
    + Each bot is formatted as an object
    + Each bot contains a `uid` property, which is an integer ID randomly chosen for each game
    + Each bot contains a `wand` property, which contains their wand's success chance
    + Each bot contains a `attacked` property, which contains the UID of the last bot they attempted to attack (or null if first turn)
* A storage object
    + Can be used for storage between turns or rounds (resets for each game)

The return value of this function should be the UID of the bot to attack.

A second function will choose its wand's success chance before the first turn of each round, and will be provided one argument, its storage object.

### Example bot

Example bot will attack a random (valid) bot that another bot attacked last turn, even itself. Always chooses a 75% wand success chance.

```
//Turn

function (self, others, storage) {
    var attacked = others.map(bot => bot.attacked).filter(uid => others.find(bot => bot.uid == uid));
    return attacked[Math.random() * attacked.length | 0] || others[0].uid;
}

//Wand

function (storage) {
    return 0.75;
}

```

### Controller

```
//Bots go in this object:

var bots = {
    "Example bot": [
        function (self, others, storage) {
            var attacked = others.map(bot => bot.attacked).filter(uid => others.find(bot => bot.uid == uid));
            return attacked[Math.random() * attacked.length | 0] || others[0].uid;
        },
        function (storage) {
            return 0.75;
        }
    ]
};

//games: Number of games to run
//rounds: Number of rounds per game
//turns: Max turns per game
//log: 0 (no logging), 1 (errors only), 2 (detailed logging)

function runGames(games = 100, rounds = 100, turns = 1000, log = 0) {
    let p = performance.now();
    let botData = [];
    for (let bot in bots)
        botData.push({
            name: bot,
            turn: bots[bot][0],
            round: bots[bot][1],
            uid: 0,
            alive: !0,
            wand: 0,
            attacked: 0,
            points: 0,
            storage: {}
        });
    for (let g = 0; g < games; g++) {
        let uids = new Array(botData.length).fill(0).map((a, b) => b);
        let round = 0;
        for (let j, i = uids.length - 1; i > 0; i--) {
            j = Math.floor(Math.random() * (i + 1));
            [uids[i], uids[j]] = [uids[j], uids[i]];
        }
        for (let i = 0; i < botData.length; i++) {
            botData[i].uid = uids[i];
            botData[i].storage = {};
        }
        for (let r = 0; r < rounds; r++) {
            let turn = 0;
            if (log >= 2)
                console.log("[0] Starting round " + (g + 1) + "-" + (r + 1));
            for (let b, i = 0; i < botData.length; i++) {
                b = botData[i];
                try {
                    b.wand = Math.max(0, Math.min(1, Number(b.round(
                        b.storage
                    ))));
                } catch(e) {
                    b.wand = 0;
                    if (log)
                        console.warn("[" + turn + "] " + b.name + "[1]:\n" + (e.stack || e.message));
                }
                if (Number.isNaN(b.wand))
                    b.wand = 0;
                if (log >= 2)
                    console.log("[" + turn + "] " + b.name + " (" + b.uid + "): " + (b.wand * 100) + "%");
                b.alive = !0;
                b.attacked = null;
            }
            do {
                let attacks = [];
                let max, alive = [];
                turn++;
                for (let b, i = 0; i < botData.length; i++) {
                    b = botData[i];
                    if (!b.alive)
                        continue;
                    try {
                        attacks[i] = b.turn(
                            {
                                uid: b.uid,
                                wand: b.wand,
                                attacked: b.attacked
                            },
                            botData.filter(a => a.alive && a.uid != b.uid).map(a => ({
                                uid: a.uid,
                                wand: a.wand,
                                attacked: a.attacked
                            })).sort((a, b) => a.uid - b.uid),
                            b.storage
                        );
                    } catch(e) {
                        attacks[i] = !1;
                        if (log)
                            console.warn("[" + turn + "] " + b.name + "[0]:\n" + (e.stack || e.message));
                    }
                }
                for (let b, i = 0; i < botData.length; i++) {
                    b = botData[i];
                    if (!b.alive)
                        continue;
                    if (!botData.find(a => a.alive && a.uid === attacks[i])) {
                        b.alive = !1;
                        if (log >= 2)
                            console.log("[" + turn + "] " + b.name + " (" + b.uid + "): Invalid bot (" + attacks[i] + ")");
                        attacks[i] = undefined;
                    }
                    b.attacked = attacks[i];
                }
                for (let b, i = 0; i < botData.length; i++) {
                    b = botData[i];
                    if (attacks[i] === undefined)
                        continue;
                    if (Math.random() < b.wand) {
                        if (log >= 2)
                            console.log("[" + turn + "] " + b.name + " (" + b.uid + "): Attacked " + botData.find(a => a.uid == attacks[i]).name + " (" + attacks[i] + ")");
                        botData.find(a => a.uid == attacks[i]).alive = !1;
                    } else if (log >= 2) {
                        console.log("[" + turn + "] " + b.name + " (" + b.uid + "): Failed to attack " + botData.find(a => a.uid == attacks[i]).name + " (" + attacks[i] + ")");
                    }
                }
                alive = botData.filter(a => a.alive);
                if (alive.length == 1)
                    alive[0].points += Math.min(20, 1 / Math.sqrt(alive[0].wand));
                if (alive.length <= 1) {
                    if (log >= 2)
                        console.log("[" + turn + "] Winner of round " + (g + 1) + "-" + (r + 1) + ": " + (alive.length ? alive[0].name : "No winner"));
                    break;
                }
            } while (turn < turns);
        }
    }
    console.log(games + " game(s) completed (" + ((performance.now() - p) / 1000).toFixed(3) + "s):\n" + botData.map(a => [a.name, a.points]).sort((a, b) => b[1] - a[1]).map(a => a[0] + ": " + a[1]).join("\n"));
}

```

### Rules

* Accessing the controller or other bots is not allowed
* There's no time limit, but keep within reason
* Any bots that error or choose an invalid bot to attack are eliminated
* Deadline: **Challenge finished** ~~Friday, April 3, 12:00 UTC (8:00 EDT)~~

**Clarification:** Wand success chance is only chosen at the beginning of each round, not once per turn.

# Answer
# Revenge!

A bot that always takes revenge on the bot that attacked it the most thus far, with just a 0.5% wand success rate:

```
'Revenge!': [
  function(self, others, storage){
    // Initialize attackLog the first round:
    if(storage.attackLog == null)
      storage.attackLog = {};

    // Update the attackLog:
    others.forEach(other => {
      if(storage.attackLog[other.uid] == null)
        storage.attackLog[other.uid] = 0;
      if(other.attacked == self.uid)
        storage.attackLog[other.uid]++;
    });

    // Filter from the remaining bots the one that attacked you the most thus far:
    var attackedMostBy = null;
    var maxAttackedBy = 0;
    others.forEach(other => {
      if(storage.attackLog[other.uid] > maxAttackedBy){
        attackedMostBy = other;
        maxAttackedBy = storage.attackLog[other.uid];
      }
    });

    // If the bots that are left never attacked you: just attack one at random:
    return attackedMostBy == null ? others[Math.random()*others.length|0].uid
    // Else: take revenge on the bot that attacked you the most thus far:
                                  : attackedMostBy.uid;
  },
  function(storage){
    // 0.25% is the lowest wand success rate that is still within the max of 20 boundary,
    // so we'll use twice that wand success rate of 0.5% for a score of roughly 14.1 each
    return 0.005;
  }
]

```

Try it with all current bots. It seems to be doing quite well, since it's usually in second place.
> 5 votes

# Answer
# Golden

Uses the golden ratio, which, if my calculations are correct, is a Nash equilibrium solution to the two-player game. Attacks the most deadly if there is still more than one opponent.

```
"Golden": [
    function(self, others, storage) {
        var targ;
        for (var i in others) {
            if (targ == null || others[targ].wand < others[i].wand)
                targ = i
        }
        return others[targ].uid;
    },
    function(storage) {
        return 0.381966;
    }
]

```

Try it online!
> 6 votes

# Answer
# Bully

```
"Bully": [
    function attack(self, others, storage) {
        minWand = Math.min(...others.map(bot => bot.wand));
        targets = others.filter(bot => bot.wand === minWand);
        return targets[Math.random() * targets.length | 0].uid;
    },

    function wandChance(storage) {
        return 0.0025;
    }
]

```

Only targets the "weakest" bots, aka bots with the lowest wand success chance.

Test all current bots!
> 5 votes

# Answer
# Climber

Always target the bot who, by our calculation, looks to have the highest score. Keeps a 1% wand for the 10 point payout if he wins.

```
"Climber": [
    function(me, them, storage) {
        storage.current = them.slice(0);
        fromEntries = function(arr){
            var obj = {};
            for(var pair of arr) obj[pair[0]] = pair[1];
            return obj
        }
        if(!storage.scores)
            storage.scores = fromEntries(them.map(x => [x.uid, 0]));

        var targ;
        for (var i in them) {
            if (targ == null || storage.scores[targ] < storage.scores[them[i].uid])
                targ = them[i].uid;
        }
        return targ;
    },
    function(storage) {
        if(storage.scores){
            for(var bot of storage.current)
                // divide the score by the number of bots that could have won
                storage.scores[bot.uid] +=
                           Math.max(Math.pow(bot.wand, -1/2), 20) /
                             (storage.current.length + 1);
        }
        return 0.01;
    }
]

```
> 5 votes

# Answer
# Upper Middle Class Hunter

```
"UpperMiddleClassHunter": [
    function(self, others, storage) {
        var myOthers = others;
        myOthers.sort((a, b) => a.wand - b.wand);
    return myOthers[myOthers.length * 0.8 | 0].uid;
    },
    function(storage) {
        return 0.333;
    }
],

```

It hunts the upper middle class bots knowing that the supreme bots will kill each other and be targets from other bots and so it doesn't need to target them. Nor will it hunt the lower bots as they also are targeted by others. Instead hunt the bots that are not the strongest but could be a threat.

It attacks with a 1/3 chance of winning, seeking a balance to kill of the threatening bots, but still gain a reasonable score if winning a round.

Its simplicity hides its effectiveness... in my tests it is either winner or runner up after 500 games.
> 4 votes

# Answer
# Peace Lover

**Not** a troll entry! *...probably.*

```
function attack(me, alive) {
    const them = alive.filter(bot => bot.uid !== me.uid);
    const attackers = them.filter(bot => bot.attacked === me.uid);

    function getMaxWand(bots) {
        return Math.max(...bots.map(bot => bot.wand));
    }
    function hasWand(wand) {
        return bot => bot.wand === wand;
    }

    function getTargets(bots) {
        return bots.filter(hasWand(getMaxWand(bots)));
    }
    const primaryTargets = getTargets(attackers);
    const secondaryTargets = getTargets(them);

    function getRandomValue(array) {
        return array[Math.random() * array.length | 0];
    }

    return (getRandomValue(primaryTargets) || getRandomValue(secondaryTargets)).uid;
}
function chooseChance() {
    return 0;
}

```

Points its useless wand according to an improved version of the heuristic of this other entry of mine.

**Note:** This entry didn't work properly because of a bug in the controller, but along with the bug fix came a limit of a measly `20` instead of the `Infinity` that can be inferred from the spec imposed on the score per win...
> 3 votes

# Answer
# JustEnough

Targets the strongest of the lowest third of opponents using a wand that is slightly stronger.

Otherwise, targets the first opponent with almost full power unless less than three opponents exist, then use almost no power.

```
"JustEnough": [
    function(self, others, storage) {

        var targ;
        storage.wand = 0.002;

        var multiplier = 1.01;
        if (others.length > 2){
           multiplier = 1.25;
           storage.wand = 0.99;
        }

        for (var i in others) {
            if ( others[i].wand < 0.3)
            {
                if (targ == null || others[i].wand > others[targ].wand) {
                   targ = i;
                   storage.wand = others[targ].wand * multiplier ;
                   if (storage.wand > .99) storage.wand = 0.99;
                }
            }
        }

        if (targ == null)
        {
           targ = 0;
        }

        return others[targ].uid;
    },
    function(storage) {
        return storage.wand;
    }
]

```

Bot derived from MegaTom's entry: Golden
> 3 votes

# Answer
# My First Bot

This is my first attempt at entering a KotH competition and I don't know what I'm doing.

It literally just hits everyone in turn for a damage value which seemed to be returning good results.

```
    'My First Bot': [
      function(self, others,storage) {
        if(typeof storage.n == 'undefined'){
          storage.n = 0;
        }
        if(others[storage.n]){
          return others[storage.n].uid;
        } else {
          storage.n = 0;
          return others[0].uid;
        }
      },
      function(storage) {
        return 0.009;
      }
    ]

```
> 3 votes

# Answer
# A Wizard Arrives Precisely When He Means To

```
'A Wizard Arrives Precisely When He Means To': [
  function(self, others, storage){
    // Store the amount of bots left:
    storage.numBots = others.length;

    // Get the bots within the highest 10% wand success rate:
    var strongOnes = [];
    for(var wandTreshold = 0.9; strongOnes.length == 0; wandTreshold -= 0.1)
      var strongOnes = others.filter(o => o.wand >= wandTreshold);
    // And pick a random one of those strong bots to attack:
    return strongOnes[Math.random()*strongOnes.length|0].uid;
  },
  function(storage){
    // Increase the round number (or initialize at 1 the first round):
    storage.round = storage.round == null ? 1 : storage.round+1;

    // If just one or two bots are left: increase wand success rate to 100%
    return storage.numBots <= 2 ? 1
    // If there are more than two bots are left: use wand success rate dependent on the round
                                : Math.max(1 / storage.round - 0.01, 0.001);
  }
]

```

This bot does a couple of things:

1. It lowers its own wand success rate \\$SR\\$ based on the round number \\$r\\$, using the formula: \\$SR\_r\text{ (in %)}=\frac{1}{round}\times100-1\\$, which will progress like this: \\$SR\_r=\[99, 49, 32\frac{1}{3}, 24, 19, 15\frac{2}{3}, 13\frac{2}{7}, 11\frac{1}{2}, 10\frac{1}{9},9, ...\]\\$, unless this is below 0.1%, in which case it'll use that instead. Also, it will use a 100% wand success rate, if there are just two or three bots (including itself) left in play.
2. It will attack a random bot within the top 10% ranged wand success rate (i.e. \\$\[90\\%, 100\\%\]\\$ until all those are eliminated, then \\$\[80\\%, 90\\%)\\$ until all those are eliminated, etc. So let's say the bots left have a wand success rate of `[83%, 75%, 50%, 1%, 25%, 82.5%, 50%, 50%, 72.5%, 85%]` it will pick a random both in the range \\$\[80\\%, 90\\%)\\$, thus one of the bots `[83%, 82.5%, 85%]`.

From the current bots, this bot usually ends up somewhere in the middle, so not too great, but also not last: Try it with all current bots.
> 3 votes

# Answer
# The Terminator

**Turn**

```
function (self, others, storage) {
    var attacked = others.map(bot => bot.attacked).filter(uid => others.find(bot => bot.uid == uid));
    return attacked[Math.random() * attacked.length | 0] || others[0].uid;
}

```

**Wand**

```
function (storage) {
    return 1.00;
}

```

*Listen, and understand! That The Terminator is out there! It can't be bargained with. It can't be reasoned with. It doesn't feel pity, or remorse, or fear. And it absolutely will not stop... ever, until you are dead!*
> 2 votes

# Answer
# Simple Threat Neutralizer

Just to get this challenge going a bit, perhaps...

```
function attack(me, them) {
    them = them.filter(bot => bot.uid !== me.uid);
    const maxWand = Math.max(...them.map(bot => bot.wand));
    const attackers = them.filter(bot => bot.attacked === me.uid);
    return (attackers.filter(bot => bot.wand === maxWand)[0] || them.filter(bot => bot.wand === maxWand)[0]).uid;
}
function chooseChance() {
    return 1;
}

```

Chooses bots with a simple danger heuristic - first bots that have attacked it in the previous turn, then all the rest. Sort by most powerful wand and target the first in the array.
> 2 votes

# Answer
# Tall Poppy Loper

Has a major case of Tall Poppy Syndrome and will elminate that bot.

It also has an irrational fear of others' potential so will elminate bots that threaten its supremancy.

```
"TallPoppyLoper": [
    function(self, others, storage) {

        if (storage.history == null )
        {
            storage.history = {};
            storage.selfuid = self.uid;
            storage.roundNo = 0;

            for (var i in others) {
                var historyBot = {};
                historyBot.alive = true;
                historyBot.killCount = 0;
                storage.history[others[i].uid] = historyBot;
            }
        }
        else if (self.attacked === null)
        {
            storage.roundNo = storage.roundNo + 1;
        }

        for (var i in others) {
            storage.history[others[i].uid].alive = true;
        }

        var targ;
        for (var i in others) {

            if (others[i].attacked != self.uid && others[i].attacked !=null && !storage.history[others[i].attacked].alive) {
                storage.history[others[i].uid].killCount = storage.history[others[i].uid].killCount + 1;
            }

            if (targ == null || storage.history[others[targ].uid].killCount < storage.history[others[i].uid].killCount)
            {
                targ = i
            }
        }

        for (var i in others) {
            storage.history[others[i].uid].alive = false;
        }

        return others[targ].uid;
    },
    function(storage) {
        return 0.95;
    }
]

```

Bot derived from MegaTom's entry: Golden
> 2 votes

# Answer
# Roulette Wheel

Every action taken is uniformly random.

```
"Roulette Wheel": [
  function (self, others, storage) {
    return others[Math.random() * others.length | 0].uid //Random target out of all opponents
  },
  function (storage) {
    return 0.0025 + Math.random() * 0.9975 //Random strength in range [1/400, 1]
  }
]

```
> 2 votes

# Answer
# The Wild Card

Chooses a wand success chance at random from the set {0.1, 0.2, ..., 0.9}, favouring values closer to 0.5. Each turn, it makes a decision to either attack a bot who previously attacked it or attack at random.

```
'The Wild Card': [
  function(self, others, storage){
    // Keep a list of the bots who we hold grudges against
    if (!storage.enemies) storage.enemies = [];

    // Update our list of enemies
    others.forEach(o =>{
        if (o.attacked === self.uid && !storage.enemies.includes(o.uid)){
           storage.enemies.push(o.uid);
        }
    });

    // Filter out bots that have been eliminated
    storage.enemies = storage.enemies.filter(x => others.map(o => o.uid).includes(x));

    if (Math.random() > storage.wand || storage.enemies.length === 0){
        // Our wand couldn't beat a random number
        return others[Math.random() * others.length | 0].uid
    }

    // Our wand was stronger than a random number - attack one of our "enemies"
    return storage.enemies[Math.random() * storage.enemies.length | 0];
  },
  function(storage){
    // Reset the enemies list at the start of each round
    storage.enemies = [];

    // Randomly assign a wand success rate (favours values closer to 0.5)
    var u = Math.random();
    var randNum = 0.9
    if (u < 0.3) randNum = 0.5
    else if (u < 0.5) randNum = 0.4
    else if (u < 0.7) randNum = 0.6
    else if (u < 0.8) randNum = 0.3
    else if (u < 0.9) randNum = 0.7
    else if (u < 0.925) randNum = 0.2
    else if (u < 0.95) randNum = 0.8
    else if (u < 0.975) randNum = 0.1

    // Store our wand success rate to use when choosing a target
    storage.wand = randNum;

    return randNum;
  }
],

```

Try it against current bots
> 2 votes

# Answer
# Don't Kill Me

Survives by staying the *second* most dangerous wizard throughout the game, so **there's always a bigger fish to fry**. Scores pretty high.

```
"Don't Kill Me": [
    function attack(self, others, storage) {
        storage.left = others.length
        maxWand = Math.max(...others.map(bot => bot.wand))
        storage.safeWand = Math.max(...others.filter(bot => bot.wand != maxWand).map(bot => bot.wand))
        return others.filter(bot => bot.wand === maxWand)[0].uid
    },

    function wandChance(storage) {
        return storage.safeWand ? ((storage.left > 1) ? storage.safeWand : 0.01) : 0.1
    }
]

```

Try it Online!
> 2 votes

# Answer
# Copycat

Attempts to make it to the late stages of a round, then copy the average wand strength of the remaining bots when there are 1 or 2 other bots left.

Targets bots with wand strength between 0.1 and 1 (exclusive).

```
"Copycat": [
    function(self, others, storage) {
        // Copy the strategy of the bots that make it to the end
        if (others.length == 2){
            storage.strength = (others[0].wand + others[1].wand) / 2;
        } else if (others.length == 1) {
            storage.strength = others[0].wand;
        }

        // Filter out the highest and lowest strength bots
        var filteredOthers = others.filter(a => a.wand < 1 && a.wand > 0.1);

        if (filteredOthers.length > 0)
            return filteredOthers[Math.random() * filteredOthers.length | 0].uid;
        return others[Math.max(0, others.length - 2)].uid;
    },
    function(storage) {
        // Prevent overfitting: discard the copied strategy with 1/10 probability
        if (!storage.strength || Math.random() <= 0.1){
            storage.strength = 0.025;
        }

        return storage.strength;
    }
],

```

Try it against the other bots
> 2 votes

# Answer
# There Can Only Be One Strongest

Simply chooses the strongest remaining bot and attacks at full power!

```
"ThereCanOnlyBeOneStrongest": [
    function(self, others) {
        var targ;
        for (var i in others) {
            if (targ == null || others[targ].wand < others[i].wand)
                targ = i
        }
        return others[targ].uid;
    },
    function(storage) {
        return 1;
    }
]

```

Bot derived from MegaTom's entry: Golden
> 1 votes

# Answer
# Simple Simon

Simply chooses the first bot in the collection of other opponents and attacks at full power

```
"SimpleSimon": [
    function(self, others) {
        return others[0].uid;
    },
    function(storage) {
        return 1;
    }
]

```

Bot derived from MegaTom's entry: Golden
> 1 votes

# Answer
# Pacifist

Thinks wizard battles are not cool and will not target anyone.

```
"Pacifist": [
    function(self, others) {
        return others[0].uid;
    },
    function(storage) {
        return 0;
    }
]

```

Bot derived from MegaTom's entry: Golden
> 1 votes

# Answer
# Marginally Lower Threat

```
"Marginally Lower Threat": [
  function (self, others, storage) {
    let maxwand = others.reduce((a,b) => Math.max(a,b.wand), 0)
    let maxbots = others.filter(b => b.wand == maxwand)
    return maxbots[Math.random() * maxbots.length | 0].uid
  },
  function (storage) {
    return 0.999
  }
]

```

If bots are going to target the strongest remaining, then why not be just a little less than the strongest? Targets a random strongest bot each turn.
> 1 votes

---
Tags: king-of-the-hill, javascript
---


# Question
Title: What's this constructed number's starter?
A number of programming languages construct large integers through 'concatenating' the digit to the end of the existing number. For example, Labyrinth, or Adapt. By concatenating the digit to the end, I mean that, if the existing number is \\$45\\$, and the digit is \\$7\\$, the result number is \\$457\\:(45 \times 10 + 7)\\$.

A constructed number is a number that can be built this way through the use of the multiples of single digit numbers: \\$1, 2, 3, 4, 5, 6, 7, 8, 9\\$ A.K.A an element in one of these 9 sequences:

$$1, 12, 123, 1234, 12345, \\: \dots$$ $$2, 24, 246, 2468, 24690, \\: \dots$$ $$3, 36, 369, 3702, 37035, \\: \dots$$ $$4, 48, 492, 4936, 49380, \\: \dots$$ $$5, 60, 615, 6170, 61725, \\: \dots$$ $$6, 72, 738, 7404, 74070, \\: \dots$$ $$7, 84, 861, 8638, 86415, \\: \dots$$ $$8, 96, 984, 9872, 98760, \\: \dots$$ $$9, 108, 1107, 11106, 111105, \\: \dots$$

To provide an example of how the sequences are constructed, here's how the sequence for \\$a = 3\\$ in constructed:

$$\begin{align} u\_1 = && a = && 3 & = 3\\ u\_2 = && 10 \times u\_1 + 2 \times a = && 30 + 6 & = 36 \\ u\_3 = && 10 \times u\_2 + 3 \times a = && 360 + 9 & = 369 \\ u\_4 = && 10 \times u\_3 + 4 \times a = && 3690 + 12 & = 3702 \\ u\_5 = && 10 \times u\_4 + 5 \times a = && 37020 + 15 & = 37035 \\ u\_6 = && 10 \times u\_5 + 6 \times a = && 370350 + 18 & = 370368 \\ \end{align}$$ $$\vdots$$ $$\begin{align} u\_{33} = && 10 \times u\_{32} + 33 \times a = && 37\dots260 + 99 & = 37\dots359 \\ u\_{34} = && 10 \times u\_{33} + 34 \times a = && 37\dots359 + 102 & = 37\dots3692 \end{align}$$ $$\vdots$$

\\$u\_{33}\\$ and \\$u\_{34}\\$ included to demonstrate when \\$n \times a \ge 100\\$. A *lot* of digits dotted out for space.

It may still not be clear how these sequences are constructed, so here are two different ways to understand them:

* Each sequence starts from the single digit. The next term is found by taking the next multiple of that digit, multiplying the previous term by \\$10\\$ and adding the multiple. In sequence terms:

$$u\_n = 10 \times u\_{n-1} + n \times a, \\: \\: u\_1 = a$$

where \\$a\\$ is a single digit (\\$1\\$ through \\$9\\$)

* Each of the \\$9\\$ elements at any point in the sequence (take \\$n = 3\\$ for instance) are the multiples of \\$123\dots\\$ from \\$1\\$ to \\$9\\$, where \\$123\dots\\$ is constructed by \\$u\_{n+1} = 10 \times u\_n + n\\$ \\$(1, 12, 123, \dots, 123456789, 1234567900, 12345679011, \dots)\\$

So the first values are \\$1 \times 1, 2, 3, \dots, 8, 9\\$, the second are \\$12 \times 1, 2, 3, \dots, 8, 9\\$, the third \\$123 \times 1, 2, 3, \dots, 8, 9\\$, etc.

Your task is to take a constructed number as input and to output the initial digit used to construct it. You can assume the input will always be a constructed number, and will be greater than \\$0\\$. It may be a single digit, which maps back to itself.

You may take input in any reasonable manner, including as a list of digits, as a string etc. It is acceptable (though not recommended) to take input in unary, or any other base of your choosing.

This is a so the shortest code wins!

## Test cases

```
       u_n        => a
 37035            => 3
 6172839506165    => 5
 5                => 5
 246913580244     => 2
 987654312        => 8
 61728395061720   => 5
 1111104          => 9
 11111103         => 9
 111111102        => 9
 2469134          => 2
 98760            => 8
 8641975308641962 => 7

```

or as two lists:

```
[37035, 6172839506165, 5, 246913580244, 987654312, 61728395061720, 1111104, 11111103, 111111102, 2469134, 98760, 8641975308641962]
[3, 5, 5, 2, 8, 5, 9, 9, 9, 2, 8, 7]

```

---

When I posted this challenge, I didn't realise it could be simplified so much by the method used in Grimmy's answer, and so therefore would be very interested in answers that take a more mathematical approach to solving this, rather than a 'digit' trick (Obviously all valid answers are equally valid, just what I'd be interested in seeing).

# Answer
# 05AB1E, ~~7~~ ~~5~~ 4 bytes

```
>9*н

```

Try it online!

```
>            # input + 1
 9*          # * 9
   н         # take the first digit

```

The \\$(n-1)^{th}\\$ term of the sequence starting with \\$a\\$ is \\$\sum \_{i=1}^{n-1} a \times i \times 10^{i-1} = a \times \frac{(10^n - 1) / 9 - n}{9}\\$. Multiply that by \\$9\\$ and add \\$a\times n\\$, and you get \\$a \times \frac{10^n - 1}{9}\\$, aka the digit \\$a\\$ repeated \\$n\\$ times. Turns out adding \\$9\\$ instead of \\$a\times n\\$ works for \\$n=1\\$, and for bigger \\$n\\$ the linear difference is negligible next to the exponential growth.
> 32 votes

# Answer
# Python 3, 22 bytes

```
lambda i:str(-~i*9)[0]

```

Try it online!

Port of Grimy's 05AB1E answer

---

# Python 3, 72 bytes

```
f=lambda i,j=1,l=1,k=2:l*(i==j)or f(i,*(10*j+k*l,l+1,l,l+1,k+1)[i<j::2])

```

Try it online!

### Explanation

Recursive function. Iterates over the sequence for each digit `l`, starting at `1`. If the input `i` is equal to the current iteration `j`, the corresponding digit `l` is returned. Else, if the current value `j` in the sequence exceeds the input value `i`, it will increment the digit `l` and start over. Argument `k` is used to increment the multiplication factor.
> 3 votes

# Answer
# Stax, 5 bytes

```
^9*Eh

```

Run and debug it
> 3 votes

# Answer
# Labyrinth,  ~~28 22~~  20 bytes

```
9 10/;!@
? _ :
)*"""

```

Applies the digit-based method described by Grimy by repeated integer division by ten until zero is found.

**Try it online!**
> 3 votes

# Answer
# Charcoal, 7 bytes

```
§Ｉ×⁹⊕Ｎ⁰

```

Try it online! Link is to verbose version of code. @Grimy's method of course. Here's a 27 byte mathematical approach:

```
ＮθＷ¬№Ｅχ×κ↨υχθ⊞υＬυＩ⌕Ｅχ×ι↨υχθ

```

Try it online! Link is to verbose version of code. Crashes on invalid inputs. Explanation:

```
Ｎθ

```

Input the constructed number.

```
Ｗ¬№Ｅχ×κ↨υχθ

```

Interpret the list as a number in base 10, multiply by all numbers from `0` to `9`, and see whether the constructed number appears.

```
⊞υＬυ

```

Push the list's length to itself. The list therefore becomes of the form `[0, 1, 2, ..., n]`.

```
Ｉ⌕Ｅχ×ι↨υχθ

```

Recreate the constructed numbers but this time find and output the index at which the input number appeared.
> 3 votes

# Answer
# MathGolf, 6 bytes

```
)9*▒├Þ

```

Try it online!

Unfortunately, there's no `head` operation in MathGolf, so I have to make do with `▒├Þ` to convert to string, pop from the left and discard all but the top of stack.
> 3 votes

# Answer
# Japt `-g`, ~~7~~ ~~6~~ 5 bytes

-1 byte thanks to Shaggy

Takes input as a string

```
i°U*9

```

Try it | Test multiple inputs
> 2 votes

# Answer
# Jelly, 5 bytes

```
‘×9DḢ

```

Try it online!

Using Grimy's approach.
> 2 votes

# Answer
# Java 8, 23 bytes

```
n->(n*9+9+"").charAt(0)

```

Port of *@Grimy*'s 05AB1E answer, so make sure to upvote him!

Try it online.

But because I kinda feel bad for *@cairdCoinheringaahing*, here a brute-force approach with a bit more afford (**83 bytes**):

```
n->{long r=n,a=0,u,k;for(;++a<10;r=u>n?r:a)for(k=2,u=a;u<n;)u=u*10+k++*a;return r;}

```

Try it online.

**Explanation:**

```
n->{                 // Method with long as both parameter and return-type
  long r=n,          //  Result, starting at the input in case it's already a single digit
       a=0,          //  The digit to start the sequence with
       u,            //  The last number of the sequence we're building for digit a
       k;            //  Multiplier which increments each iteration
  for(;++a<10;       //  Loop in the range [1,9] (over each digit):
      r=u>n?         //    After ever iteration: if `u` is larger than the input:
            r        //     Keep the result the same
           :         //    Else:
            a)       //     Change the result to `a`
    for(k=2,         //   Reset `k` to 2
        u=a;         //   Reset `u` to the current digit `a`
        u<n;)        //   Inner loop as long as `u` is smaller than the input
      u=             //    Change `u` to:
        u*10         //     10 times the current `u`
            +k++*a;  //     With `k` multiplied by `a` added
                     //     (after which `k` increases by 1 with `k++`)
  return r;}         //  And after we iterated over each digit, return the result

```
> 2 votes

# Answer
# Whitespace, 108 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][S S S T    N
_Push_1][T  S S S _Add][S S S T S S T   N
_Push_9][T  S S N
_Multiply][S S S T  N
_Push_1][N
S S N
_Create_Label_LOOP][S S S T S T S N
_Push_10][T S S N
_Multiply][S N
S _Duplicate][S T   S S S T S N
_Copy_0-based_2nd]S N
T   Swap_top_two][T S S T   _Subtract][N
T   T   S N
_If_neg_jump_to_Label_PRINT][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT][S S S T    S T S N
_Push_10][T S T S _Integer_divide][T    S T S _Integer_divide][T    N
S T _Output_top_as_number]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Port of *@Grimy*'s 05AB1E answer, except that I don't have a builtin to get the first digit. ;)

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer i = STDIN as integer
i = i + 1
i = i * 9
Integer t = 1
Start LOOP:
  t = t * 10
  If(i - t < 0):
    Call function PRINT
  Go to next iteration of LOOP

function PRINT:
  t = t / 10
  i = i / t    (NOTE: Whitespace only has integer-division)
  Print i as integer to STDOUT

```
> 2 votes

# Answer
# JavaScript (ES6),  ~~16~~  15 bytes

*Thanks to @Grimy for lifting the 32-bit constraint I had with the previous version.*

Using Grimy's magical incantation. Takes input as a string.

```
n=>(n*9+9+n)[0]

```

Try it online!

---

# JavaScript (ES6), 53 bytes

Naive brute force approach.

```
n=>(g=(k,x=i=0)=>x>n?g(k+1):x<n?g(k,++i*k+10*x):k)(1)

```

Try it online!
> 1 votes

# Answer
# PHP, 20 bytes

```
<?=(_.++$argn*9)[1];

```

Try it online!

Yet another Grimy's answer port!
> 1 votes

# Answer
# Jelly, 8 bytes

```
RRḌ÷@fⱮ9

```

Try it online!

A full program that takes an integer and prints the starter digit. Doesn’t use Grimy’s clever method! Terribly inefficient for larger input. The following version handles all of the test cases but is a byte longer:

# Jelly, 9 bytes

```
DJRḌ÷@fⱮ9

```

Try it online!
> 1 votes

# Answer
# Hy, 44 bytes

```
(defn a[p](print(get(str(*(+(int p)1)9))0)))

```

Uses Grimy's method

Try it online!
> 1 votes

# Answer
# Keg `-rr`, 4 bytes

```
⑨9*÷

```

Try it online!

Of course, uses the same approach as the 05AB1E answer. Also uses the new `-rr` (reverse and print raw) flag.

Transpiles to:

```
from KegLib import *
from Stackd import Stack
stack = Stack()
printed = False
increment(stack)
integer(stack, 9)
maths(stack, '*')
item_split(stack)
if not printed:
    reverse(stack)
    raw(stack)

```
> 1 votes

# Answer
# Wren, 30 bytes

Just a port of most answers.

```
Fn.new{|i|(i*9+9).toString[0]}

```

Try it online!
> 1 votes

# Answer
# `h`, 3 bytes

```
)9*

```

# Explanation

)   % Increment by 1
 9* % Multiply by 9

Flag:h % Take the first item of the result
```
</code></pre>
> 1 votes

# Answer
# cQuents, 10 bytes

```
D9*_+$)[0]

```

Try it online!

Just another port of Grimmy's answer.

```
     $     # Index
   _+      # +1
 9*        # *9
D     )[0] # First digit

```
> 1 votes

---
Tags: code-golf, number, sequence
---


title: Mirror and reverse text

text:
# Question
Title: Mirror and reverse text
Inspired by I reverse the source code, ...

Your task, if you wish to accept it, is to reverse text and mirror select characters. Yes, yes, I know. Very surprising.

## Input

A string, `stdin`, an array of characters, or any other source of text. All characters of the input are guaranteed to be in the printable ASCII range (32-126).

## Output

The reversed text with some characters mirrored. To do this:

* You replace any occurrences of the characters `(`, `)`, `/`, `\`, `<`, `>`, `[`, `]`, `{`, or `}` in the text with the corresponding "mirrored" character: `)`, `(`, `\`, `/`, `>`, `<`, `]`, `[`, `}`, or `{`.
* and then reverse the text.

You may assume a maximum line length of 255.

## Rules

* Standard loopholes apply.
* This is , which means that the shortest answer in each programming languages wins. Consequently, I will not be accepting an answer.

## Testcases

```
(s)t/r\i<n>g[i]e{s} -> {s}e[i]g<n>i/r\t(s)
stringies -> seignirts
()/\<>[]{} -> {}[]<>/\()
{s}e[i]g<n>i/r\t(s) -> (s)t/r\i<n>g[i]e{s}
seignirts -> stringies
{}[]<>/\() -> ()/\<>[]{}
qwertyuiop database -> esabatad poiuytrewq

```

As seen above, the output should go back to the input if run through the program again.

Sandbox link

# Answer
# Python 3, ~~61~~ ~~60~~ 59 bytes

```
lambda s,t="(/<[{}]>\)":[(c+t)[~t.find(c)]for c in s][::-1]

```

Try it online!

 -1 byte thanks to @xnor.

Changed the lookup string, so that the `c in t` test is eliminated.

---

# Python 2, 63 bytes

```
lambda s,b='(/<[{}]>\)':map(dict(zip(b,b[::-1])).get,s,s)[::-1]

```

Try it online!

-1 byte thanks to @xnor.

# Python 3, ~~65~~ 64 bytes

```
lambda s,b=b'(/<[{}]>\)':s.translate(dict(zip(b,b[::-1])))[::-1]

```

Try it online!

Just for fun using idiomatic Python. (More idiomatic would be using `str.maketrans`, but it's *way* too long.)

-1 byte for both because the `\` in `'\)'` doesn't need to be escaped.
> 9 votes

# Answer
# Stax, 2 bytes

```
:R

```

Try it online!

Well, um, yeah, Stax has a two-byte built-in that exactly does the job.
> 6 votes

# Answer
# Bash \+ GNU utilities, 33 bytes

```
tr '(<[{/)>]}\' ')>]}\\(<[{/'|rev

```

Try it online!

A straightforward solution seems best here. Really the only golfing is making sure that the backslash appears last in one of the arguments to tr, because then that backslash doesn't have to be escaped, saving 1 byte.
> 5 votes

# Answer
# JavaScript (ES6),  ~~65~~  59 bytes

*Saved 6 bytes thanks to @Bubbler*

I/O format: array of characters

```
a=>a.map(c=>(S='()/\\<>[]{}')[S.indexOf(c)^1]||c).reverse()

```

Try it online!
> 4 votes

# Answer
# 05AB1E, 4 (or 3?) bytes

```
ºsK

```

Doesn't work for single-character inputs that are not in the mirror character-set (i.e. `"a"`).
Thanks to *@Grimmy* for this version.

Try it online or verify all test cases.

```
º2äθ

```

Also works for single-character inputs that aren't in the mirror character-set.

Try it online or verify all test cases.

**Explanation:**

```
º     # Mirror the (implicit) input-string
      #  i.e. "(s)t/r\i<n>g[i]e{s}" → "(s)t/r\i<n>g[i]e{s}{s}e[i]g<n>i/r\t(s)"
 sK   # And remove the input-string from it
      #  → "{s}e[i]g<n>i/r\t(s)"
      # (after which it is output implicitly)

º     # Mirror the (implicit) input-string
      #  i.e. "(s)t/r\i<n>g[i]e{s}" → "(s)t/r\i<n>g[i]e{s}{s}e[i]g<n>i/r\t(s)"
 2ä   # Split it into two equal-sized parts
      #  → ["(s)t/r\i<n>g[i]e{s}","{s}e[i]g<n>i/r\t(s)"]
   θ  # Pop and only leave the mirrored second part
      #  → "{s}e[i]g<n>i/r\t(s)"
      # (after which it is output implicitly)

```
> 3 votes

# Answer
# Python 3, 69 bytes

```
lambda s,t=r"()/\[]{}<>":[[c,t[t.find(c)^1]][c in t]for c in s][::-1]

```

Try it online!

**Input**: A sequence of character.
**Output**: The reversed string, as list of characters.

**How**:
For each character `c`:

* `c in t` checks if `c` is a bracket.
* `t.find(c)` finds the index of `c` in the bracket string. `t.find(c)^1` finds the index of the mirrored bracket, which is 1 more or 1 less than the index of `c`.
* `[c,t[t.find(c)^1]][c in t]` evaluates to the same character if `c` is not a bracket, otherwise evaluates to the mirrored bracket.
* `[::-1]` reverses the result.
> 2 votes

# Answer
# Retina 0.8.2, 22 bytes

```
T`(/<[{}]>\\)`Ro
O^$`.

```

Try it online! Link includes test cases. Explanation:

```
T`(/<[{}]>\\)`Ro

```

Transliterate the string `(/<[{}]>\)` to its reverse.

```
O^$`.

```

Reverse the whole string.
> 2 votes

# Answer
# Charcoal, 13 bytes

```
Ｐθ‖ＴＦθ¿№βι←ι←

```

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

```
Ｐθ

```

Print the input string without moving the cursor.

```
‖Ｔ

```

Reflect the canvas. This mirrors the characters `()/\<>[]{}bdpq`.

```
Ｆθ

```

Loop over the original string.

```
¿№βι

```

Is the current character a `b`, `d`, `p`, `q` (or any other lowercase letter that wouldn't have been transformed)?

```
←ι

```

If so then replace it with the original lowercase letter and move left.

Otherwise leave the current character, which might be a transformed `()/\<>[]{}`.
> 2 votes

# Answer
# C (gcc), ~~112~~ \\$\cdots\\$ ~~84~~ 83 bytes

Saved a whopping 27 bytes thanks to Bubbler!!!
Saved a byte thanks to dingledooper!!!
Saved a byte thanks to ceilingcat!!!

```
char*t,*b="()/\\<>[]{}";f(char*s){*s&&putchar((t=index(b,*s))?b[t-b^1]:*s,f(s+1));}

```

Try it online!
> 2 votes

# Answer
# batch, ~~442~~ 408 bytes

```
@Echo off&Setlocal EnableDelayedExpansion
for %%A in (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z)do Set %%A=%%A
for %%B in ("(=)",")=(","<=>",">=<","[=]","]=[","{=}","}={","/=\","\=/")do Set "%%~B"
Set "_=%~1"
Call :M
Echo(!$!
Endlocal
Exit /B
:M
For /L %%C in (0,1,256)do (
If "!_:~%%C,1!"=="" Exit /B
Set ".=!_:~%%C,1!"
For %%D in ("!.!")do IF "!%%~D!"=="" (Set "$= !$!")Else (Set "$=!%%~D!!$!")
)

```

Output:
> 2 votes

# Answer
# Python 3, ~~111~~ \\$\cdots\\$ ~~75~~ 69 bytes

```
lambda s,b=r'()/\<>[]{}':[[c,b[b.find(c)^1]][c in b]for c in s][::-1]

```

Try it online!
> 1 votes

# Answer
# Java (JDK), 111 bytes

```
s->{var a="(\\<[{}]>/)";for(int i=s.length,j;i-->0;System.out.print(j<0?s[i]:a.charAt(9-j)))j=a.indexOf(s[i]);}

```

Try it online!

## Credits
> 1 votes

# Answer
# , ~~32~~ ~~28~~ 26 bytes

-4 bytes thanks to Bubbler!

-2 bytes thanks to FrownyFrog

```
|.rplc(;"0|.)@'([{/<>\}])'

```

Try it online!
> 1 votes

# Answer
# Canvas, 1 byte

Exactly. A 1 byte built-in.

Try it here!
> 1 votes

# Answer
# PowerShell, ~~69~~ 58 bytes

`+` to @Bubbler

-11 bytes thanks to @mazzy

```
$t='(/<[{}]>\)'
$args|%{$a="$_$t"[-1-($t|% i*f $_)]+$a}
$a

```

Expects input via splatting.

Try it online!
> 1 votes

# Answer
# Red, 69 bytes

```
func[s][reverse s forall s[s/1: any[select"()([][{}{<></\/"s/1 s/1]]]

```

Try it online!
> 0 votes

# Answer
# Icon, ~~76~~ 68 bytes

```
procedure f(s)
r:=reverse
return map(r(s),t:="([{/<>\\}])",r(t))
end

```

Try it online!
> 0 votes

# Answer
# Perl 5 -pl, 37 bytes

```
$_=reverse;y|(){}[]<>/\\|)(}{][><\\/|

```

Try it online!
> 0 votes

# Answer
# PHP, 52 bytes

```
<?=strrev(strtr($argn,$a='(/<[{}]>\\)',strrev($a)));

```

Try it online!

Glad that this time PHP has an elegant way of doing it ^^
> 0 votes

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


title: Let's decompress a bit

text:
# Question
Title: Let's decompress a bit
Given a compressed string \\$s\\$ made of printable ASCII characters (32 to 126), your task is to print or return the original text by applying this simple decompression algorithm:

1. Start with \\$k=0\\$
2. Look for the first occurrence of the digit \\$k\\$ in \\$s\\$ and the sub-string \\$s'\\$ consisting of the \\$2\\$ characters preceding it. If the pattern is not found, stop here.
3. Remove the first occurrence of the digit \\$k\\$. Replace all other occurrences with \\$s'\\$.
4. Increment \\$k\\$. If it's less than or equal to \\$9\\$, resume at step \\$2\\$.

## Example 1

Input: `bl3a2h1 00001!`

1. The first occurrence of `"0"` is preceded by `"1 "`. We remove the first occurrence of `"0"` and replace all other ones with `"1 "`, leading to `"bl3a2h1 1 1 1 1!"`.
2. We do the same thing for `"1"`, with the sub-string `"2h"`. This gives `"bl3a2h 2h 2h 2h 2h!"`.
3. We do the same thing for `"2"`, with the sub-string `"3a"`. This gives `"bl3ah 3ah 3ah 3ah 3ah!"`.
4. We do the same thing for `"3"`, with the sub-string `"bl"`. This gives `"blah blah blah blah blah!"`, which is the final output because there are no more digits in \\$s\\$.

## Example 2

Input: `Peter Pipe1r pick0ed a 10 of pi0led 1p1rs.`

The first step uses the sub-string `"ck"` and gives:

```
Peter Pipe1r picked a 1ck of pickled 1p1rs.

```

The second and final step uses the sub-string `"pe"` and gives:

```
Peter Piper picked a peck of pickled peppers.

```

## Rules

* The input string is guaranteed to be valid. In particular, there will always be at least 2 characters before the first occurrence of a digit.
* However, the input string may not be compressed at all, in which case it must be returned as-is.
* The uncompressed text is guaranteed not to contain any digit.
* This is .

## Test cases

### Input

Short test cases (one per line):

```
Hello, World!
antidis0establ0hmentarian0m
bl3a2h1 00001!
A AB4 43C22D11E00F0FG
Peter Pipe1r pick0ed a 10 of pi0led 1p1rs.
The 7first 9rul7of Fi6g5h98C3l2ub1 is: You4 do no9talk ab495210. Th7second rul7of 50 is: Y4 do no9talk ab4950.

```

Longer test case (first paragraph of the Adventures of Sherlock Holmes / A Scandal in Bohemia, from Project Gutenberg):

```
To Sher6lock Holmes 3she 9i3a8lway3_the_ woman. I h4av9seldom4eard4im mention246 und68ny oth6 name. In4i3eye3sh9eclipses8nd predomin5ate3t7h19whol9of46 sex. It 0wa3not1at49felt8ny emoti28k57o lov9for Iren9Adl6. All emoti2s,8nd1a029particularly, w69abhorrent7o4i3cold, precise, but8dmirably balanced m5d. H9was, I7ak9it,19mos0p6fec0reas25g8nd obs6v5g mach59that19world4a3seen; but,8s8 lov6,49would4av9placed4imself 58 fals9positi2. H9nev6 spok9of19soft6 passi2s, sav9with8 gib9and8 sne6. They w69admirabl9th5g3for19obs6v6--excellen0for draw5g19veil from men'3motives8nd8cti2s. Bu0for19tra5ed reas267o8dmi0such 5trusi235to4i3own delicat9and f5ely8djusted7emp6amen0was7o 5troduc9a distract5g factor which might1row8 doub0up28ll4i3mental results. Gri058 sensitiv95strument, or8 crack 5 29of4i3own4igh-pow6 lenses, would no0b9mor9disturb5g1an8 str2g emoti2 58 natur9such8s4is. And yet169wa3bu029woman7o4im,8nd1a0woman was19lat9Iren9Adl6, of dubious8nd questi2abl9memory.

```

### Output

```
Hello, World!
antidisestablishmentarianism
blah blah blah blah blah!
A AB ABC ABCD ABCDE ABCDEF ABCDEFG
Peter Piper picked a peck of pickled peppers.
The first rule of Fight Club is: You do not talk about Fight Club. The second rule of Fight Club is: You do not talk about Fight Club.

```

Longer one:

```
To Sherlock Holmes she is always _the_ woman. I have seldom heard him mention her under any other name. In his eyes she eclipses and predominates the whole of her sex. It was not that he felt any emotion akin to love for Irene Adler. All emotions, and that one particularly, were abhorrent to his cold, precise, but admirably balanced mind. He was, I take it, the most perfect reasoning and observing machine that the world has seen; but, as a lover, he would have placed himself in a false position. He never spoke of the softer passions, save with a gibe and a sneer. They were admirable things for the observer--excellent for drawing the veil from men's motives and actions. But for the trained reasoner to admit such intrusions into his own delicate and finely adjusted temperament was to introduce a distracting factor which might throw a doubt upon all his mental results. Grit in a sensitive instrument, or a crack in one of his own high-power lenses, would not be more disturbing than a strong emotion in a nature such as his. And yet there was but one woman to him, and that woman was the late Irene Adler, of dubious and questionable memory.

```

# Answer
> 11 votes
# Python 3, 74 bytes

```
s=input()
for k in'0123456789':a,*b=s.split(k);s=a+a[-2:].join(b)
print(s)

```

Try it online!

# Answer
> 5 votes
# Retina, 36 bytes

```
~(`.+
9*
L$`
(?<=(..)$.`.$*)?$.`¶$$1

```

Try it online! Link includes test cases. Unfortunately Retina does not have a convenient way to access a loop index in its loop construct, so it turns out to be easier to create and evaluate the 179-byte program Retina 0.8.2 would need to solve this. Explanation:

```
~(`

```

When the inner program has finished, evaluate the result as a Retina program on the original input.

```
.+
9*

```

Replace the input with 9 characters that we can loop over.

```
L$`

```

Loop `$.`` from `0` to `9`.

```
(?<=(..)$.`.$*)?$.`¶$$1

```

Generate a replacement stage that for each `$.`` in the input, replaces it with the two characters preceding the first `$.``. If the first `$.`` could not be found then this is the first `$.`` and it is simply deleted. Expanded for `$.` = 0` the code looks like this:

```
(?<=(..)0.*)?0
$1

```

# Answer
> 4 votes
# , ~~49~~ 48 bytes

```
(i.~{2<\.]rplc[;i.~{2]\[,,)&> ::]/@|.@;;/@Num_j_

```

Try it online!

```
({~rplc~^:_~>@]{3({:;}:)\_2|.[)i.&Num_j_<^:3@-.#

```

Try it online!

# Answer
> 3 votes
# 05AB1E, ~~22~~ ~~13~~ 12 bytes

```
9ƒN¡ćDŠ2.£ý«

```

-1 byte thanks to *@CommandMaster*.

Try it online or verify all test cases.

**Explanation:**

```
9ƒ            # Loop `N` in the range [0,9]:
  N¡          #  Split the string at `N`
              #  (which uses the implicit input in the first iteration)
    ć         #  Extract head; pop and push remainder-list and first item separated
     D        #  Duplicate this head
      Š       #  Triple swap a,b,c to c,a,b on the stack (head, remainder-list, head)
       2.£    #  Pop the head, and only leave its last two characters
          ý   #  Join the remainder-list by this 2-char string as delimiter
           «  #  Append it to the duplicated head
              # (after the loop, the resulting string is output implicitly)

```

# Answer
> 3 votes
# Bash \+ GNU utilities, ~~113~~ 112 bytes

```
s=`rev`
for n in {0..9};{ s=`sed "s/\(.*\)$n/\1/;s/$n/$(sed "s/.*$n\(..\).*/\1/"<<<"$s")/g"<<<"$s"`;}
rev<<<"$s"

```

Try the test suite online!

Input on stdin, output on stdout.

Here's how the program works:

> **(1)** The input is reversed right-to-left, to accommodate sed's greedy regex matching.
>
> **(2)** Then the reversed string is decompressed using multiple calls to sed (using the mirror image of OP's decompression rules because the string has been reversed).
>
> **(3)** Finally, the resulting string is reversed again.

**Step (2),** the mirror-image decompression, is implemented as follows.

> **For each `n`** from `0` to `9`:
>
> **(2a)** Due to the way bash does its expansions, the inner sed
>
> `$(sed "s/.*$n\(..\).*/\1/"<<<"$s")`
>
> is evaluated first. Its value is the string consisting of the two characters immediately following the last `n`. That two-character string replaces the entire string
>
> `$(sed "s/.*$n\(..\).*/\1/"<<<"$s")`
>
> in its enclosing larger expression, and only then is the larger expression evaluated.
>
> **(2b)** Now, going back to the first sed, the last `n` in the string is deleted.
>
> **(2c)** All the earlier occurrences of `n` in the string are replaced with the two-character string evaluated in step 2a.

# Answer
> 2 votes
# Python 2, <sup>~~111~~ \\$\cdots\\$ ~~98~~</sup> 97 bytes

Saved ~~2~~ 10 bytes thanks to Uriel!!!
Save a byte thanks to Surculose Sputum!!!

```
def f(s):
 for k in'0123456789':i=s.find(k);s=[s,s[:i]+s[i+1:].replace(k,s[i-2:i])][i>0]
 print s

```

Try it online!

Borrowed test rig from Uriel.

# Answer
> 2 votes
# Perl 5 `-p`, 53 bytes

```
for$c(0..9){s/(..)\K$c(.*)/"'$2'=~s|$c|\Q$1\E|gr"/ee}

```

Try it online!

# Answer
> 2 votes
# Red, ~~94~~ 91 bytes

```
func[s][foreach k"0123456789"[t: copy/part p: any[find s k""]-2 take p replace/all s k t]s]

```

Try it online!

# Answer
> 2 votes
# Charcoal, 35 bytes

```
Ｆχ«≔⌕θＩιη≔⁺…θη⪫⪪✂θ⊕ηＬθ¹Ｉι✂θ⁻η²η¹θ»θ

```

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

```
Ｆχ«

```

Loop over each digit.

```
≔⌕θＩιη

```

Find the first digit in the input.

```
≔⁺…θη⪫⪪✂θ⊕ηＬθ¹Ｉι✂θ⁻η²η¹θ

```

Replace each digit in its suffix with the last two characters of the prefix, and prepend its prefix.

```
»θ

```

After all the digits have been expanded, print the result.

# Answer
> 1 votes
# Python 3.8, ~~93~~ ~~89~~ 87 bytes

```
f=lambda s,k=0:(g:=s.find(m:=str(k)))+1and f(s[:g]+s[g+1:].replace(m,s[g-2:g]),k+1)or s

```

Try it online!

# Answer
> 1 votes
# Java (JDK), 121 bytes

```
s->{int j;for(char i=47;++i<58;s=j>0?s.replaceFirst(""+i,"").replace(""+i,s.substring(j-2,j)):s)j=s.indexOf(i);return s;}

```

Try it online!

Naive Java implementation.

## Credits

# Answer
> 1 votes
# Haskell, ~~154~~ 148 bytes

```
n%c=show n==[c]
n#(a:s@(b:c:_))|n%c=[a,b]|1>0=n#s
_#_=""
f n s|n>9||n#s==[]=s|1>0=f(n+1)$l++r>>= \c->last$[c]:[n#s|n%c]where(l,(_:r))=break(n%)s
f 0

```

Try it online!

### Ungolfed:

```
digitIsChar :: Int -> Char -> Bool
digitIsChar n c = show n == [c]

getSubStr :: Int -> String -> String
getSubStr n (a:b:c:s)
    | digitIsChar n c = [a,b]
    | otherwise = getSubStr n (b:c:s)
getSubStr _ _ = ""

replaceKey :: Int -> String -> Char -> String
replaceKey n key c
    | digitIsChar n c = key
    | otherwise = [c]

decompress :: Int -> String -> String
decompress n s
    | n >= 10 || null key = s
    | otherwise = decompress (n+1) (lhs ++ replaced)
    where
        key = getSubStr n s
        (lhs, (_:rhs)) = break (digitIsChar n) s
        replaced = rhs >>= replaceKey n key

```

### Edits

1. -6 bytes (@FrownyFrog)

# Answer
> 1 votes
# Raku (raku -p), ~~66~~ ~~61~~ ~~58~~ 56 Bytes

```
my $a=-1;$_=S/(..)$a/{$0}/.subst(/$a/,$0,:g)until ++$a>9

```

First attempt. I am sure it can be improved

# Answer
> 1 votes
# Wolfram Language (Mathematica), 124 bytes

```
(r=StringReplace;s=ToString;i=-1;FixedPoint[(i++;r[r[#,s@i->"",1],s@i->StringCases[#,_~~_~~s@i][[1]]~StringTake~2])&,#,10])&

```

Try it online!

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


# Question
Title: Maintain diagonal symmetry when placing N items on a square grid
Write a program that takes in two non-negative integers **S** and **N** in that order. S represents the side length of a square grid of `.` characters. N represents the number of those `.`'s that need to be changed to `x`'s. You may assume N is no greater than S squared.

Your program needs to output this S×S square of `.`'s and N `x`'s but the requirement is that **the square must always have a diagonal line of symmetry from its top left to its bottom right**. Any grid arrangement is valid output as long as it has this symmetry.

For example, if S is 3 and N is 4 here are several grids that have this diagonal symmetry and would be valid output:

```
x.x
...
x.x

x..
.xx
.x.

...
.xx
.xx

```

The following grids however would not be valid:

```
.x.
xxx
...
(lacks diagonal symmetry)

..x
xx.
.x.
(has diagonal symmetry but not from the top left to the bottom right)

x.x
.x.
x.x
(incorrect number of x's)

```

**This is code golf so the shortest program in bytes wins!**

### Details:

* A trailing newline after the grid is fine.
* You may use any two distinct printable-ASCII characters in place of `.` and `x` if you prefer.
* If you prefer you may even output a instead of a string.
* When N is 0 the output will be a pure S×S square of `.`'s with no `x`'s.
* When S is 0 the output will be an empty string (or single trailing newline).
* The output does not need to be deterministic, as long as it is always guaranteed to be valid.

### More Examples:

Not all valid arrangements are listed for each example input. Your output might look different yet still be valid.

```
S = 0, N = 0
[empty string]

S = 1, N = 0
.

S = 1, N = 1
x

S = 2, N = 0
..
..

S = 2, N = 1
x.
..

..
.x

S = 2, N = 2
x.
.x

.x
x.

S = 2, N = 3
xx
x.

.x
xx

S = 2, N = 4
xx
xx

S = 3, N = 2
x..
.x.
...

..x
...
x..

S = 4, N = 1
....
.x..
....
....

S = 4, N = 5
x..x
.x..
..x.
x...

xxx.
x...
x...
....

S = 5, N = 23
xxxxx
xxxxx
xxxxx
xxx.x
xxxx.

xxxxx
xxxxx
xxxxx
xxxx.
xxx.x

S = 7, N = 13
...x...
...x...
...x...
xxxxxxx
...x...
...x...
...x...

xxxxxxx
x......
x......
x......
x......
x......
x......

```

# Answer
# Python 2, ~~116~~ ~~113~~ ~~112~~ 101 bytes

```
lambda s,n:[[[n>i<s-(s+n&1),[i*~-i+2*j,j*~-j+2*i][i<j]<n-s][j!=i]for j in range(s)]for i in range(s)]

```

Try it online!

**Input**: 2 integers `s` and `n`
**Output**: A 2D list of `True` and `False`, representing `x` and `.` respectively.

### Explanation

The strategy is to put as many `x`s on the diagonal as possible.

* If \\$s\\$ and \\$n\\$ has the same parity, then we can fill \\$min(s,n)\\$ diagonal squares.
* If \\$s\\$ and \\$n\\$ has different parity, then we can fill \\$min(s-1,n)\\$ diagonal squares.

The remaining `x`s can be split symmetrically between the 2 triangular half of the grid. For the bottom triangle, we fill from top to bottom, where each row is filled left to right. The upper triangle mirrors the bottom triangle (fill left to right, each column from top to bottom)

Thus, we can determine if a square is filled just based on its indices \\$(i,j)\\$:

* If \\$i=j\\$ (the square is on the diagonal), then that square is filled if \\$i\<n\\$ and \\$i\<s-t\\$, where \\$t\\$ is 0 or 1 depending on whether \\$s\\$ and \\$n\\$ have the same or different parity.
The following snippet evaluates to `True` or `False` if the diagonal square should be filled or not.

```
[n>i<s-(s+n&1), ...case when square is not diagonal... ][j!=i]

```
* If \\$i\>j\\$ (the square is in lower triangle), then the number of squares in the lower triangle before this square (in fill order) is \\$m = \frac{i(i-1)}{2} + j\\$. Thus if this square is filled, then the number of squares filled before it is \\$2m = i(i-1)+2j\\$. We need to make sure that \\$2m\<n-s\\$, otherwise the diagonal cannot be filled to the maximum.
Similarly, if \\$i\>j\\$, then we fill if \\$j(j-1)+2i\<n-s\\$.
The following snippet evaluates to `True` or `False` if the non-diagonal square is filled or not:

```
[i*~-i+2*j,j*~-j+2*i][i<j]<n-s

```

Combined together, this big expression evaluates to whether a square \\$(i,j)\\$ should be filled:

```
[n>i<s-(s+n&1),[i*~-i+2*j,j*~-j+2*i][i<j]<n-s][j!=i]

```

*Thanks @ovs for saving 4 bytes in a previous solution!*
> 7 votes

# Answer
# JavaScript (ES6),  ~~116 114~~  110 bytes

Takes input as `(s)(n)`. Returns a matrix of Boolean values.

```
s=>n=>[...Array(s)].map((_,y,a)=>a.map((_,x)=>(p=Math.min(n&~1,s*s-s),x-y?(x<y?y*y-y+2*x:x*x-x+2*y)<p:x<n-p)))

```

Try it online!

### How?

The output matrix is divided into 2 parts:

* the cells located on the main diagonal (type A)
* all other cells (type B)

Whenever a type-B cell is set, its symmetrical counterpart must be set as well. We want to set as many type-B cells as possible and this number is given by:

$$p\_{n,s}=\min\left(2\left\lfloor\frac{n}{2}\right\rfloor,s(s-1)\right)$$

The number of type-A cells is therefore given by:

$$q\_{n,s}=n-p\_{n,s}$$

We define \\$T(k)\\$ as the \\$k\\$-th triangular number:

$$T(k)=\frac{k(k+1)}{2}$$

To figure out whether the type-B cell at \\$(x,y)\\$ must be set or not, we assign it the following ID and compare it with \\$\dfrac{p\_{n,s}}{2}\\$:

$$\begin{cases} T(y-1)+x,&\text{if $x\<y$}\\ T(x-1)+y,&\text{if $x\>y$}\\ \end{cases}$$

Example for \\$s=5\\$:

$$\begin{pmatrix} -&0&1&3&6\\ 0&-&2&4&7\\ 1&2&-&5&8\\ 3&4&5&-&9\\ 6&7&8&9&- \end{pmatrix}$$

To figure out whether the type-A cell at \\$(x,x)\\$ must be set or not, we simply use \\$x\\$ as its ID and compare it with \\$q\_{n,s}\\$.

Example for \\$s=5\\$:

$$\begin{pmatrix} 0&-&-&-&-\\ -&1&-&-&-\\ -&-&2&-&-\\ -&-&-&3&-\\ -&-&-&-&4 \end{pmatrix}$$
> 4 votes

# Answer
# MATL, ~~21~~ 20 bytes

```
U:<~Zc`tnZ@)[]ett!-z

```

Try it online!

Characters are `#` and . The output is random, that is, it may be different every time the program is run. Running time is also random, but the program is guaranteed to finish in finite time.

## How it works

**General idea**

The code first generates a numeric vector with N ones and S^2-N zeros (`U:<~`), and transforms it into a string replacing 1 and 0 by the two mentioned characters (`Zc`). Then, a random permutation is applied (`tnZ@)`) , the result is reshaped into a square matrix of characters (`[]e`), and this is repeated (```) until the matrix equals its transpose (`t!-z`), while leaving a copy (`t`) for the next iteration or as final result.

**Detailed steps**

```
U        % Input (implicit): S. Push S^2
:        % Range [1 2 ... S^2]
<~       % Input (implicit): N. Greater-or-equal, element-wise. Gives
         % [1 1 ... 1 0 0 ... 0] with N ones and S^2-N zeros
Zc       % String where 1 becomes '#'  and 0 becomes space
`        % Do...while
  tn     %   Duplicate. Number of elements. Gives S^2
  Z@     %   Random permutation of the integers 1, 2, ..., S^2
  )      %   Apply as an index. This shuffles the previous string
         %   or char matrix, and gives a string as result
  []e    %   Reshape as a square matrix of chars
  tt!    %   Duplicate twice, and transpose the second copy
  -      %   Subtract element-wise
  z      %   Number of nonzeros. This is the loop condition. The loop
         %   is exited when the result is 0, meaning that the matrix
         %   and its transpose are equal
         % End (implicit)
         % Display (implicit). The stack contains a copy of the latest
         % matrix of chars, which is the first that was found to
         % satisfy the symmetry condition

```
> 4 votes

# Answer
# Wolfram Language (Mathematica), 113 bytes

Searches random matrices \[S,N\] until matrix g is equal to Transpose(g)
Outputs a binary matrix

```
If[#<1,"",g=(P=Partition)[k=Join@@{1~Table~#2,Table[0,#^2-#2]},#];While[g!=Transpose@g,g=P[RandomSample@k,#]];g]&

```

Try it online!

# Wolfram Language (Mathematica), 75 bytes

Here is also a deterministic version that searches all possible matrices
(it works only up to 4x4 due to memory limitations)

```
If[#<1,"",x=#2;Select[{0,1}~Tuples~{#,#},#==Transpose@#&&Tr[Tr/@#]==x&,1]]&

```

Try it online!

*-2 bytes by @my pronoun is monicareinstate*
> 3 votes

# Answer
# Bash \+ Unix utilities, 152 bytes

```
a=`dc<<<4dk$2*1+v1-2/0k1/p`
for((q=$2-a*a-a,b=++a<$1?q/2:0;i<$1;++j>=$1?j=0,i++:0)){ printf $[i-j?i<a&j<a?1:i==a&j<b|j==a&i<b?1:0:i<q-2*b?1:0]\ ;}|rs $1

```

Try the test suite online!

\\$S\\$ and \\$N\\$ are read from stdin, and the output is printed to stdout. The characters used are `0` and `1` (for (for `.` and `x`, respectively).

This program prints a space between successive characters, which I think looks better (the grids are more squarish and easier to read), and it saves me a byte. If that's not acceptable, use `fold` instead of `rs` as follows (for 153 bytes):

```
a=`dc<<<4dk$2*1+v1-2/0k1/p`
for((q=$2-a*a-a,b=++a<$1?q/2:0;i<$1;++j>=$1?j=0,i++:0)){ printf $[i-j?i<a&j<a?1:i==a&j<b|j==a&i<b?1:0:i<q-2*b?1:0];}|fold -$1

```

**How it works:**

First we use `dc` to compute $$a=\left\lfloor\frac{\sqrt{4N+1}-1}{2}\right\rfloor.$$

You can check that \\$a\\$ is the greatest integer such that \\$a(a+1) \leq N.\\$ The reason this is useful is that $$a(a+1)=2(1+2+\dots+a).$$

The for loop that comes next runs through each position \\$(i, j)\\$ where each of the variables goes from \\$0\\$ to \\$S-1.\\$ It prints a `0` or a `1` for each \\$(i,j)\\$.

For convenience, \\$a\\$ is incremented during the for loop initialization, so it's actually \\$1\\$ higher than the above value during the body of the loop.

The following entries are filled in with `1`s (the others are all `0`s):

(1) Fill in each \\$(i,j)\\$ where \\$0 \le i \lt a\\$ and \\$0 \le j \lt a.\\$

(2) If \\$a\<S\\$ (so that there's at least one row and one column left untouched still), fill in the entries at positions \\$(a,i)\\$ and \\$(i,a)\\$ (starting from \\$i=0\\$ and keeping \\$i\\$ below \\$a-1\\$), up to the number of additional entries that are still needed after step 1. These are always entered in pairs.

(3) If we still haven't marked enough entries (which can happen because we ran out of room off the main diagonal, or simply because we needed to mark an odd number of entries, but everything so far has been in pairs), then fill in entries \\$(i,i)\\$ on the main diagonal, starting at \\$i=0,\\$ until we've filled in the right number of `1`s.

Finally, the `rs` (or `fold`) at the end formats it all as a square array.
> 2 votes

# Answer
# Perl 5, 139 bytes

```
sub f{($s,$n)=@_;$_='-'x$s x$s;$i=-1;while($n){$j=++$i%$s*$s+int$i/$s;$n<2&&$i-$j&&next;for$o($i,$j){$n-=s,^(.{$o})-,$1x,}}s/.{$s}/$&\n/gr}

```

Try it online!

```
sub fungolfed {
  ($s,$n) = @_;                     # input params s and n
  $_ = '-' x $s x $s;               # $_ is the string of - and x
  $i=-1;                            # start at position i=0, due to ++ below
  while($n){                        # while more x's to place (n>0)
    $j = ++$i % $s * $s + int$i/$s; # j is the symmetrical position of i
    $n<2 && $i-$j && next;          # place x only in diagonal if one x left (n=1)
    for $o ($i,$j){                 # place x at positions i and j
      $n -= s/^(.{$o})-/$1x/        # ...and decrease n if - was replaced by x
                                    # ...that is if the position was not aleady x
    }
  }
  s/.{$s}/$&\n/gr                   # put \n after each s'th char and return that
}

```

Test:

```
for my $s (0..7){
  for my $n (0..$s*$s){
    print "\n__________________ s=$s n=$n\n";
    print f($s,$n) =~ s/./$& /gr;                 }  }

```

Part of the output:

```
__________________ s=3 n=0
- - -
- - -
- - -
__________________ s=3 n=1
x - -
- - -
- - -
__________________ s=3 n=2
x - -
- x -
- - -
__________________ s=3 n=3
x x -
x - -
- - -
__________________ s=3 n=4
x x -
x x -
- - -
__________________ s=3 n=5
x x x
x - -
x - -
__________________ s=3 n=6
x x x
x x -
x - -
__________________ s=3 n=7
x x x
x x -
x - x
__________________ s=3 n=8
x x x
x x x
x x -
__________________ s=3 n=9
x x x
x x x
x x x

```
> 1 votes

# Answer
# PowerShell, ~~153~~ ~~140~~ 136 bytes

```
param($l,$n)if($l--){0..$l|%{$y=$_
-join(0..$l|%{$n-=$a=($_-eq$y-and$n)+2*($_-gt$y-and$n-gt1)
'.x'["$y;$_"-in($c+=,"$_;$y"*$a)-or$a]})}}

```

Try it online!

Unrolled:

```
param($length,$n)
if($length--){
    0..$length|%{
        $y=$_
        -join(0..$length|%{
            $draw = 1*($_ -eq $y -and $n) +         # draw 1 element on the diagonal
                    2*($_ -gt $y -and $n -gt 1)     # draw 2 elements in the corners
                                                    # or draw 0 elements (draw field char '.')
            $n-=$draw                               # reduce the number of drawing elements
            $coordCache += ,"$_;$y" * $draw         # add one element or two identical elements
            '.x'[$draw -or "$y;$_" -in $coordCache] # draw element directly or draw from cache
        })
    }
}

```
> 1 votes

# Answer
# Charcoal, 39 bytes

```
ＮθＮηＧ←↑⊖θ.ＵＭ✂ＫＡ⁰⊘η¹x↑‖Ｍ↗Ｐ↘⭆θ§.x›η⁺ι№ＫＡx

```

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

```
ＮθＮη

```

Input `S` and `N`.

```
Ｇ←↑⊖θ.

```

Fill a triangle of size `S-1` with `.`s.

```
ＵＭ✂ＫＡ⁰⊘η¹x

```

Change up to `N/2` of those `.`s to `x`s.

```
↑‖Ｍ↗

```

Reflect to create the diagonal symmetry, but leaving the diagonal empty.

```
Ｐ↘⭆θ§.x›η⁺ι№ＫＡx

```

Count the number of `x`s and complete the diagonal using `x`s and `.`s as necessary to end up with `N` `x`s.
> 1 votes

# Answer
# Ruby, 97 bytes

```
->s,n{t=(?.*s+$/)*s
i=1
(t[i*-~s/s]=t[i/s-i%s*~s]=?X;i+=1)until 2>m=n-t.count(?X)
m>0&&t[0]=?X
t}

```

Try it online!

Llamda function. Returns a newline separated string with `X` and `.` can be shorter if a single line string is acceptable.

Very simple:

* Make a newline separated string of s lines of s `.`
* Set `i=1` and scan through all indexes of `i` interpreting this as both \[row-then-column\] and \[column-then-row\] and change the relevant `.` to `X` . The total number of `X` added per iteration will be 1 if it is the cell is on the diagonal, and either 2 or 0 if it is not, depending on whether the cells already contain `X`.
* End the loop when less than 2 more `X` need to be added.
* If there is still one `X` to be added, put it at top left (index 0)
* Return the string
> 1 votes

---
Tags: code-golf, string, integer, grid, binary-matrix
---