title: Code-generator with unique characters

text:
# Question
Title: Code-generator with unique characters
# Challenge

Your task is to write a piece of code that outputs another piece of code. That code must in turn output yet another code until the final code outputs the integer **1**. The chain ends the first time **1** is outputted.

**None of your programs may share any characters** (there's one exception in the Rules-section).

The winning submission will be the submission with the longest chain. The tie-breaker will be shortest total code-length.

---

### Rules:

* You may use both functions, programs and snippets. You may assume a REPL environment.
* All functions must be written in the same language
* Symbol independent languages are disallowed. This includes partially symbol independent languages such as Headsecks.
* Default output formatting may optionally be disregarded in a function's output. This includes trailing newlines, `ans =` etc.
* You may reuse the space character (ASCII code point 32), but note the following:
    + You may use as many space characters as you like in one of the functions, but restrict it to maximum 5 in all other functions
    + You may not reuse any characters if code point 32 is not space in your language.
* None of the programs may take input
* The chain must be at least two programs long.

---

### Example:

Your initial code is `abc+cab+bac`. This outputs: `foofoo*123`, which in turn outputs `disp(~0)`, which outputs `1`. This is a chain of 3 programs, with a combined length of 29 (tie breaker).

# Answer
> 18 votes
# 05AB1E, 5-chain: 236 + 29 + 13 + 3 + 1 = 282 bytes

```
10101100011010001101100010110110001111000111001110101001000000000010111100100110011011010110011000100110101001001101100001110001111010100100000100010010001010011101011001110001000001011010101111001110011110001010111100001110110C₁<Au¦н.V

```

Try it online!

which prints the program

```
633693S<J6bαð3<žQTÌ>è9663тαhJ

```

Try it online!

which prints the program

```
522472 2-255B

```

Try it online!

which prints the program

```
88ç

```

Try it online!

which prints the program

```
X

```

Try it online!

which prints `1`

# Answer
> 12 votes
# Java 8, chain of 2 functions, ~~90+10~~ ~~37+4~~ 28+4 = 32 bytes

```
o\u002D\u003E"\44\55\76"+2/2

```

Which is equivalent to:

```
o->"$->"+2/2

```

-57 bytes thanks to *@OlivierGrégoire*.

Try it online.

Which returns the String:

```
$->1

```

Try it online.

Which returns the integer:

```
1

```

# Answer
> 10 votes
# , 3-chain 198 + 44 + 3 bytes

```
`+`=`\143\141\164`;+"\143\141\164\050\151\156\164\124\157\125\164\146\070\050\143\050\070\070\055\071\055\071\054\071\071\071\055\070\070\071\055\070\055\070\054\070\070\055\071\055\071\051\051\051"

```

Try it online!

Returns :

```
cat(intToUtf8(c(88-9-9,999-889-8-8,88-9-9)))

```

Try it online!

Returns :

```
F^F

```

Try it online!

Returns `1`

**Explanation :**

The first program is almost totally written in octal representation, where each character is written as `\xxx` where `xxx` is the ASCII code in octal mode. In human readable form would be :

```
`+`=`cat`;+"cat(intToUtf8(c(88-9-9,999-889-8-8,88-9-9)))"

```

Here, to avoid the use of round brackets we redefine the prefix operator `+` equal to `cat` function, then we use that to print the next string. Even after assigning `cat` to `+`, the latter still keeps its prefix operator "status" and will just take whatever follows it as its first parameter.

The second program, simply prints the characters `F^F` obtaining them from decimal ASCII : `70,94,70`

Since in the first program we used the octal representation, only numbers `8` and `9` are free to be used; hence, we obtain `70` and `94` with some differences between numbers with only `8's` and `9's`.

Finally, the last program, `F^F`, exploits the `^` function (power of) which coerces `FALSE` to `0` and computes `0^0` returning `1`

Credits to :

* @ngm for the first 2-chain idea
* @Giuseppe for the hint to use octals in functions
* @BLT and @JayCe for the idea to override `+` in order to avoid brackets

---

Previous version :

# , 2-chain ~~27+3~~ 24 + 2 bytes

```
cat(intToUtf8(c(49,76)))

```

Try it online!

Returns:

```
1L

```

Try it online!

Returns `1`.

# Answer
> 8 votes
# Python 2, 2-Chain, 7+44 = 51 bytes

```
lambda:("7072696e74203"+`3-2`).decode("hex")

```

and

```
print 1

```

Try it online!

The base 16 code translates to `print 1`, which is returned by the anonymous function.

# Answer
> 7 votes
# Octave, 3 programs, Length 42 bytes

```
char("``;8%79b/7%,,b"-5)

```

Outputs: `[[63 24]*2 '']`. Try it online!

```
[[63 24]*2 '']

```

Outputs: `~0`. Try it online!

```
~0

```

Outputs: `1`. Try it online!

# Answer
> 7 votes
# Perl 5, 3-chain, ~~151~~ 139 chars (114 + 20 + 5)

```
&{"CORE::SYSWRITe"|"CORE::39372!4"}(STDOUT,"\x70\x72\x69\x6E\x74\47\x50\x42\x5A\3\22\47\x5E\47\43\43\43\43\43\47")

```

The ugliness inside the `&{ }` evaluates to `CORE::syswrite`, and so the hex-escaped string is printed to standard output as:

```
print'PBZ^C^R'^'#####'

```

Please note that the *^C* and *^R* in the above represent literal control characters. (And not to be confused with the literal `^` caret that occurs between the two strings.)

This program in turn outputs:

```
say 1

```

# Answer
> 6 votes
# Cjam, 4-chain, 28+20+3+1=52 bytes

### Snippet 1:

```
"tugshrm\x18$\x18vj\x1b\x07um~l$\x1b"{71^}%

```

### Snippet 2:

```
32 4/5*_c_1-\@2*9+c\

```

### Snippet 3:

```
'Y(

```

### Snippet 4:

```
X

```

Which then prints 1.

Try it online!

***Note:***

1. Since Cjam *does not* have interpretation for escape characters, the ones in snippet 1 are only there for better web view. You need to use the corresponding actual characters to run the snippet.
2. If I cannot shave off more characters, then good job to @Emigna for the `05AB1E` answer!

# Answer
> 5 votes
# Excel, Chain 2, 27+3 bytes

```
=CHAR(45)&CHAR(45)&CHAR(49)

```

Not sure if this is OK...

# Answer
> 5 votes
# x86 bytecode, Chain 2, 10+4 bytes

(Assembled with FASM, format PE)

`ÇA.Ï?¿<÷Y.` produces `1À@Ã` in the address next to it and executes it, which returns `1` in eax (as per fastcall). In both cases the `.` actually represents `A` or LF.

In hex: `C7 41 0A CF 3F BF 3C F7 59 0A` and `31 C0 40 C3`.

Disassembled:

```
mov dword ptr ds:[ecx+A],3CBF3FCF
neg dword ptr ds:[ecx+A]

```

produces

```
xor eax,eax
inc eax
ret

```

This (ab?)uses the fact that the entrypoint of the program is stored in ecx, and then writes the inverse of the to be executed code to the address 10 bytes over and negates it.

May or may not break if assembled with anything but fasm, to anything but a PE or with a different entrypoint.

# Answer
> 5 votes
# JavaScript REPL, lots of bytes, 4 iterate

```
(+!![]+[!![]+!![]+!![]+!![]]+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(+!![])+![]+![]+(!![]+!![]+!![])+![]+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+![]+(+!![])+(!![]+!![])+![]+(+!![])+(!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+![]+(!![]+!![]+!![])+![]+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+![]+(+!![])+(!![]+!![])+![]+(+!![])+(!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(+!![])+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(+!![])+![]+![]+(+!![])+(!![]+!![])+![]+(+!![])+(+[])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(+!![])+(+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(+!![])+![]+![]+(+!![])+(!![]+!![])+![]+(+!![])+(+[])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![])+![]+![]+(+!![])+![]+(!![]+!![])+![]+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(!![]+!![]+!![]+!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(!![]+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(+!![])+![]+![]+(+!![])+![]+(+!![])+(+[])+![]+(+!![])+(+!![])+![]+(+!![])+(!![]+!![]+!![]+!![]))[(![]+[])[!![]+!![]+!![]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]]+[])[!![]+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[+!![]])()([][[]]))[+!![]+[+[]]]+(![]+[])[!![]+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[+[]]](![])[(+(!![]+!![]+[+[]]+(+!![])+(!![]+!![])+(!![]+!![]+!![]+!![]+!![])))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([]+[])[([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]][([][[]]+[])[+!![]]+(![]+[])[+!![]]+([]+(+[])[([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]])[+!![]+[+!![]]]+(!![]+[])[!![]+!![]+!![]]]](!![]+!![]+!![]+[+[]])](([]+[])[([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]]+[])[!![]+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[+!![]])()(+[]+[![]])[!![]+!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+!![]]+(+[![]]+[][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]())[+!![]+[+!![]]]+(!![]+[])[+[]]][([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+([![]]+[][[]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+([][[]]+[])[!![]+!![]]]([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]]+[])[!![]+!![]+[+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]+[+[]]]+(![]+[])[+!![]]+(![]+[])[!![]+!![]])()(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+!![]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]]+[])[!![]+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[+!![]])()(![]+[![]])[+!![]+[+[]]]+(!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![]+!![])+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![]+!![])+(!![]+!![])+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(![]+[])[+[]]+(!![]+!![]+!![]+!![]+!![]+!![])+(+[])+(!![]+!![]+!![]+!![]+!![])+([][[]]+[])[!![]+!![]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[!![]+!![]]]+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])))[([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([![]]+[][[]])[+!![]+[+[]]]+([][[]]+[])[+!![]]]([])
"\x60\44\x7b\55\x7e\x7b\x7d\x7d\44\x7b\55\x7e\x7b\x7d\x7d\x60\56\x73\x70\x6c\x69\x74\x60\x60\56\x74\x6f\x53\x74\x72\x69\x6e\x67\x60\x60"
`${-~{}}${-~{}}`.split``.toString``
1,1
1

```

Too lazy to optimize the JSFUCK code

# JavaScript REPL, 164 bytes, 3 iterate

may be able to expand

```
[g=222222222222222222,e=2e40,f=2e23,f,2e40,n=2222e49,r=2e24,2e30,e,n,r,8e28,2e40,n,r,9e29,g].map(S=>String.fromCharCode(Math.log(S))).join([])
'\55\x7E\x7B\x7D'
-~{}
1

```

Try it online!

# Answer
> 5 votes
# MATL, 5 programs, 404+159+35+4+1 = 603 bytes

Getting to 4 programs was hard. 5 programs was *very hard!*

'/'37 13+3+3+'3`/'37 13+3+3+77 13+37 13+3+3+'3`/'37 13+3+3+'3tttttttt`/'37 13+3+3+'3#'37 13+3+3+'3ttttt`'37 13+3+3+'3ttttt'37 13+3+3+77 13+'/'37 13+3+3+'3`<<tttttttttt'37 13+3+3+'3#'37 13+3+3+77 13+37 13+3+3+'3///<3////t````ttttt```<</////t`````t<3tttttttttt<3tt/'37 13+3+3+'3ttttttttt'37 13+3+3+'3`{'37 13+3+3+77 13+'y$'37 13+3+3+'3/////t`````ttI#I'77 13+3+'dk'hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh3_+''h

Try it online!

```
,50],5W50],50qqqqqqqq],50 50qqqqq]50qqqqq5W,50]99qqqqqqqqqq50 5W50,,,90,,,,q]]]]qqqqq]]]99,,,,,q]]]]]q90qqqqqqqqqq90qq,50qqqqqqqqq50]x5Wv!50,,,,,q]]]]]qqF FZah

```

Try it online!

This might be my favorite program I've written on PPCG:

```
22 2 2**2-2-- 22Y2 2EEEEEEEEBPX)2)

```

Try it online!

```
84
c

```

Try it online!

```
T

```

Try it online!

### Explanation:

Having used hours on this program, I won't write the entire explanation now! I'll write it later!

Short summary:

```
T            -> Literal true = 1

```

---

```
84c          -> Convert 84 to its ASCII-character T

```

---

```
22 2 2**...  -> Calculate 84 using only 2, * and -
 22Y2        -> 22Y2 is a cell array with the name of all the months
 2EE..B      -> Is 512 in binary [1 0 0 ...]
 P           -> Flips is, [0 0 ... 1]
 X)          -> Uses the binary vector as index and gets the 10th element
             -> 'October'
2)           -> The second character, 'c'
             -> Resulting in the stack: 84, 'c' that's implicitly printed

```

---

```
,50]...      -> A string with ASCII character codes of '22 2...
             -> There's a lot of ,xyz], which means "do twice" and q which is decrement

```

In order to convert this to a string instead of character codes, we need to concatenate it with a string using `h`. To get a string, without using quotes, or the XY modifiers, we do base conversion and convert an integer to whitespace.

---

```
'/'37 13 ...  -> Concatenation of strings and character codes using only available numbers
3_+           -> Subtract 3 from all character codes to get the correct ones
''h           -> And concatenate with the empty string.

```

# Answer
> 5 votes
# CJam, 7-chain, 92365+1819+79+14+9+3+1 bytes

This 92365-byte program prints

```
YaY+`$1<mR1+1+1+1+1+1+11+1+1+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+1+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR1+1+1+1+1+11+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+1+YaY+`$1<mR1+1+1+1+1+11+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+1+1+1+11+YaY+`$1<mR1+11+11+YaY+`$1<mRYaY+`$1<mR1+1+1+1+1+1+11+1+1+1+1+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR1+11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+11+11+11+11+11+1+1+1+1+YaY+`$1<mR11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1+1+1+1+1+YaY+`$1<mR1+1+11+11+11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+1+1+1+11+11+1+1+YaY+`$1<mR11+11+YaY+`$1<mR1+1+1+1+1+1+11+1+1+1+YaY+`$1<mR1+11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+11+11+YaY+`$1<mR1+1+11+YaY+`$1<mR1+11+YaY+`$1<mR1+1+1+1+1+11+11+1+1+YaY+`$1<mR11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+YaY+`$1<mR1+1+1+1+1+

```

which prints

```
34 4673 4656 4673 4656 5464 4656 4673 4673 4740 34 50 34707 5477]{N7=64777-,=}%

```

which prints

```
";*;*Q*;;~"2f^

```

which prints

```
9(9(S(99|

```

which prints

```
88c

```

which prints

```
X

```

which prints `1`.

# Answer
> 4 votes
# CJam, 10 programs, 5,751,122,990 bytes

I was too lazy to golf it... But apparently I don't need to golf it to be competitive. But without golfing it is a bit difficult to post the solution in an answer.

It should work in the JavaScript interpreter in theory, but the program is too long to be tested in a browser. It should output the same in the Java interpreter except for the last program. But it may also run out of memory in the Java interpreter for the first few programs.

### Statistics

```
5683631402 bytes, used )\_l
  65027874 bytes, used %&<>WXehrstu{|} and newline
   2247044 bytes, used +DEFHIS~
    199997 bytes, used ,38=[]`
     15352 bytes, used -25:N and space
      1181 bytes, used 67c
        84 bytes, used #'(@CKMTgkp
        21 bytes, used !"$?BJLQR^fijo
        16 bytes, used */4AGYZabdy
        19 bytes, used .09
         1 byte,  used 1

```

### First bytes

```
l)__)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))...
\n{s}sX>X<eu{h}sX>X<eu{\n}sX>X<{{XXXXXXX}seeseeseeW>{X<{|}%}%}%{|}sX>X<{{X}se...
SH+~+E+E+E+SH+~+H+E~+SH+~+H+E~+SI+~+H+D+D+SI+~+I+E+E+SH+~+H+E~+SF+~+E+SD+~+D+...
[33]`3=,3333=[33]`3=,388333=[8]`88=,8333=[8]`88=,8333=[8]`88=,8338=[8]`88=,33...
N:--25--22- 2-N:--25--22- 2-N:--22--22-N:--25--22- 2-N:--25--22- 2-N:--22--22...
776776777767c677676676677667c66677666676776c776776777767c7667776c666776666767...
'#('@('T(('k(('T((('k(('K('p(''((('@('T(('k(('T((('k(('k('M('#(('#('C('g('g((...
"?RiQiJo$?RiQijL!"Bf^
4YbZbAd/4YbZbaG*
0.99999999999999999
1

```

`\n` is newline in the second program.

### Generator

```
"'#('@('T(('k(('T((('k(('K('p(''((('@('T(('k(('T((('k(('k('M('#(('#('C('g('g((((((((("

{_[i1:X;{_1&6+ \1$X*X5*:X;- 2/}16*;]__,,:)\f<Wf%10fb:c@#)<W%'c}%s

"67c"
"N:--22--22-
N:--25--22- 2-
N:--55--25--5--2--2-"N/ers

"N:-25 "
"[33]`3=,3333=
[33]`3=,388333=
[8]`88=,8333=
[8]`88=,8338=
[8]`88=,333=
[8]`88=,88="N/ers

"[]`38=,"
"SH+~+E+E+E+
SI+~+H+D+D+
SI+~+I+E+E+
SH+~+H+E~+
SI+~+I+D~+H+E~+
SF+~+E+
SD+~+D+D~+"N/ers

"SDEFHI+~"
"{s}sX>X<eu
{t}sX>X<{{XXXXXXXX}s{X}s{XXXXXX}erseeW>{X<{&}%}%}%
{ee}sX>X<eu
{&}sX>X<{{XXXXXXs}s{X}s{XXXXXX}erseeW>{X<{|}%eu}%}%
{h}sX>X<eu
{h}sX>X<eu{X|}%
{N}sX>X<{{XXXXXXX}seeseeseeW>{X<{|}%}%}%
{|}sX>X<{{X}seeW>{X<{|}%}%}%"N/'Nf/Nf*erN\+s

1>"l)_"o)\{'_oi10-')*o'\o}/i10-')*o

```

# Answer
> 3 votes
# APL (Dyalog), 2 chain, 15+2 = 17 bytes

```
⎕AV[2+⎕AV⍳'⍳.']

```

Try it online!

Outputs the program

```
*0

```

That outputs

```
1

```

# Answer
> 3 votes
# JavaScript (ES6), 2 functions, 31+4 = 35 bytes

```
function(){return atob`Xz0+MQ`}

```

returns `_=>1`, which returns `1`

```
f0 =
function(){return atob`Xz0+MQ`}

res0 = f0()
console.log('Output of 1st function:', res0)

f1 = eval(res0)
res1 = f1()
console.log('Output of 2nd function:', res1)
```

# Answer
> 3 votes
# Java 8, 3 programs, 431 bytes

## Program 1, 332 bytes

A lambda from one (empty) parameter of any type to `String`.

```
x\u002D\u003E"\151\156\164\40\157\75\70\46\70\52\70\54\156\75\53\53\157\53\70\73\156\145\167\40\123\164\162\151\156\147\50\51\53\50\143\150\141\162\51\50\47\171\47\53\157\51\53\50\143\150\141\162\51\50\47\54\47\53\157\51\53\50\143\150\141\162\51\50\47\75\47\53\157\51\53\156\53\50\143\150\141\162\51\50\47\56\47\53\157\51\53\156\73"

```

This is just a lambda with the arrow characters Unicode-escaped returning the text of the second program encoded with octal escape sequences.

Try It Online

## Program 2, 93 bytes

Snippet producing a `String`.

```
int o=8&8*8,n=++o+8;new String()+(char)('y'+o)+(char)(','+o)+(char)('='+o)+n+(char)('.'+o)+n;

```

Try It Online (with return added)

## Program 3, 6 bytes

A lambda from one (empty) parameter of any type to `int`.

```
z->9/9

```

Try It Online

# Answer
> 3 votes
# Jelly,  ~~38 37 36~~  35 bytes, Chain of 4

```
ØJiⱮ⁾ɱṾ⁽÷ṃ;ṾØJ⁽¡Ṡị

```

**Try it online!** (**18** bytes)

```
8220,163,187Ọ

```

**Try it online!** (**13** bytes)

```
“£»

```

**Try it online!** (**3** bytes)

```
!

```

**Try it online!** (**1** byte)

**18+13+3+1=35** bytes

### How?

```
ØJiⱮ⁾ɱṾ⁽÷ṃ;ṾØJ⁽¡Ṡị - Main Link: no arguments
    ⁾ɱṾ            - list of charcters -> ['ɱ','Ṿ']
ØJ                 - yield the characters of Jelly's code-page
   Ɱ               - Ɱap across the two characters applying:
  i                -   first index of? -> [163, 187]
       ⁽÷ṃ         - 8220 (a base 250 compressed number)
          ;        - concatenate -> [8220, 163 187]
           Ṿ       - un-eval (get Jelly code) -> "8220,163,187"
                   - (Note: here a full program prints 8220,163,187 as it is the end
                   - of a leading constant chain due to the following constant)
            ØJ     - yield the characters of Jelly's code-page
              ⁽¡Ṡ  - 1206 (a base 250 compressed number)
                 ị - index into (1-indexed & modular, so gets the 182nd item, 'Ọ')
                   - implicit print (making the final output 8220,163,187Ọ)

8220,163,187Ọ - Main link: no arguments
8220,162,187  - list of numbers -> [8220, 162, 187]
            Ọ - cast ordinals to characters -> ['“','£','»']
              - implicit print (flat Jelly lists print as if strings so outputs “£»)

“£» - Main link: no arguments
“   - open string-literal
 £  - the content of the string-literal
  » - close it interpreting as a compressed string
    - this yields ['!']
    - implicit print (outputs !)

! - Main link: no arguments
! - factorial (of implicit input 0 - 0! = 1 as it is the empty product)
  - implicit print (outputs 1)

```

# Answer
> 3 votes
# Python 2, 3 snippets, 68 + 12 + 3 = 83 bytes

```
chr(44*2+4).join([chr(42&54),`45+25`,`42*2+52`,`4*4+55`+chr(42&54)])

```

which produces the string of octal literals:

```
"\70\136\71"

```

which produces:

```
8^9

```

Which finally produces `1`.

Try it online!

# Answer
> 2 votes
# SmileBASIC, chain 3, 375 bytes

```
k=59599-44444print c("sbanm",k,4,"")+c("sbwav",44-5,2,"")+c("sbwav",594-222,4,"")+c("game5vs",4528-442,2,"")+c("sbanm",k,4,"")+c("sbanm",72,5-4,"")*2+c("sbwav",594-222,4,"")+c(sbwav,854-44,2,"")+c("staffroll",259+2,9,"")+c("ex8techdemo",24455,5-2,"")+key(4)[.]def c(f,s,l,q)for i=.to-5+l+4q=q+load("txt:sys/"+f,.)[s+i]next:return q:end

```

Outputs:

```
CHR$63OUT A$CHR$33OUT B$PRINT A$;B$;L

```

Outputs:

```
?!0

```

Outputs:

```
1

```

# Answer
> 2 votes
# PHP 7.0, 2-chain, 35 + 8 = 43 bytes

While writing my initial answer I realized I could just use base64 encode the second echo. It shaved off 11 bytes, so here it is. You can find my original idea below, too.

### Run using php -r:

```
echo base64_decode('RUNITyAxPz4=');

```

This outputs:

```
ECHO 1?>

```

Which then obviously prints:

```
1

```

### Output:

*My code when run in a terminal. The appended **&& echo** is for readability only.*

### Comments:

There's not much to it really. Very simple once you know about "?\>" implicitly acting as ";". The "tricky" part was to figure out what to encode:

* *ECHO 1;* became *RUNITyAx**O**w==*, so we have a collision of uppercase O's. No good.
* *echo 1;* became *ZWN**o**byAxOw==*, so now there's two *lower*case o's. Unfortunate!
* *ECHO 1?\>* became *RUNITyAxPz4=*. It's the same length and none of the characters collide. So that's it!

### Alternatively we can use "echO" and "ECHo", too (36 + 7 = 43 bytes).

```
echO base64_decOde('RUNIbyAxOw==')?>
ECHo 1;
1

```

We can also switch the ; and ?\> around using that. It works equally well and it all scores the same in length.

---

---

## My initial solution:

# PHP 7.0, 2-chain, 44 + 10 = 54 bytes

This is the best I could come up with at first. I understood that "unique characters" meant "echo" is not equal to "ECHO". Hope I got that right!

### Run using php -r:

```
echo strtoupper(urldecode('echo true%3b'))?>

```

This outputs:

```
ECHO TRUE;

```

Which in turn gives us our number:

```
1

```

### Output:

*My code when run in a terminal. The appended **&& echo** is for readability only.*

### Some comments:

* I think you can only do a 2-chain in PHP since it requires the ";" instruction separator.
    + You can get around this *once* by using "?\>", which implies a semicolon, but obviously can't re-use it a second time
    + This was the hardest part for me to figure out. I didn't know this worked beforehand, nor that "?\>" was even allowed when running via php -r
* By using strtoupper() I was able to just write the code for chain #2 in lowercase, while the output is obviously uppercase. Easy mode right there!
* urldecode() allows me to encode ";" as "%3b"
* That's all there is really, nothing too exciting

---

Thanks for the challenge, I learned something today!

# Answer
> 2 votes
# Lua, 2 chain, 83+8=91 bytes

```
load(('').char(0x70,0x72,0x69,0x6E,0x74,39,0x70,0x72,0x69,0x6E,0x74,34,49,34,39))()

```

Outputs

```
print"1"

```

Which outputs

```
1

```

# Answer
> 1 votes
# Charcoal, 2 programs, 10 + 2 = 12 bytes

```
⭆´Ｇ´·℅⊕⊕℅ι

```

Try it online! Outputs

```
Ｉ¹

```

Try it online! Which outputs 1.

# Answer
> 1 votes
# Braingolf, 2 chain, 9 + 2 = 11 bytes

```
72-_#23-@

```

Try it online!

This outputs

```
5/

```

Try it online!

(Plus some default output which can be ignored per OP's rules)

This in turn outputs

```
1

```

# Answer
> 1 votes
# Röda, 2 chain, 31 + 3 = 34 bytes

Snippet 1:

```
(`X.Z`/"")|ord _|push _+3|chr _

```

Try it online!

Snippet 2:

```
[1]

```

Try it online!

They are snippets, because every valid Röda program must include `main{...}` bloat. They are also valid Röda REPL programs.

# Answer
> 1 votes
# dc, 3 programs, 48 bytes

First:

```
82 2-adAArdAAI2*-rAAI-I2/2^-f

```

Yields the second:

```
75
P
90
P
110
P

```

Yields the third:

```
KZn

```

Yields `1`.

Try it online! (has some stack-clearing and newline-printing code thrown in to make all three bits run in one go).

Perhaps best to start at program three, `KZn`. There are only a few ways to print things in `dc`, and I realized at this stage I would probably be stuck with either `p` or `n`, both of which are in the 100s in decimal ASCII. This means that I was almost certainly going to have to generate 1 instead of just using the program `1n`. `K` pushes the current (default: 0) precision to the stack, and `Z` pushes the number of digits of top-of-stack, which gives us the 1 to print.

The second program is pretty straightforward. `P` prints the character with the given ASCII value, so we print `75` (`K`) `90` (`Z`) and finally `110` (`n`), which works wonderfully. It also means that, aside from the aforementioned 1, I can't use the digits 5, 7, 9, or 0 elsewhere. I also need a method other than `P` for turning numbers into characters.

The first program, then, has to make four numbers without using the digits 1, 5, 7, 9, or 0. It needs to make **`80`** (ASCII value of `P`): `82 2-`; **`75`**: `AA` (110) `I-` (subtract the default input radix, 10) `I2/` (so, 5) `2^` (so, 5^2, 25) `-` (75); **`90`**: `AA` (110) `I2*` (twice the default input radix of 10, so 20) `-` (90); and **`110`**: well, it's just `AA`. After making `80`, we use `a` to convert a number to a string. There are some `r`everse and `d`uplicate commands in there to put the `P`s in the right spots, and then finally we print the whole stack with `f`.

I'm pretty sure I didn't screw this up, but I did have my head spinning a little bit...

# Answer
> 1 votes
# 05AB1E, 5 + 3 = 8 bytes

```
ght<n

```

Try it online!

which right off the bat returns

I am taking the output 1.0 as not equalling 1, so I run that code:

```
1.0

```

Try it online!

which returns

```
1

```

And there you go!

Number of programs = `2`

# Answer
> 0 votes
# Ruby, 2-chain, 24+3 = 27 bytes

```
$><<(''<<56+56<<' '<<49)

```

Output is

```
p 1

```

---
Tags: code-challenge, code-generation
---


title: Split the bits!

text:
# Question
Title: Split the bits!
We define \\$V(x)\\$ as the list of distinct powers of \\$2\\$ that sum to \\$x\\$. For instance, \\$V(35)=\[32,2,1\]\\$.

By convention, powers are sorted here from highest to lowest. But it does not affect the logic of the challenge, nor the expected solutions.

## Task

Given a semiprime \\$N\\$, replace each term in \\$V(N)\\$ with another list of powers of \\$2\\$ that sum to this term, in such a way that the union of all resulting sub-lists is an exact cover of the matrix \\$M\\$ defined as:

$$M\_{i,j}=V(P)\_i \times V(Q)\_j$$

where \\$P\\$ and \\$Q\\$ are the prime factors of \\$N\\$.

This is much easier to understand with some examples.

## Example #1

For \\$N=21\\$, we have:

* \\$V(N)=\[16,4,1\]\\$
* \\$P=7\\$ and \\$V(P)=\[4,2,1\]\\$
* \\$Q=3\\$ and \\$V(Q)=\[2,1\]\\$
* \\$M=\pmatrix{8&4&2\\4&2&1}\\$

To turn \\$V(N)\\$ into an exact cover of \\$M\\$, we may split \\$16\\$ into \\$8+4+4\\$ and \\$4\\$ into \\$2+2\\$, while \\$1\\$ is left unchanged. So a possible output is:

$$\[ \[ 8, 4, 4 \], \[ 2, 2 \], \[ 1 \] \]$$

Another valid output is:

$$\[ \[ 8, 4, 2, 2 \], \[ 4 \], \[ 1 \] \]$$

## Example #2

For \\$N=851\\$, we have:

* \\$V(N)=\[512,256,64,16,2,1\]\\$
* \\$P=37\\$ and \\$V(P)=\[32,4,1\]\\$
* \\$Q=23\\$ and \\$V(Q)=\[16,4,2,1\]\\$
* \\$M=\pmatrix{512&64&16\\128&16&4\\64&8&2\\32&4&1}\\$

A possible output is:

$$\[ \[ 512 \], \[ 128, 64, 64 \], \[ 32, 16, 16 \], \[ 8, 4, 4 \], \[ 2 \], \[ 1 \] \]$$

## Rules

* Because factorizing \\$N\\$ is not the main part of the challenge, you may alternately take \\$P\\$ and \\$Q\\$ as input.
* When several possible solutions exist, you may either return just one of them or all of them.
* You may alternately return the exponents of the powers (e.g. \\$\[\[3,2,2\],\[1,1\],\[0\]\]\\$ instead of \\$\[\[8,4,4\],\[2,2\],\[1\]\]\\$).
* The order of the sub-lists doesn't matter, nor does the order of the terms in each sub-list.
* For some semiprimes, you won't have to split any term because \\$V(N)\\$ already is a perfect cover of \\$M\\$ (see A235040). But you still have to return a list of (singleton) lists such as \\$\[\[8\],\[4\],\[2\],\[1\]\]\\$ for \\$N=15\\$.
* This is !

### Test cases

```
 Input | Possible output
-------+-----------------------------------------------------------------------------
 9     | [ [ 4, 2, 2 ], [ 1 ] ]
 15    | [ [ 8 ], [ 4 ], [ 2 ], [ 1 ] ]
 21    | [ [ 8, 4, 4 ], [ 2, 2 ], [ 1 ] ]
 51    | [ [ 32 ], [ 16 ], [ 2 ], [ 1 ] ]
 129   | [ [ 64, 32, 16, 8, 4, 2, 2 ], [ 1 ] ]
 159   | [ [ 64, 32, 32 ], [ 16 ], [ 8 ], [ 4 ], [ 2 ], [ 1 ] ]
 161   | [ [ 64, 32, 16, 16 ], [ 8, 8, 4, 4, 4, 2, 2 ], [ 1 ] ]
 201   | [ [ 128 ], [ 64 ], [ 4, 2, 2 ], [ 1 ] ]
 403   | [ [ 128, 64, 64 ], [ 32, 32, 16, 16, 16, 8, 8 ], [ 8, 4, 4 ], [ 2 ], [ 1 ] ]
 851   | [ [ 512 ], [ 128, 64, 64 ], [ 32, 16, 16 ], [ 8, 4, 4 ], [ 2 ], [ 1 ] ]
 2307  | [ [ 1024, 512, 512 ], [ 256 ], [ 2 ], [ 1 ] ]

```

# Answer
# K (ngn/k), ~~66~~ 63 bytes

```
{(&1,-1_~^(+\*|a)?+\b)_b:b@>b:,/*/:/2#a:{|*/'(&|2\x)#'2}'x,*/x}

```

Try it online!

accepts (P;Q) instead of N

algorithm:

* compute A as the partial sums of V(P\*Q)
* multiply each V(P) with each V(Q), sort the products in descending order (let's call that R), and compute their partial sums B
* find the positions of those elements in B that also occur in A; cut R right after those positions
> 4 votes

# Answer
# Jelly, 24 bytes

```
BṚT’2*
Ç€×þ/FṢŒṖ§⁼Ç}ɗƇPḢ

```

A monadic link accepting a list of two integers `[P, Q]` which yields one possible list of lists as described in the question.

**Try it online!** (footer prints a string representation to show the list as it really is)

Or see the test-suite (taking a list of N and reordering results to be like those in the question)

### How?

We may always slice up the elements of \\$M\\$ from lowest up, greedily (either there is a \\$1\\$ in \\$M\\$ or we had an input of \\$4\\$, when \\$M=\[\[4\]\]\\$) in order to find a solution.

Note: the code collects all (one!) such solutions in a list and then takes the head (only) result - i.e. the final head is necessary as the partitions are not of all possible orderings.

```
BṚT’2* - Link 1, powers of 2 that sum to N: integer, N    e.g. 105
B      - binary                                                [1,1,0,1,0,0,1]
 Ṛ     - reverse                                               [1,0,0,1,0,1,1]
  T    - truthy indices                                        [1,4,6,7]
   ’   - decrement                                             [0,3,5,6]
    2  - literal two                                           2
     * - exponentiate                                          [1,8,32,64]

Ç€×þ/FṢŒṖ§⁼Ç}ɗƇPḢ - Main Link: list of two integers, [P,Q]
Ç€                - call last Link (1) as a monad for €ach
    /             - reduce with:
   þ              -   table with:
  ×               -     multiplication
     F            - flatten
      Ṣ           - sort
       ŒṖ         - all partitions
              Ƈ   - filter keep if:
             ɗ    -   last three links as a dyad:
         §        -     sum each
            }     -     use right...
               P  -       ...value: product (i.e. P×Q)
           Ç      -       ...do: call last Link (1) as a monad
          ⁼       -     equal? (non-vectorising so "all equal?")
                Ḣ - head

```
> 3 votes

# Answer
# Python 2, ~~261~~ ~~233~~ ~~232~~ 231 bytes

```
g=lambda n,r=[],i=1:n and g(n/2,[i]*(n&1)+r,i*2)or r
def f(p,q):
 V=[[v]for v in g(p*q)];i=j=0
 for m in sorted(-a*b for a in g(p)for b in g(q)):
	v=V[i]
	while-m<v[j]:v[j:j+1]=[v[j]/2]*2
	i,j=[i+1,i,0,j+1][j+1<len(v)::2]
 return V

```

Try it online!

1 byte from Jo King; and another 1 byte due to Kevin Cruijssen.

Takes as input `p,q`. Pursues the greedy algorithm.
> 3 votes

# Answer
# Jelly, 41 bytes

```
Œṗl2ĊƑ$Ƈ
PÇIP$ƇṪÇ€Œpµ³ÇIP$ƇṪƊ€ŒpZPṢ⁼FṢ$µƇ

```

Try it online!

Should probably be much shorter (some parts feel very repetitive; especially `ÇIP$Ƈ`, but I don't know how to golf it). Explanation to come after further golfing. Returns all possible solutions in case multiple exist and takes input as \\$\[P, Q\]\\$.
> 2 votes

# Answer
# Jelly, 34 bytes

```
BṚT’2*
PÇŒṗæḟ2⁼ƊƇ€ŒpẎṢ⁼Ṣ}ʋƇÇ€×þ/ẎƊ

```

Try it online!

Input format: `[P, Q]` (the TIO link above doesn't accept this, but a single number instead, to aid with the test cases).

Output format: List of all solutions (shown as grid representation of 3D list over TIO).

Speed: Turtle.
> 2 votes

# Answer
# Pyth, 27 bytes

Inspired by Jonathan Allan's crushing of my Jelly solution. Takes \\$N\\$ as input.

```
L^2x1jb2;hfqyQsMT./S*M*FyMP

```

Try it here!
> 1 votes

# Answer
# Haskell, ~~281~~ 195 bytes

```
import Data.List
r=reverse.sort
n#0=[]
n#x=[id,(n:)]!!mod x 2$(n*2)#div x 2
m!0=[]
m!x=m!!0:tail m!(x-m!!0)
m%[]=[]
m%n=m!head n:drop(length$m!head n)m%tail n
p&q=r[x*y|x<-1#p,y<-1#q]%r(1#(p*q))

```
> 1 votes

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


title: Stack Exchange Stock Exchange - V3

text:
# Question
Title: Stack Exchange Stock Exchange - V3
> **NOTICE:** This challenge is now closed: I will no longer be updating the leaderboard and will not change the accepted answer. However, you are free to run the controller and update the leaderboard yourself, if you wish.

## Join the chat!

## Introduction

Good evening, traders! You are all traders for the golfing company PPCG. Your task is to make as much money as possible.

## Challenge

Write a program that buys and sells shares on the Stack Exchange Stock Exchange with the aim of making as much money as possible.

## Gameplay

All players will start with 5 shares and $100 in their bank. The game always starts with a share price of $10.

Each game will have 1000 rounds where the first round is round `1`. In each round, your program will be supplied four arguments as input: the current share price, the number of shares you hold, the amount of money you own and the round number (1-indexed).

For example, if my program is `test1.py`, the share price is `100`, the number of shares I hold is `3`, the amount of money I have is `1200`, and the round number is `576`, my program will be run like so:

```
python test1.py 100 3 1200 576

```

In a round, the share price given to each player will be the same. This doesn't change until the end of the round.

In response, the player must print their command. There are two options:

* Buy shares: This command is given as `bn` where `n` is the number of shares you wish to buy. For example, if you want to buy 100 shares, you would output:

```
b100

```

When buying shares, you are allowed an overdraft of up to $1000. If you try to buy enough shares that exceed this overdraft (your bank balance goes below $-1000), you will be declared bankrupt. This means that you will lose all of your shares and your balance will be set to $50.

The share price will be unaffected by your command if you go bankrupt.

(If your balance is $-1000, you are not bankrupt. However if your balance is $-1001, you are bankrupt)

* Sell shares: This command is given as `sn` where `n` is the number of shares you wish to sell. For example, if you want to sell 100 shares, you would output:

```
s100

```

You may not sell more shares than you own. If you try to do this, your request will be denied, and you will skip the round.

If you want to skip the round and do nothing, output either `b0` or `s0`.

Your request will be denied if you try to buy or sell a negative number of shares and/or a non-integer number of shares.

After 5 rounds, at the end of each round, all players will be payed a dividend, the value of which is 5% of the mean average share price of the last 5 rounds.

## How does it work?

Initially the share price will be $10. At the end of each round, it will be recalculated using the formula:

$$\text{New Share Price} = \text{Old Share Price} + (\text{Number of shares bought}-\text{Number of shares sold})$$

The share price will be limited so that it never falls below $1.

To prevent overly rapid change, the change in share price is limited to a maximum of \\$\pm$200\\$.

## Rules

* Your program must have a name

* Your program is allowed a single text file for data storage. It must be stored in the same folder as your program

* Include in your answer details of how to run your program

* This KotH is open to all programming languages that are free-to-use and can be run on Windows 10

* Your score is based solely on the contents of your balance. Any money locked up in shares will not be counted

* You may edit your program at any time. Before each game, the latest code will be saved and compiled

* You should not write code which specifically targets another bot.

## Controller

The controller is written in Python and can be found here: https://gist.github.com/beta-decay/a6abe40fc9f4ff6cac443395377ec31f

At the end it will print a leaderboard and display a graph of how the share price changed throughout the game.

For example, when two random bots were playing

## Winning

The player with the highest amount of money in their balance at the end of the last game wins.

## Leaderboard

**Game 4: 16:14 10/08/2018**

```
Name                                Balance

Experienced Greedy Idiot            $14802860126910608746226775271608441476740220190868405578697473058787503167301288688412912141064764060957801420415934984247914753474481204843420999117641289792179203440895025689047561483400211597324662824868794009792985857917296068788434607950379253177065699908166901854516163240207641611196996217004494096517064741782361827125867827455285639964058498121173062045074772914323311612234964464095317202678432969866099864014974786854889944224928268964434751475446606732939913688961295787813863551384458839364617299883106342420461998689419913505735314365685264187374513996061826694192786379011458348988554845036604940421113739997490412464158065355335378462589602228039730
Equalizer                           $763185511031294813246284506179317396432985772155750823910419030867990447973211564091988995290789610193513321528772412563772470011147066425321453744308521967943712734185479563642323459564466177543928912648398244481744861744565800383179966018254551412512770699653538211331184147038781605464336206279313836606330
Percentage Trader                   $448397954167281544772103458977846133762031629256561243713673243996259286459758487106045850187688160858986472490834559645508673466589151486119551222357206708156491069820990603783876340193236064700332082781080188011584263709364962735827741094223755467455209136453381715027369221484319039100339776026752813930
OYAIB                               $8935960891618546760585096898089377896156886097652629690033599419878768424984255852521421137695754769495085398921618469764914237729576710889307470954692315601571866328742408488796145771039574397444873926883379666840494456194839899502761180282430561362538663182006432392949099112239702124912922930
Chimps on a Typewriter              $176504338999287847159247017725770908273849738720252130115528568718490320252556133502528055177870
Greedy B*****d                      $17689013777381240
Illiterate Dividend Investor        $2367418699671980
Lucky Number 6                      $4382725536910
Lone Accountant                     $90954970320
Buy/Reinvest                        $127330
Technical Analysis Robot            $126930
Dollar Cost Averager                $106130
Fibonacci                           $69930
Novice Broker                       $28130
Buy Low                             $6130
Naive Statistician                  $6130
Fallacious Gambler                  $6130
Passive Trader                      $4980
Half More or Nothing                $4920
Monkeys on a Typewriter             $66

```

**View graphs of each contestant**

---

<sub>**Related but the gameplay and winning criterion are very different to this challenge.**</sub>

# Answer
# The Experienced Greedy Idiot

PHP, tested on PHP \>= 7, should work on previous ones as well.

```
<?php

class StickExchange
{
    private $dbFile;
    private $sharePrice;
    private $shares;
    private $balance;
    private $overdraft;

    public function __construct($sharePrice, $shares, $balance, $round)
    {
        $this->dbFile = __FILE__ . '.txt';
        $this->sharePrice = gmp_init($sharePrice);
        $this->shares = gmp_init($shares);
        $this->balance = gmp_init($this->parseScientificNotationToInt($balance));
        $this->overdraft = gmp_init(1000);

        $action = 'b';

        if ($round == 1) {
            $this->buy();
        } elseif ($round == 1000) {
            $this->sell();
        } else {
            $content = $this->getDbContent();
            $lastPrice = gmp_init($content['price']);
            $secondLastPrice = gmp_init($content['last_price']);
            $lastAction = $content['action'];

            $shareAndLastCmp = gmp_cmp($this->sharePrice, $lastPrice);
            $lastAndSecondLastCmp = gmp_cmp($lastPrice, $secondLastPrice);

            if ($shareAndLastCmp > 0 && $lastAndSecondLastCmp > 0) {
                if ($lastAction == 'b') {
                    $this->sell();
                    $action = 's';
                } else {
                    $this->buy();
                }
            } elseif ($shareAndLastCmp < 0 && $lastAndSecondLastCmp < 0) {
                if ($lastAction == 'b') {
                    $this->sell();
                    $action = 's';
                } else {
                    $this->skip();
                }
            } elseif ($shareAndLastCmp > 0) {
                $this->sell();
                $action = 's';
            } elseif ($shareAndLastCmp < 0) {
                $this->buy();
            } else {
                $this->skip();
            }
        }

        $this->setDbContent([
            'action' => $action,
            'price' => gmp_strval($this->sharePrice),
            'last_price' => isset($lastPrice) ? gmp_strval($lastPrice) : '0',
        ]);
    }

    private function parseScientificNotationToInt($number)
    {
        if (strpos($number, 'e+') !== false) {
            $sParts = explode('e', $number);
            $parts = explode('.', $sParts[0]);
            $exp = (int)$sParts[1];

            if (count($parts) > 1) {
                $number = $parts[0] . $parts[1];
                $exp -= strlen($parts[1]);
            } else {
                $number = $parts[0];
            }

            $number = gmp_init($number);
            $pow = gmp_pow(gmp_init(10), $exp);
            return gmp_strval(gmp_mul($number, $pow));
        } elseif (strpos($number, 'e-') !== false) {
            return sprintf('%d', $number);
        } else {
            $parts = explode('.', $number);
            return $parts[0];
        }
    }

    private function getDbContent()
    {
        return unserialize(file_get_contents($this->dbFile));
    }

    private function setDbContent($content)
    {
        file_put_contents($this->dbFile, serialize($content));
    }

    private function buy()
    {
        $realBalance = gmp_add($this->balance, $this->overdraft);
        $sharesToBuy = gmp_div($realBalance, $this->sharePrice);
        $this->stdout('b' . gmp_strval($sharesToBuy));
    }

    private function sell()
    {
        $this->stdout('s' . gmp_strval($this->shares));
    }

    private function skip()
    {
        $this->stdout('b0');
    }

    private function stdout($string)
    {
        $stdout = fopen('php://stdout', 'w');
        fputs($stdout, $string);
        fclose($stdout);
    }
}

new StickExchange($argv[1], $argv[2], $argv[3], $argv[4]);

```

An updated version of "The Greedy Idiot" with re-structured behavior and bug fixes related to working with huge numbers.

### Notes:

* Save in a file and run it like this: `php C:\path\path\stack_exchange.php 10 5 100 1`
* This script creates a text file with same name as the script file and a `.txt` appended to the end. So please run with an user with appropriate write permission on the script path.
* A simple how to install PHP 7.2 on windows: http://www.dorusomcutean.com/how-to-install-php-7-2-on-windows/
* To work with super huge numbers, I had to use GMP, so these two lines on `php.ini` should be un-commented (the semi-colon at start of line should be removed, if it isn't already):
    + `; extension_dir = "ext"`
    + `;extension=gmp`
> 11 votes

# Answer
# Chimps On A Typewriter

```
import random
from sys import argv

share_price = int(argv[1])
share_count = int(argv[2])
balance = float(argv[3])

x = random.random()
if x < 0.5:
    max_buy = balance / share_price
    buy_count = int(max_buy * random.random())
    print('b' + str(buy_count))
else:
    sell_count = int(share_count * random.random())
    print('s' + str(sell_count))

```

Chimps are smarter than monkeys, they won't buy stocks they can't afford, or sell stocks they don't have.

Still pretty random otherwise though.

Run with python3, but should(?) work with python2 as well
> 19 votes

# Answer
# OYAIB

```
from sys import argv

share_price = float(argv[1])
shares      = int(argv[2])
cash        = float(argv[3])
cur_round   = int(argv[4])
tot_rounds  = 1000.0

investments = shares * share_price
total_assets = investments + cash

target_cash = round(cur_round / tot_rounds * total_assets)

if target_cash > cash:
  shares_to_sell = min(shares, round((target_cash - cash) / share_price))
  print('s%d' % shares_to_sell)
else:
  shares_to_buy = round((cash - target_cash) / share_price)
  print('b%d' % shares_to_buy)

```

Following the old saying of "own your age in bonds," this program tries to do the same. This way we aren't subject to market volatility at the end-game.

**Edit:** Looking at the controller it shows that we can only buy/sell full shares, but can have a fractional account balance.
> 10 votes

# Answer
# Lone Accountant

`buy-sell.py`:

```
from sys import argv

Price = int(argv[1])
Shares = int(argv[2])
Balance = float(argv[3])
Round = int(argv[4])

if Round % 2 == 0: print('s' + str(Shares))
if Round % 2 == 1: print('b' + str(int((Balance + 1000) / Price)))

```

Doesn't store anything in `buy-sell.txt`.

In odd rounds, it buys as many shares as it can. In even rounds, it sells all of its shares.

The intent is to first raise the share price by buying as many shares as possible, and then sell those shares to get more money. It works because the final round is even (round 1000).

Even though the share price will remain the same (`5`) after each pair of rounds (assuming the bot is alone, therefore ***Lone* Accountant**), the bot's balance increases, since the selling price is higher than the buying price, and more balance leads to the ability of buying more shares. It's a vicious cycle, but in a good way (for me).

The major vulnerability comes with evil bots playing alongside, selling in order to lower the share price (not sure if it's good for them either). In this case, the bot may remain with a balance of $-890, provided there are enough evil bots. This accountant really wants their peace of mind. ;-)
> 8 votes

# Answer
# The Passive Trader

```
from sys import argv

share_price = int(argv[1])
balance = float(argv[3])
round_num = int(argv[4])

if round_num == 1:
    print('b%s' % str(int(balance / share_price)))
else:
    print('b0')

```

This guy isn't big on this whole "Stocks" thing, but he heard that if he just spends a little money now, he'll get little bits of money over time that'll add up to more than he spent.

He'll buy enough stocks to go to $0 (no overdraft for this fella, he's not gunna put himself in debt for a little profit), then sit around letting the dividends build

Run with python3, but should(?) work with python2 as well.
> 5 votes

# Answer
# Monkeys On A Typewriter

```
import random

cmd = ['b', 's'][int(random.random() * 2)]
num = str(int(random.random() * 1000000))
print("%s%s" % (cmd, num))

```

It's a bunch of monkeys on typewriters. Randomly sells or buys X stocks, where:
`0 <= X <= 1,000,000`

Run with python3, but should(?) work with python2 as well
> 4 votes

# Answer
# Buy Low

(Python 2 or 3)

```
import random

def run(price, shares, balance, round_):
    # We get no value from our leftover shares at the end, so sell them all.
    if round_ == 1000:
        print('s' + str(int(shares)))
        return

    # If the price is low enough, buy everything we can.
    if price <= 20 + round_ * 60:
        print('b' + str((balance + 1000) // price))
        return

    # If we have no shares, wait for the price to drop.
    if shares == 0:
        print('b0')
        return

    # Sometimes sell shares so we can buy if the price gets low again.
    if random.random() < 0.4:
        print('s1')
        return

    # Otherwise, just wait for a better price.
    print('b0')

if __name__ == '__main__':
    import sys
    run(*[float(x) for x in sys.argv[1:]])

```
> 4 votes

# Answer
# The Naïve Statistician

Made for Python 3, might work in Python 2

```
from sys import argv
from math import floor

# Save an entry to the stock history
def save_history(price):
    with open('stockhistory.txt', 'a') as f:
        f.write(str(price) + '\n')

# Load the stock history
def load_history():
    with open('stockhistory.txt', 'r') as f:
        return [float(line.strip()) for line in f]

# Calculate average price rise/fall streak length
def average_streak(history, condition):
    streaks = []
    current_streak = 0
    last_price = history[0]
    for price in history[1:]:
        if condition(last_price, price):
            current_streak += 1
        elif current_streak:
            streaks += [current_streak]
            current_streak = 0
        last_price = price
    if current_streak:
        streaks += [current_streak]
    return sum(streaks) / len(streaks) if streaks else None

# Calculate the current streak length
def current_streak(history, condition):
    streak = 0
    while streak < len(history) - 1 and condition(history[-streak - 2], history[-streak - 1]):
        streak += 1
    return streak

def run(share_price, share_count, balance, round_number):
    save_history(share_price)

    # Sell all shares if it is the last round
    if round_number == 1000:
        print('s' + str(int(share_count)))
        return

    # Buy as many shares as possible if the price is down to one, as there's
    # nothing to lose
    if share_price == 1:
        buy_count = int(balance + 1000)
        print('b' + str(buy_count))
        return

    history = load_history()

    # Calculate the average and current rise/fall streaks
    average_rise = average_streak(history, lambda a, b: a <= b)
    current_rise = current_streak(history, lambda a, b: a <= b)
    average_fall = average_streak(history, lambda a, b: a >= b)
    current_fall = current_streak(history, lambda a, b: a >= b)

    # Do nothing if there's no analyzed data
    if not average_fall or not average_rise:
        print('b0')
        return

    # Buy shares if the current rise streak is as long as or longer than average
    if current_rise > current_fall and current_rise >= average_rise:
        buy_count = (balance + 1000) / share_price
        print('b' + str(int(buy_count)))
        return

    # Sell shares if the current fall streak is as long as or longer than average
    if current_fall > current_rise and current_fall >= average_fall:
        print('s' + str(int(share_count)))
        return

    # Otherwise, do nothing
    print('b0')

run(*map(float, argv[1:]))

```

This is a naïve statistician that tries to predict stock prices by only buying/selling if the price has risen/fallen for longer than usual, while also buying stocks if the price is down to one and selling all stocks on the last round.
> 4 votes

# Answer
# Percentage Trader Python3

(maybe works in python2)

```
import sys
args=sys.argv

price=int(args[1])
held=int(args[2])
money=int(args[3])
roundNum=int(args[4])
prevPrice=0

if roundNum==1:
    print("b"+str((money+1000)//price))
else:
    if roundNum==1000:
        print("s"+str(held))
    else:
        with open("percentageTrader.dat","r") as f:
            prevPrice=int(f.read())
        if(price>prevPrice):
            toSell=int(held*int(1000000*(price-prevPrice))/(price))//1000000
            print("s"+str(toSell))
        if(price<prevPrice):
            toBuy=int(((money+1000)//price)*int(1000000*(prevPrice-price))//(prevPrice))//1000000
            print("b"+str(toBuy))
        if(price==prevPrice):
            print("b0")

with open("percentageTrader.dat","w") as f:
    f.write(str(price))

```

### Instructions on running

* Save as filename.py
* Run with python filename.py price #shares balance round#

### How it works

* First round the bot purchases as many shares as it can afford.
* If the price increases, the bot sells a percentage of shares equal to the percentage increase in price(calculated from new value)
* If the price decreases, the bot buys a percentage of the maximum shares it could buy equal to the percentage decrease in price(calculated from previous value)
* Sells off everything at round 1000

Changes should hopefully remove the problems caused by floating point division
> 4 votes

# Answer
# Equalizer

```
from sys import argv
p, n, b, r = map(int, argv[1:])
c = p*n
print "bs"[(c+b)/2>b] + str(int(abs(((c-b)/2)/p))) if r < 999.5 else "s" + str(int(n))

```

Partitions its financial resources equally between cash and stocks on every round except the last. I believe this strategy to be a mathematically sound way of making at least *some* money, but I may be proven wrong.

There may or not be bugs that I haven't caught. Also golfed somewhat.
> 4 votes

# Answer
# Fallacious Gambler

(Python 2 or 3)

```
import random

def run(price, shares, balance, round_):
    # We get no value from our leftover shares at the end, so sell them all.
    if round_ == 1000:
        print('s' + str(int(shares)))
        return

    # For the first round, just watch.
    if round_ == 1:
        with open('fg.txt', 'w') as f:
            f.write('1 0 10')
        print('b0')
        return

    # Get the state.
    with open('fg.txt') as f:
        direction, streak, previous = map(int, f.read().strip().split())
    change = price - previous

    # If the market isn't moving, wait for it to get hot again.
    if change == 0:
        print('b0')
        return

    # Keep track of the market direction.
    if (change > 0) == (direction > 0):
        streak += 1
    else:
        streak = 0
        direction *= -1

    # If the market's been going one way for too long, it has to switch, right?
    if streak > 5:
        if direction > 0:
            print('s' + str(shares // 2))
        else:
            print('b' + str((balance + 1000) // price // 2))
    # Otherwise, the market's too volatile.
    else:
        print('b0')

    # Save the state.
    with open('fg.txt', 'w') as f:
        f.write('%d %d %d' % (direction, streak, price))

if __name__ == '__main__':
    import sys
    run(*[float(x) for x in sys.argv[1:]])

```
> 3 votes

# Answer
# The Dollar Cost Averager

(tested with Python 3.7)

First post in codegolf so tell me if I did something wrong.

The basic idea is to buy one share each round if that's possible and sell all shares at the end.

```
from sys import argv
share_price = int(argv[1])
share_count = int(argv[2])
balance = float(argv[3])
round = int(argv[4])

if round < 1000:
    if balance > share_price-1000:
        print("b1")
    else:
        print("b0")
else:
    print("s" + str(share_count))

```
> 3 votes

# Answer
# The (Dyalog) APL Farmer

```
r←apl_stock_farmer args
 round←¯1↑args
 :If 1=round
     (buyPrice sellPrice)←10 0
     bought←1
     (currPrice shares balance)←3↑args
     r←'b10'
 :ElseIf 1000=round
     r←'s',⍕shares
 :Else
     (currPrice shares balance)←3↑args
     :If (currPrice>buyPrice)∧bought
         bought←0
         sellPrice←currPrice
         r←'s',⍕shares
     :ElseIf (currPrice<sellPrice)∧~bought
         bought←1
         buyPrice←currPrice
         r←'b',⍕⌊(1000+balance)÷currPrice
     :Else
         r←'b0'
     :End
 :End

```

A TradFn which buys every possible share on the first round, and only sells when the current price of the shares is higher than the price they were bought for. After selling, the bot will only buy shares that are cheaper than the price it last sold shares for.

That's because the farmer's accountant told him that's how you do stock trading. "Buy low, sell high" and all that stuff.

### Disclaimer

This is my first attempt at a KotH challenge, and since I basically only do APL here, I decided to go on with it.

That said, I'm not completely sure if this will be able to be run alongside the other bots, since it's a Tradfn and can't be fed directly into a CMD/Bash shell.

So, to run this in Bash, you need the following command:

`$ echo apl_stock_farmer args | dyalog 'stock_exchange.dws' -script`

Where:

`apl_stock_farmer` is the name of the function, which is in the first line of code.

`args` is a vector of space separated arguments (in the first round, it would be `10 5 100 1`).

`dyalog` is the path to the Dyalog executable

`'stock_exchange.dws'` is the name (or path, if the file is not in the same directory the shell has open) of the workspace that contains the function. That workspace file can be obtained by opening a clear workspace, typing `)ed apl_stock_farmer`, pasting the code above and then doing a `)save <path>`. I can also provide this workspace file if that would be easier.

`-script` is just an argument that makes dyalog execute the given code and print to stdout without actually opening the REPL.

Unfortunately, I haven't found a way to make it work with the Windows CMD or Powershell, so I ran it using Git Bash. I'm not sure how feasible it is to put this bot on the competition, but I like this code way too much not to post it.
> 3 votes

# Answer
# Illiterate Dividend Investor

```
import random
from sys import argv

price = float(argv[1])
shares = int(argv[2])
cash = float(argv[3])
round = int(argv[4])

# buy 1st round, sell last round
if round == 1:
    print('b' + str(int((cash + 1000) / price)))
elif round == 1000:
    print('s' + str(shares))

# round right before dividend: sell
elif round % 5 == 4:
    print('s' + str(shares))

# 1 round after dividend: buy
elif round % 5 == 0:
    print('b' + str(int((cash + 1000) / price)))

# 2 rounds after dividend: 50/50 sell/try to buy
elif round % 5 == 1:
    if random.random() < 0.5:
        print('s' + str(shares))
    else:
        print('b' + str(int((cash + 1000) / price)))

# 3 rounds after dividend: sell if own shares (didn't sell last round), else buy
elif round % 5 == 2:
    if shares > 0:
        print('s' + str(shares))
    else:
        print('b' + str(int((cash + 1000) / price)))

# otherwise, 4 rounds after dividend, buy
else:
    print('b' + str(int((cash + 1000) / price)))

```

Assumes after dividends, people have more cash, so they will be more likely to buy. Sells right before dividends, buys right after. Goes through one other sell/buy cycle in the other 3 rounds.
> 3 votes

# Answer
# Novice Broker (but gets the basic idea)

`se_stock_exchange.rb`:

```
DATA_FILE = $0.sub /\.rb$/, ".data"
NUM_ROUNDS = 1000

share_price, num_shares, money, round = ARGV.map &:to_i

order = "s0"

if round == NUM_ROUNDS
  puts "s#{num_shares}"
  exit
end

if File.exists? DATA_FILE
  last_price, trend, bought_price = File.read(DATA_FILE).lines.map &:to_i
else
  last_price = 0
  trend = -1
  bought_price = 0
end

if (new_trend = share_price <=> last_price) != trend
  case trend
  when -1
    order = "b#{(money + 1000) / share_price}"
    bought_price = [bought_price, share_price].max
  when 1
    if share_price > bought_price
      order = "s#{num_shares}"
      bought_price = 0
    end
  end
  trend = new_trend
end

File.open(DATA_FILE, "w") { |f| f.puts share_price, trend, bought_price }

puts order

```

Waits until the price turns around, then buys/sells everything. I mean, that's what it says to do in *Day Trading for Dummies* <sup>Note: this is probably a real book, and that's probably something someone might get from it</sup>.

Saves data in `se_stock_exchange.data`. Run with `ruby se_stock_exchange.rb ${SHARE_PRICE} ${SHARES} ${MONEY} ${ROUND}` (substituting the appropriate values).
> 2 votes

# Answer
## Buy/Reinvest as much as possible!

Similar to my Dollar-Cost Averager that did, surprisingly, quite average, this buys each round as many shares as are affordable and only sells them in the last round.

```
from sys import argv

share_price = int(argv[1])
share_count = int(argv[2])
balance = float(argv[3])
round = int(argv[4])

if round < 1000:
    if balance > share_price-1000:
        buy_count = int((balance+1000)/share_price)
        print("b"+str(buy_count))
    else:
        print("b0")
else:
    print("s" + str(share_count))

```
> 2 votes

# Answer
# Half More or Nothing

```
def run(price, shares, balance, cur_round):
    if cur_round==1000:
        print('s'+str(int(shares)))
        return

    if cur_round==1:
        with open('HalfMoreOrNothing.dat', 'w') as f:
            f.write(str(int(price)))
        print('b'+str(int((balance+1000)/price)))
        return

    if shares==0:
        with open('HalfMoreOrNothing.dat', 'w') as f:
            f.write(str(int(price)))
        print('b'+str(int((balance+1000)/price)))
        return

    with open('HalfMoreOrNothing.dat', 'r') as f:
        bought_price=int(f.read())
    if price>=bought_price*1.5:
        print('s'+str(int(shares)))
        return

    print('b0')

if __name__ == '__main__':
    import sys
    run(*[float(x) for x in sys.argv[1:]])

```

I rarely use Python, let me know if this generates an error somewhere.

The strategy is to wait until the share price is at least 50% bigger than the price at the moment of bying them, then sell them, then immediately buy new shares so it can wait for the new share price raise.

Hopefully, ~~people~~ chimps won't start to sell shares near the end... (it seems that most bots just wait for the right moment, whatever that is)
> 2 votes

# Answer
# Fibonacci

I've rewritten this in Python 3 to make things easier. Hopefully!

```
import math
from sys import argv

price = float(argv[1])
shares = int(argv[2])
balance = float(argv[3])
roundNum = int(argv[4])

fibonacci = [2,3,5,8,13,21,34,55,89,144,233,377,610,987]
if (roundNum == 1):
    buy = int((balance+1000)/price)
    print('b' + str(buy))
elif (roundNum in fibonacci) and roundNum % 2 == 1 and balance > 0:
    buy = int((balance/price)/2)
    print('b' + str(buy))
elif ((roundNum in fibonacci) and roundNum % 2 == 0) or roundNum % 100 == 0:
    if (roundNum == 1000):
        sell = shares
        print('s' + str(sell))
    else:
        sell = math.ceil(shares/2)
        print('s' + str(sell))
else:
    print('b0')

```

It buys half the maximum amount of shares that is affordable when the round is equal to an odd Fibonacci number and sells half of the available shares when the round is equal to an even Fibonacci number and also every 100 rounds. Sells all shares on round 1000. Otherwise, it just waits. Only buys shares when balance is positive.
> 2 votes

# Answer
## Technical Analysis Robot

I study business economics so I tried to realize the simpliest method for analizing a stock market (the technical analysis). According to the theory you just have to analyze all the minimums of the graph to see if there is a trend (up ord down). During an up trend you have to buy and during a down trend you have to sell.

I don't think that this method will work too well but let's give it a try :)

```
import sys
from sys import argv

share_price = int(argv[1])
share_number = int(argv[2])
bank_account = float(argv[3])
round_number = int(argv[4])

max_buy_greedily = (1000 + bank_account) / share_price
minima = []

def log():
    f = open("log_technical_analysis.txt","a+")
    f.write("%d;" % share_price)

def analyze():
    f = open("log_technical_analysis.txt","r+")
    line = f.readline()
    values = line.split(";")
    values.pop()
    for i in range(len(values) - 1):
        if i > 0 and int(values[i-1]) > int(values[i]) and int(values[i+1]) > int(values[i]):
            minima.append(int(values[i]))
    if len(minima) >= 3 and minima[len(minima) - 1] > minima[len(minima) - 2] and minima[len(minima) - 2] > minima[len(minima) - 3]:
        print('b' + str(int(max_buy_greedily)))
    elif len(minima) >= 3 and minima[len(minima) - 1] < minima[len(minima) - 2] and minima[len(minima) - 2] < minima[len(minima) - 3]:
        print('s' + str(share_number))
    else:
        print('b0')

if round_number >= 994:
    print('s' + str(share_number))
    sys.exit(0)

if share_price <= 15:
    print('b' + str(int(max_buy_greedily)))
    log()
    sys.exit(0)

log()
analyze()
sys.exit(0)

```

Tested with python3
> 2 votes

# Answer
**Greedy B\*****d**

```
# Gready one...
from sys import argv

SMA_PERIOD = 5
LAST_BUY_DAY = 985
LAST_SELL_DAY = 993

# Save an entry to the stock history
def save_history(price):
    with open('db.txt', 'a') as f:
        f.write(str(price) + '\n')

# Load the stock history
def load_history():
    with open('db.txt', 'r') as f:
        return [float(line.strip()) for line in f]

def get_sma(d, n):
    l = d[-n:]
    return int(sum(l) / len(l))

def buy(price, account):
    if account + 1000 > 0:
        print 'b' + str(int((account + 1000) / price))
        return
    print 'b0'

def sell(holdings):
    print 's'+ str(int(holdings))

def run(price, holdings, account, day):

    save_history(price)
    d = load_history()

    if price <= get_sma(d, SMA_PERIOD) and day < LAST_BUY_DAY:
        return buy(price, account)

    if price > get_sma(d, SMA_PERIOD):
        return sell(holdings)

    if day >= LAST_SELL_DAY:
        return sell(holdings)

    # Otherwise, do nothing
    print 'b0'

run(*map(float, argv[1:]))

```

He will go all in when its cheap and sell it all once the price goes up...
> 1 votes

# Answer
## Lucky Number 6

EDIT: Oh ffs, I think me not converting the selling count to int was one of my problems, well here we go again.

Probably my last contribution, unless I'm bored at work and make something a bit more sophisticated, but I fell like the sophisticated bots already fill the niches.

This guy basically sells some of his shares every 6 rounds, because hey 6 is his lucky number.

```
from sys import argv
import random

share_price = int(argv[1])
share_count = int(argv[2])
balance = float(argv[3])
round = int(argv[4])
x = random.uniform(1,2)

if round == 1 or round == 1000:
    print("s"+str(share_count))
elif round % 6 == 0 and share_price >= 10:
    sell = int(share_count/x)
    print("s"+str(sell))
elif balance > share_price-1000:
    buy_count = int((balance+1000)/share_price)
    print("b"+str(buy_count))
else:
    print("b0")

```
> 1 votes

---
Tags: king-of-the-hill
---


title: Ordering a list

text:
# Question
Title: Ordering a list
# Summary

Given a list of integers, return the index each integer would end up at when sorted.

For example, if the list was `[0,8,-1,5,8]`, you should return `[1,3,0,2,4]`. Note that the two `8`s maintain their order relative to each other (the sort is stable).

Put another way: For each element in the list, return the number of elements in the list that are: Smaller than the chosen element OR (equal to the element AND appears before the chosen element)

Indexes must start with 0 (not 1)EDIT: given the large pushback, I'll allow 1-based indicies.

# Test cases:

```
0                -> 0
23               -> 0
2,3              -> 0,1
3,2              -> 1,0
2,2              -> 0,1
8,10,4,-1,-1,8   -> 3,5,2,0,1,4
0,1,2,3,4,5,6,7  -> 0,1,2,3,4,5,6,7
7,6,5,4,3,2,1,0  -> 7,6,5,4,3,2,1,0
4,4,0,1,1,2,0,1  -> 6,7,0,2,3,5,1,4
1,1,1,1,1,1,1,1  -> 0,1,2,3,4,5,6,7
1,1,1,1,1,1,1,0  -> 1,2,3,4,5,6,7,0

```

# Answer
# APL, 2 bytes

```
⍋⍋

```

The “grade up” built-in, applied twice. Works if indexing starts at 0, which isn’t the default for all flavors of APL. Try it here!

## Why does this work?

`⍋x` returns a *list of indices that would stably sort `x`*. For example:

```
    x ← 4 4 0 1 1 2 0 1
    ⍋x
2 6 3 4 7 5 0 1

```

because if you take element `2`, then `6`, then `3`… you get a stably sorted list:

```
    x[⍋x]
0 0 1 1 1 2 4 4

```

But the index list that answers this question is subtly different: first we want the index of the smallest element, then the second smallest, etc. — again, keeping the original order.

If we look at `⍋x`, though, we see it can give us this list easily: the *position* of a `0` in `⍋x` tells us where the smallest element would end up after sorting, and the *position* of a `1` in `⍋x` tells us where the second smallest element would end up, etc.

But we know `⍋x` contains exactly the numbers **\[0, 1… n−1\]**. If we grade it **again**, we’ll just get the index of `0` in `⍋x`, then the index of `1` in `⍋x`, etc., which is precisely what we’re interested in.

So the answer is `⍋⍋x`.
> 21 votes

# Answer
# Jelly, 2 bytes

```
ỤỤ

```

Grade up twice. 1-indexed. Try it online!
> 12 votes

# Answer
# JavaScript ES6, ~~87~~ ~~82~~ ~~79~~ ~~74~~ 70 bytes

```
(a,b={})=>a.map(l=>[...a].sort((a,b)=>a-b).indexOf(l)+(b[l]=b[l]+1|0))

```

Don't like using an object but it seems to be the shortest way to keep track of dupes

## Explanation

```
(a,b={})=>          `a` is input
                    `b` stores the occurrences of each number
  a.map(l =>        Loop over the array, `l` is item
  [...a]            Copy `a`
    .sort(...)       Sort in ascending numerical order
    .indexOf(l)      Index of input in that array
  +                 Add the following to account for dupes
   (b[l]=            set and return the item `l` in hashmap `b` to...
     b[l]+1           Increase the counter by one if it exists yet
     |0               default is zero
   )

```
> 6 votes

# Answer
# , ~~5~~ 2 bytes

```
<<

```

Grade up (`<`) twice. JohnE saved three bytes by pointing out tacit expressions exist in K! Super cool. Try it out.
> 6 votes

# Answer
## Haskell, ~~50~~ 48 bytes

```
import Data.List
m x=map snd$sort$zip x[0..]
m.m

```

Usage example: `m.m $ [4,4,0,1,1,2,0,1]`-\> `[6,7,0,2,3,5,1,4]`.

It's `map snd.sort.zip x [0..]` applied twice on the input, i.e pair each element e with it's index i (`(e,i)`), sort it remove the first elements. Repeat one time.

@Lynn came up with `m=map snd.sort.(`zip`[0..])` which has the same byte count.
> 5 votes

# Answer
# Python 2, ~~67~~ 60 bytes

```
def f(x):x=zip(x,range(len(x)));print map(sorted(x).index,x)

```

*Thanks to @xnor for golfing off 7 bytes!*

Test it on Ideone.
> 5 votes

# Answer
# MATL, ~~10~~ ~~9~~ 4 bytes

*4 Bytes saved thanks to @Luis*

```
&S&S

```

This solution uses 1-based indexing

**Try it Online**
> 4 votes

# Answer
# CJam, 15 bytes

```
{{eeWf%$1f=}2*}

```

Try it online!

## Explanation

```
{             }       Delimits an anonymous block.
 {         }2*        Run this block on the argument twice:
  ee                  Enumerate ([A B C] → [[0 A] [1 B] [2 C]])
    Wf%               Reverse each ([[A 0] [B 1] [C 2]])
       $              Sort the pairs lexicographically;
                        i.e. first by value, then by index.
        1f=           Keep the indices.

```
> 4 votes

# Answer
# Python 2, 67 bytes

```
a=input()
p=[]
for x in a:print sorted(a).index(x)+p.count(x);p+=x,

```

xnor saved two bytes.
> 4 votes

# Answer
## PowerShell v2+, 63 bytes

```
param($n)$n|%{($n|sort).IndexOf($_)+($n[0..$i++]-eq$_).count-1}

```

Takes input `$n`, pipes that through a loop over every element `|%{...}`. Each iteration, we `sort` `$n` and get the `IndexOf` our current element `$_`. This counts how many items are smaller than the current element. We add to that a slice of `$n`, that expands every loop iteration, of the elements that are equal to the current element `$_` and take the `.Count` of that. We then subtract `-1` so we don't count our current element, and that number is left on the pipeline. Output at the end is implicit.

### Examples

```
PS C:\Tools\Scripts\golfing> .\ordering-a-list.ps1 @(4,4,0,1,1,2,0,1)
6
7
0
2
3
5
1
4

PS C:\Tools\Scripts\golfing> .\ordering-a-list.ps1 @(8,10,4,-1,-1)
3
4
2
0
1

```
> 4 votes

# Answer
# J, 5 bytes

```
/:^:2

```

Grade up (`/:`) twice (`^:2`). 0-indexed.

To try it out, type `f =: /:^:2` and then `f 4 4 0 1 1 2 0 1` into tryj.tk.
> 4 votes

# Answer
## 05AB1E, 12 bytes

```
2FvyN‚}){€¦˜

```

**Explained**

```
2F            # 2 times do
  vyN‚})      # create list of [n, index]-pairs
        {€¦   # sort and remove first element leaving the index
           ˜  # deep flatten
              # implicit output

```

Try it online
> 4 votes

# Answer
## Haskell, 40 bytes

```
f l|z<-zip l[0..]=[sum[1|y<-z,y<x]|x<-z]

```

Annotate each element with its index, then map each element to the count of smaller elements, tiebreaking on index. No sorting.
> 4 votes

# Answer
# Pyth, ~~10~~ 9 bytes

**1 byte thanks to Jakube.**

```
xLo@QNUQU

```

Test suite.

There **must** be a shorter way...
> 3 votes

# Answer
# Julia, 17 bytes

```
~=sortperm;!x=~~x

```

1-indexed. Grade up (`sortperm`) twice. Try it here.

EDIT: Dennis saved *four* bytes by giving stuff operator-y names! Julia is weird.
> 3 votes

# Answer
## JavaScript (ES6), 52 bytes

```
a=>(g=a=>[...a.keys()].sort((n,m)=>a[n]-a[m]))(g(a))

```

Defines `g` as the grade function, which returns an array of indices to which all the elements in the sorted array would have come from in the original array. Unfortunately what we want is the indices which all the elements will go to. Fortunately this turns out to be the mapping from the grade back to the original list of indices, which itself can be considered to be the result of sorting the grade, thus allowing us to take the grade of the grade to achieve the desired result.
> 3 votes

# Answer
# Racket, 117 bytes

```
(λ(x)(build-list(length x)(λ(h)((λ(y)(+(count(λ(z)(< z y))x)(count(λ(z)(eq? z y))(take x h))))(list-ref x h)))))

```

I am eternally disappointed by the lack of a builtin for this.
> 2 votes

# Answer
# Ruby, ~~54~~ 53 bytes

Try it online

-1 byte from upgrading to @Downgoat's approach of using a hash to store values instead of counting the duplicates each time.

```
->a{b={};a.map{|e|a.sort.index(e)+b[e]=(b[e]||-1)+1}}

```
> 2 votes

# Answer
# Clojure, 83 bytes

```
(fn[a](nth(iterate #(->> %(map-indexed(comp vec rseq vector))sort(map second))a)2))

```

I create an anonymous function that grades the input array up and iterate it twice on the input. The first call will return the grade. The second call operates on the grade and returns the rank.
> 2 votes

# Answer
# Brachylog, 27 bytes

```
lL-M,?og:MjO,L~l.#d:Orz:ma?

```

Try it online! or verify all test cases.

### Explanation

This is a straightforward implementation of the following relationship: each integer of the output corresponding to an element of the input is the index of that element in the sorted input.

```
Example input: [3:2]

lL               L is the length of the input (e.g L=2)
  -M,            M = L-1 (e.g. M=1)
?o               Sort the input...
  g:MjO,         ... and create a list O with L copies of the input (e.g. O=[[2:3]:[2:3]])
L~l.             Output is a list of length L (e.g. [I:J])
    #d           All elements of the output must be distinct (e.g. I≠J)
      :Orz       Zip O with the output (e.g. [[[2:3]:I]:[[2:3]:J]])
          :ma?   Apply predicate Member with that zip as input and the input as output
                 (e.g. 3 is the Ith element of [2:3] and 2 is the Jth element of [2:3])

```
> 2 votes

# Answer
# Mathematica, 15 bytes

```
(o=Ordering)@*o

```
> 2 votes

# Answer
# Mathematica, 135 bytes

```
Function[{list}, SortBy[MapIndexed[Join[{#1}, #2]&, Sort@MapIndexed[Join[{#1}, #2] &, list]], #[[1, 2]] &][[All, 2]] - 1]

```
> 2 votes

# Answer
## Common Lisp, 117 bytes

```
(flet((i(Z)(mapcar'cdr(stable-sort(loop for e in Z for x from 0 collect(cons e x))'< :key'car))))(lambda(L)(i(i L))))

```

Apply a Schwartzian transform twice.

```
;; FIRST TIME

(0 8 -1 5 8)
;; add indexes
((0 . 0) (8 . 1) (-1 . 2) (5 . 3) (8 . 4))
;; sort by first element
((-1 . 2) (0 . 0) (5 . 3) (8 . 1) (8 . 4))
;; extract second elements
(2 0 3 1 4)

;; SECOND TIME

(2 0 3 1 4)
;; indexes
((2 . 0) (0 . 1) (3 . 2) (1 . 3) (4 . 4))
;; sort by first element
((0 . 1) (1 . 3) (2 . 0) (3 . 2) (4 . 4))
;; extract second elements
(1 3 0 2 4)

```

### Test

```
(let ((fn (flet((i(Z)(mapcar'cdr(stable-sort(loop for e in Z for x from 0 collect(cons e x))'< :key'car))))(lambda(L)(i(i L))))))
  (every
   (lambda (test expected)
     (equal (funcall fn test) expected))

   '((0) (23) (2 3) (3 2) (2 2) (8 10 4 -1 -1 8) (0 1 2 3 4 5 6 7)
     (7 6 5 4 3 2 1 0) (4 4 0 1 1 2 0 1) (1 1 1 1 1 1 1 1) (1 1 1 1 1 1 1 0))

   '((0) (0) (0 1) (1 0) (0 1) (3 5 2 0 1 4) (0 1 2 3 4 5 6 7) (7 6 5 4 3 2 1 0)
     (6 7 0 2 3 5 1 4) (0 1 2 3 4 5 6 7) (1 2 3 4 5 6 7 0))))
=> T

```
> 1 votes

# Answer
## GNU Core Utils, 39 33 bytes

```
nl|sort -nk2|nl|sort -nk2|cut -f1

```

Produces 1-based output. Add `-v0` after the second `nl` to get 0-based output. (+4 bytes)

Commands we are using:

* `nl` adds line numbers to each line of the input.
* `sort -n -k 2` sorts by column 2 numerically.
* `cut -f 1` takes the first Tab-delimited column, discarding the rest.

Additionally, the `-s` option can be passed to `sort` to request a stable sort, but we don't need it here. If two items are identical, `sort` will determine their order by falling back to the other columns, which in this case is the monotonically increasing output from `nl`. So the sort will be stable without needing to specify it, by virtue of the input.
> 1 votes

# Answer
## JavaScript (using external library) (105 bytes)

```
(n)=>{var a=_.From(n).Select((v,i)=>v+""+i);return a.Select(x=>a.OrderBy(y=>(y|0)).IndexOf(x)).ToArray()}

```

Link to lib: https://github.com/mvegh1/Enumerable Explanation of code: Create anonymous method that accepts a list of integers. \_.From creates an instance of the library that wraps an array with special methods. Select maps each item to a new item, by taking the "v"alue, parsing it to a string, then concatenating the "i"ndex of that item (this solves duplicate value case). Thats stored in variable 'a'. Then we return the result of the following: Map each item in 'a' to the index of that item in the sorted version of a (as integers), and cast back to a native JS array

Note that negative duplicate numbers seem to print in the reverse order. I'm not sure if that invalidates this solution? Technically 8,10,4,-1,-1,8 should be 3,5,2,0,1,4 according to OP but my code is printing 3,5,2,1,0,4 which I believe is still technically valid?
> 1 votes

# Answer
# Java ~~149~~ 140 bytes

```
public int[] indexArray(int[] index){
  int[] out=new int[index.length];
  for(int i=-1;++i<index.length;){
    for(int j=-1;++i<index.length;){
      if(index[i]==Arrays.sort(index.clone())[j]){
        out[i]=j;
      }
    }
  }
  return out;
}

```

Golfed

```
int[]a(int[]b){int l=b.length;int[]o=new int[l];for(int i=-1;++i<l;)for(int j=-1;++i<l;)if(b[i]==Arrays.sort(b.clone())[j])o[i]=j;return o;}

```

Thanks to @Kevin Cruissjen for shaving of 9 bytes.
> 1 votes

# Answer
# PHP, 88 bytes

```
unset($argv[0]);$a=$argv;sort($a);foreach($argv as$e)echo$h[$e]+++array_search($e,$a),_;

```

operates on command line arguments; prints 0-indexed, underscore-separated list. Run with `-nr`.

**breakdown**

```
unset($argv[0]);        // remove file name from arguments
$a=$argv;               // create copy
sort($a);               // sort copy (includes reindexing, starting with 0)
foreach($argv as$e)     // loop $e through original
    echo                    // print:
        $h[$e]++            // number of previous occurences
        +array_search($e,$a)// plus position in copy
        ,_                  // followed by underscore
    ;

```
> 1 votes

# Answer
# **MATLAB, 29 bytes**

```
function j=f(s);[~,j]=sort(s)

```

Most of MATLAB's sorting built-ins will return an optional second array containing the sorted indices. The `j=` could be removed if printing the indices is acceptable, rather than returning them.
> 0 votes

# Answer
# CJam, 19 bytes

```
_$:A;{A#_AWt:A;1+}%

```

Try it online!

Explanation:

```
_ duplicate array
 $ sort array
  :A store in variable A
    ; discard top item in stack
     {A#_AWt:A;1+} block that finds index of item and removes it from sorted array to prevent duplicates
      % map block onto every item in array

```
> 0 votes

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


title: Minimum insertions to make palindrome

text:
# Question
Title: Minimum insertions to make palindrome
Today you will be doing another palindrome challenge!

So, your task today is to take a string, and determine the minimum amount of letters required to insert to turn it into a palindrome.

For example, let's take the string `fishes`.

In this, case the best way would be to add `h if`, so the result would be 3.

```
fishe s
     h if
---------
fishehsif

```

Now let's try with `codegolf`. Since there is a repeated `o`, we can just do:

```
  codeg  o lf
fl     ed c
-------------
flcodegedoclf

```

to get a result of 5.

## Test cases

```
ppcg -> 2
codegolf -> 5
palindrome -> 9
stackexchange -> 8
programmingpuzzlesandcodegolf -> 20

```

# Answer
> 3 votes
# Python, 112 bytes

```
d=lambda x,l,h:0if h<l else d(x,l+1,h-1)if x[l]==x[h]else-~min(d(x,l+1,h),d(x,l,h-1));e=lambda x:d(x,0,len(x)-1)

```

Very inefficient.

Try it online! You have to wait a minute for the last case to finish.

Call with `e(<string>, 0, <length of string - 1>)`, like e("fishes", 0, 5)\`.

Ungolfed (sort of) with explanation:

```
def minInsert(x, l, h):                # Declare func, arugments for x, l, h       # d=lambda x,l,h:
  if l >= h:                           # If l is the same or past h                #                 if h<l
    return 0                           #     then return 0                         #                0
  elif x[l] == x[h]:                   # If first and last character are the same  #                        else             if x[l]==x[h]
    return minInsert(x, l + 1, h - 1)  #     then return the min w/o first & last  #                             d(x,l+1,h-1)
  else:                                # If not, we shave off a character          #                                                      else
    a = minInsert(x, l, h - 1)         #     (last one)                            #                                                                d(x,l+1,h)
    b = minInsert(x, l + 1, h)         #     (first one)                           #                                                                           d(x,l,h-1)
    return min(a, b) + 1               #     and add one for the char we took off  #                                                          -~min(          ,          )

```

# Answer
> 3 votes
## Pyth, 10 bytes

test suite.

```
l.-Qe@y_Qy

         y   All subsequences of the input (implicit), sorted by length
      y_Q    All subsequences of the reversed input, sorted by length
     @       Their setwise intersection: the common subsequences
    e        Last element: the longest common subsequence
 .-Q         Remove it bagwise from the input: the letters not in this LCS
l            The length of that

```

There's a few equivalent characterizations of the value we're after:

* The fewest insertions needed to make a palindrome
* The fewest deletions needed to make a palindrome
* Half the number of delete or insert operations needed to transform the string to its reverse
* The length of the input with its longest palindromic subsequence removed
* The length of the input, removing the longest common subsequence between it and its reverse. (The code uses this one.)

The common idea is the "skeleton" of letters in the input that are matched with letters of the input in the final product.

```
  codeg  o lf
   *  *  *
fl o  gedoc

flcodegedoclf

```

This skeleton is always a palindrome, with letters matching to their reversed counterparts. Each non-skeleton letters is unmatched and must have its counterpart inserted.

A same-length alternative instead uses the fourth condition, the length of the input minus the length of its longest palindromic subsequence

```
l.-Qef_ITy

```

Link to test suite.

The part that's different is

```
f_ITy

    y   All subsequences of the input (implicit), sorted by length.
f       Filtered on:
 _IT     being invariant under reversal, i.e. a palindrome

```

For both, instead of removing the palindromic subsequence from the input and taking the length, we could instead subtract its length from the length of the input. Either one costs 4 bytes: `-lQl` vs `l.-Q`.

# Answer
> 2 votes
# 05AB1E, 11 bytes

Uses CP-1252 encoding.

```
ÂæsæÃ¤g¹g-Ä

```

Try it online! or as a Test suite

**Explanation**

```
              # implicit input
Â             # push a reversed copy
 æ            # compute powerset of the reversed string
  sæ          # compute powerset of the string
    Ã¤g       # get length of the longest common subset
      ¹g-     # subtract the length of the original string
         Ä    # take absolute value

```

# Answer
> 2 votes
# Brachylog, 9 bytes

```
⊆P↔P;?lᵐ-

```

Try it online!

This challenge really needed a Brachylog v2 answer, as insertion palindromization is so intuitive in that language.

### Explanation

`⊆P↔P` really is what does palindromization by insertion (see this example)

```
⊆P           P is an ordered superset of the input
 P↔P         P reversed is P (i.e. P is a palindrome)
   P;?lᵐ     Compute the length of both P and the input
        -    Subtraction

```

# Answer
> 1 votes
# C, ~~89~~ 121 bytes

```
#define g(a) f(a,a+strlen(a)-1)
f(char*a,char*b){return a>=b?0:*a-*b?f(a+1,b)<f(a,b-1)?f(++a,b)+1:f(a,--b)+1:f(++a,--b);}

```

Shameless port of Oliver's answer, could not think of any shorter solution.

`g` calls `f` with the pointer to the first and the last char of a string (the last char is part of the string, not the `'\0'`). Gets even more inefficient because `f` is called two times for the `min` case.

Ungolfed:

```
f(char*a,char*b){
 return a>=b ? 0 :
   *a-*b ?    //if the pointed chars are not the same
     f(a+1,b)<f(a,b-1) ? f(a+1,b)+1 : f(a,b-1)+1    //min(f..,f..)+1
   : f(a+1,b-1);  //if they were the same, make it more narrow
 }

```

Usage:

```
int main(){
 char s[]="palindrome";
 printf("%d\n",g(s));
}

```

# Answer
> 1 votes
# Brachylog v1, 13 bytes

```
,IrIs?:I:lar-

```

Try it online!

You can check the palindromes it finds with this code.

### Explanation

I'm almost surprised this even works, seeing how ridiculously simple it is.

```
,IrI             I reversed is I (i.e. I is a palindrome)
   Is?           The Input is an ordered subset of I
     ?:I:la      The list [length(Input), length(I)]
           r-    Output = length(I) - length(Input)

```

This is guaranteed to find the smallest palindrome because `IrI` will generate strings of increasing length when backtracking, starting from the empty string.

This is not efficient enough to compute the last test case on TIO, because of the use of `s - Ordered subset`.

# Answer
> 0 votes
## Batch, ~~234~~ 232 bytes

```
@echo off
set n=99
call:l 0 %1
echo %n%
exit/b
:g
set/am=%1
if %m% lss %n% set/an=m
exit/b
:l
if "%2"=="" goto g
set s=%2
if %s:~,1%==%s:~-1% call:l %1 %s:~1,-1%&exit/b
call:l %1+1 %s:~1%
set s=%2
call:l %1+1 %s:~,-1%

```

Works by recursively trying to insert nonmatching characters at both ends, so very slow (I didn't try the last test case). Recursion limits mean that this only works for a limited string length anyway, so the `99` is somewhat arbitrary. I have to use `call` parameters as local variables as I couldn't get `setlocal` to work for me, which means that `%1` parameter to the `:l` subroutine is an expression that evaluates to the number of insertions done so far.

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