title: We're all unique in our own way

text:
# Question
Title: We're all unique in our own way
This is an challenge where every part of your answer should aim to be unique from every other answer.

This question will work in the following way:

* I will post the first answer. The next answer will stem from that, and all other answers will originate from it.
* In this answer I will include a program and specify three things:
    + The language the program is written in
    + The integer it outputs
    + The bytes the next program must use
* The next user will then write an answer, and specify the same three things - the language they used, the integer they output and the bytes the next program must use
* And so on, until the chain ends.

Each answer will do the following:

* It will include a program, written in a language that hasn't been used by any previous answer.
* The program outputs an integer, through one of our standard I/O formats, that no previous answer in the chain has outputted before. This integer must be deterministic and consistent between executions, and may be positive, negative or \\$0\\$.
* It will take either no input, or an empty input if necessary, and will output nothing more than the integer to a standard output method (STDOUT, function return, Javascript's `alert` etc.)
* It only uses the bytes allowed to it by the previous answer. It may use each byte as many times as it likes, but **each byte must be used at least once**.
* The answer will specify a set of bytes (containing no duplicates) that the next answer must use. This set of bytes may not have been used by any previous answer, and can be any subset of the integers between \\$0\\$ and \\$255\\$. There must be a minimum of 1 and a maximum of 256 bytes in this subset, and the number of bytes must be unique of all existing answers (i.e. if one answer allows the next to use 120 bytes, no other answer may allow 120 bytes).

Through this, each new answer will determine how difficult (or easy) the next answer is; only allowing a small subset of bytes will make it substantially more difficult than if allowing a larger set. "Bytes" means that you may use languages with non-UTF-8 encodings, by simply taking the characters those bytes represent in that code page.

For the sake of fairness, the first answer (which I'll post) will have all 256 bytes available to it, so that the answers truly are unique in all the specified ways.

## Scoring

Your score is the number of answers you have in the chain, with a higher score being better.

## Formatting

Please format your answer in the following way:

```
# [N]. [Language], [# of bytes available] available bytes

    [program]

This outputs [output]

This uses the characters [characters/bytes], allowed by [previous answer](link)

The next answer may use the following bytes:

    [list of bytes]

```

## Rules

* You must wait an hour between posting two answers
* You may not post two answers in a row
* So long as they're unique, the language, integer and bytes are up to your choice
* You are under no obligation to golf your code
* You may submit either a full program or function
* Different versions of languages (e.g Python 2 and Python 3) are **not** considered separate languages. As a general rule, if the only way the language names differ is by a version number, or if the languages are usually thought of as versions of each other, they are considered the same language.
* You may use any language that wasn't specifically invented to answer this challenge
* The chain ends when 14 days pass with no new answers being posted or after 256 answers have been posted (as no new byte sets will be available).

Good luck!

# Answer
# 5. Retina 0.8.2 `-m`, 8 available bytes

The code is given as three separate files. Here are their hexdumps:

```
00000000: 002a 0f2a 062a 092a 042a 142a            .*.*.*.*.*.*
00000000: 4545 4545 4545                           EEEEEE
00000000: 45                                       E

```

This outputs `6`. Try it online!

The first file uses bytes 0, 15, 6, 9, 4, 20, and 42, and the other two files consist entirely of `E` (byte 69), covering the list specified by the previous answer.

---

Normally, Retina takes patterns and replacements in a single file separated by newlines, but we don't have newlines available. Fortunately, Retina 0.8.2 still makes available the language's original multi-file code format.\* This program has two stages, a replacement stage and a count stage:

* Find all regex matches of `_*_*_*_*_*_*` in the input, where `_` represents the various unprintable characters. Since the input is empty, this matches once. Replace that match with `EEEEEE`.
* In the resulting string, count the number of matches of `E` (six).

* IIRC, Retina was originally designed this way to take advantage of a PPCG scoring loophole. Now I'm using it to take advantage of a different kind of loophole. Seems appropriate.

---

The next answer may use the 54 bytes whose codepoints are prime numbers:

```
2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251

```
> 7 votes

# Answer
# 2. Python 3, 94 available bytes

```
values = {(k,): ord(k) for k in "ABCDEFGHIJKLMNOPQRSTUVWXYZ@"};combined = [~values[g.upper(),] + 1 // 2 - 3 * 4 & 5 % 6 > 0 < 7 ^ 8 for g in 'hjqwxyz'];_ = sum(combined) | 7 + 9;_ += ord("$") + ord("\n");print(_ + ord("`"))#!?

```

Try it online!

Outputs `163`

I could've just printed a number and stuck everything else in a comment, but I thought I'd add some unnecessary fluff to it to make it more interesting :P

This uses all printable ASCII bytes as required by the previous answer. Python is a unique language, and 163 is a unique number.

---

The next answer must contain all bytes *except* the printable ASCII characters; that is, codepoints 0 through 31 and 127 through 255.
> 6 votes

# Answer
# 3. x86 machine code (MS-DOS .COM), 161 available bytes

```
B8 19 0E 04 17 BB 01 00 CD 10 C3
02 03 05 06 07 08 09 0A 0B 0C 0D 0F
11 12 13 14 15 16 18 1A 1B 1C 1D 1E 1F
80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F
90 91 92 93 94 95 96 97 98 99 9A 9B 9C 9D 9E 9F
A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 AA AB AC AD AE AF
B0 B1 B2 B3 B4 B5 B6 B7 B9 BA BC BD BE BF
C0 C1 C2 C4 C5 C6 C7 C8 C9 CA CB CC CE CF
D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF
E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 EA EB EC ED EE EF
F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB FC FD FE FF

```

Relevant code (the rest is filler):

```
B8 19 0E    MOV AX,0E19H
04 17       ADD AL,17H
BB 01 00    MOV BX,0001H
CD 10       INT 10H
C3          RET

```

The DOS functions that print use printable characters (INT 21H and INT 29H), so I use INT 10H instead. This program outputs `0`.

---

The next answer must use every codepoint except for the digits `0` through `9` (48 through 57 inclusive).
> 6 votes

# Answer
# 21. Incident, 9 available bytes

Decoded as codepage 437:

```
£ñ¥££₧Ç£¢£%₧£%¢£ñ¥ñÇ¢£$¥ñ£¥ñ£¥%Ç₧ñ$¥%ñƒ%ñ¢Ç$₧%Ç¢%ñƒñ$ƒñ$ƒ%ÇƒñÇ₧ñ%₧ññƒ%%₧%%₧Ç$¥%%ƒ%£ƒ%£¢Ç$¢ñ%¥%£₧ññƒññ¥ñ%¢ñ£¥£$¥£$¥ñÇ¥£%¥Ç£¢Ç£¢££ƒ££¥£ñ¢Ç%ƒÇ%¢Ç%¢ÇñƒÇñ¥Çñ

```

or as an xxd reversible hexdump:

```
00000000: 9ca4 9d9c 9c9e 809c 9b9c 259e 9c25 9b9c  ..........%..%..
00000010: a49d a480 9b9c 249d a49c 9da4 9c9d 2580  ......$.......%.
00000020: 9ea4 249d 25a4 9f25 a49b 8024 9e25 809b  ..$.%..%...$.%..
00000030: 25a4 9fa4 249f a424 9f25 809f a480 9ea4  %...$..$.%......
00000040: 259e a4a4 9f25 259e 2525 9e80 249d 2525  %....%%.%%..$.%%
00000050: 9f25 9c9f 259c 9b80 249b a425 9d25 9c9e  .%..%...$..%.%..
00000060: a4a4 9fa4 a49d a425 9ba4 9c9d 9c24 9d9c  .......%.....$..
00000070: 249d a480 9d9c 259d 809c 9b80 9c9b 9c9c  $.....%.........
00000080: 9f9c 9c9d 9ca4 9b80 259f 8025 9b80 259b  ........%..%..%.
00000090: 80a4 9f80 a49d 80a4                      ........

```

Try it online!

Prints `33`. This is a) because 33 is by far the easiest two-digit number to print in Incident, b) because I already had a program to print 33 handy, and all I needed to do was try to fit it into the given set of available bytes.

This program was harder to write than I expected (given that I'd already written it); 9 bytes is not a lot (the more the better with Incident, although it can work with very restricted sets if necessary), and working with character encoding issues is annoying. I started working with UTF-8, planning to change to Latin-1 later, but a) the program parses differently in UTF-8 (Incident looks at the raw bytes, so the encoding matters), b) I couldn't figure out what encoding @Razetime's currency symbols were in (euro isn't normally at 0x9C), and c) TIO apparently feeds UTF-8 to Incident so the program didn't work there directly, and I had to write my own wrapper in the TIO link above. A much more fruitful technique was to work with ASCII (`abcde,.:;`), and `tr` it into the set of available bytes at the end (Incident is `tr`-invariant; consistently replacing one codepoint in the program with another unused codepoint makes no difference to the program's behaviour).

## Explanation

### Parsing the program

In the rest of this explanation, I'm going to represent the program in a more readable, equivalent, ASCII form (which is just a consistent replacement of the 9 available bytes):

```
cb,cc:dc.ca:ca.cb,bd.ce,bc,bc,ad:be,ab;ab.de:ad.ab;be;be;ad;
bd:ba:bb;aa:aa:de,aa;ac;ac.de.ba,ac:bb;bb,ba.bc,ce,ce,bd,ca,
dc.dc.cc;cc,cb.da;da.da.db;db,db

```

This program uses 17 different commands. The original program represented each command as a single byte:

```
lm3kklijhhdebbodbeedifgaaoaccofcggfhjjik33mml111222

```

but this uses 17 different bytes, and we only have 9 available. So instead, each of the commands is represented as a pair of letters from `abcde` (i.e. the first five our our currency symbols). This would lead to a huge number of accidental mis-parses if I just wrote it out directly (in fact, Incident fails to parse a single token!), so additional characters drawn from `.,:;` (i.e. the last four of our currency symbols) were inserted in between them in order to ensure that it recognised the correct pairs of bytes as tokens. (As a reminder, Incident tokenises the source by treating each substring of bytes that occurs exactly three times as a token, with a few adjustments for overlapping tokens and tokens that are subsets of each other.)

To translate the original program into the form with command pairs separated by additional characters, I used the Jelly program

```
O%38+10%25b€5ị“abcde”j”.

```

I then used simulated annealing to choose appropriate separating characters to make sure that none of the tokens ended up overlapping (usually these characters weren't part of the token, but in a few cases they became part of an adjacent token, without changing the behaviour of the program).

### Program behaviour

```
cb,                Call subroutine cb (which prints a 3)
cc:                Goto label cccc (used to call cb a second time)
dc.                Goto label dcdc (apparently unused?)

ca:ca.             Jump target
cb,                Entry/exit point for subroutine cb (which prints a 3)
bd.                Call subroutine bd (which prints half a 3)
ce,                Goto label cece

bc,bc,             Jump target
ad:                Call subroutine ad (which prints a 0 bit)
be,                Goto label bebe

ab;ab.             Jump target
de:                Output a 0 bit (and jump to the centre of the program)
ad.                Entry/exit point for subroutine ad (which prints a 0 bit)
ab;                Goto label abab

be;be;             Jump target
ad;                Call subroutine ad (which prints a 0 bit)
bd:                Entry/exit point for subroutine bd (which prints half a 3)
ba:                Call subroutine ba (which prints a 1 bit)
bb;                Goto label bbbb

                   CENTRE OF THE PROGRAM:
aa:aa:de,aa;       After outputting a bit, jump back to where you were

ac;ac.             Jump target
de.                Output a 1 bit (and jump to the centre of the program)
ba,                Entry/exit point for subroutine ba (which prints a 1 bit)
ac:                Goto label acac

bb;bb,             Jump target
ba.                Call subroutine ba (which prints a 1 bit)
bc,                Goto label bcbc

ce,ce,             Jump target
bd,                Call subroutine bd (which prints half a 3)
ca,                Goto label caca (i.e. return from subroutine cb)

dc.dc.             Jump target
cc;cc,             Jump target

cb.                Call subroutine cb (which prints a 3)

da;da.da.          No-op to ensure "de" is in the centre of the program
db;db,db           No-op to ensure "de" is in the centre of the program

```

This is pretty straightforward as programs go: we define a subroutine `cb` to print `3`, and it does so in terms of a subroutine `bd` which prints half a `3` (Incident prints a bit at a time, and the bit pattern of `3` is `11001100` in Incident's bit order, so to print half a `3` you just need to print `1100`). Unfortunately, the behaviour of an Incident command (except for unconditional jumps, which go from `x` to `xx`) depends on its position in the program, so a huge number of jumps are required in order to make the program's control flow run all the commands in the right order. The sequence in which the commands that actually do something must be given is fairly fixed (e.g. a subroutine must be called from exactly 2 locations, with the first location before it is defined, and the second location after it is defined; and I/O behaviour depends on which command is in the centre of the program), so because we can't reorder the commands to say which order we want to run them in, we reorder the control flow instead, putting jumps just before and after pretty much all of them.

I'm not completely sure why I put two different jump labels `cccc` and `dcdc` back when I originally wrote this program, but Incident is sufficiently hard to write that I'm not sure I want to change things now. (Perhaps it was in an attempt to get the centre of the program into the right place.)

## Restriction

Time for a change of pace, given how unreadable the programs in this answer are. The next answer must use all 26 lowercase ASCII letters, plus the ASCII space character: `abcdefghijklmnopqrstuvwxyz` , i.e. 0x61-0x7a, plus 0x20.

(Please try to keep the restrictions fairly reasonable from now on; one of the inspirations behind Incident was "escaping from tricky situations in puzzles", but now that it's been used, we won't have our get-out-of-jail card to free us from such situations if they happen again.)
> 6 votes

# Answer
# 4. Vyxal, 245 available bytes

```
#λ¬∧⟑∨⟇÷«»°․⍎½∆øÏÔÇæʀʁɾɽÞƈ∞⫙ß⎝⎠ !"#$%&'()*+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_abcdefghijklmnopqrstuvwxyz{|}~⎡⎣⨥⨪∺❝ð£¥§¦¡∂ÐřŠč√∖ẊȦȮḊĖẸṙ∑Ṡİ•Ĥ⟨⟩ƛıĲĳĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňŉŊŋŌōŎŏŐőŒœŔŕŖŗŘŚśŜŝŞşšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƊƋƌƍƎ¢≈Ωªº

ĳ

```

This outputs `10`.

This uses every character except in the range `[48, 57]`.

After everything is ignored in the comment, simply push `10` to the stack and auto print.

---

The next answer may only have bytes in this list: `[69, 42, 0, 15, 6, 9, 4, 20]`
> 5 votes

# Answer
# 7. Charcoal, 16 available bytes

```
11»；∧”″⟲⌊$@Qdy✂Ｄα

```

Try it online! Outputs the integer `11`, after which the `»` ends the block (program), ignoring the remaining 14 bytes.

---

The next answer must not use any bytes which code for ISO-8859-1 characters with an alphanumeric appearance i.e. `0-9`, `A-Z`, `_`, `a-z`, but also `¢¥©ª®°²³µ¹º¼½¾`, `À-Ö`, `Ø-ö`, or `ø-ÿ`.
> 4 votes

# Answer
# 12. 05AB1E, 62 available bytes

```
5oCsnqaDZbOSF10u69pWEjBAf2KUMkLIgePzG8dTyHwNX3lRtmir7cQxhJ4YvV

```

Try it online!

Outputs `64`.

I got this by scrambling the bytes until it eventually gave me a nice number.

---

The next answer must use the byte set of powers of two and three: `[1, 2, 3, 4, 8, 9, 16, 27, 32, 64, 81, 128]` (12).
> 4 votes

# Answer
# 1. Whispers v2, 256 available bytes

```
> 1
>> Output 1

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ

```

Try it online!

Outputs `1`

This uses all 256 bytes (from `0x00` to `0xFF`).

The next answer must use the printable ASCII bytes (`0x20` to `0x7E`,  to `~`, \\$32\\$ to \\$126\\$ etc.). Note that this *does not* include newlines.

---

## How it works

Only the first two lines are actually executed. Every other line doesn't begin with `>` so it's ignored. From there, it's kinda simple. The first line returns `1` and the second outputs it.
> 3 votes

# Answer
# 6. Jelly, 54 available bytes

```
¦¬£¿Æ×Œçøþ%)/;=CGISYaegkmq³⁹⁻ⱮƤṣɗɲʂḌṂḂ¤ḊḢĿạẉẓḋOṁỌȯ»+¶5

```

Try it online!

This outputs `5`. Why? Because  counts as a newline in Jelly (like, `\n` and  are the exact same thing), and only the last link (line) is run in Jelly, everything except the `5` is ignored. Actually, moving the  to other places works too, because Jelly's really forgiving and just puts 0 through the chain of evaluation a bunch and since there's a number, I'm able to output something besides 0.

---

The next answer must use the 16 bytes with square codepoints:

`0,1,4,9,16,25,36,49,64,81,100,121,144,169,196,225`
> 3 votes

# Answer
# 8. !@#$%^&\*()\_+, 184 available bytes

```
(?@)

 !"#$%&'*+,-./:;<=>[\]^`{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡£¤¦§¨«¬®¯±´¶·¸»¿×÷

```

*The code outputs the integer `34`, the ASCII value of the character `"`.*

This uses the characters specified by previous answer.

Try it online!

## How does it work?

The starting `(?@)` indicates that the code will run `?@` while the stack is not zero. Since the stack is zero at the start, the code does not excecute. Both of these characters print some sort of thing, which makes it necessary to put them in brackets.

The code then pushes a few codepoints, including the codepoint of `"`, which is `34`. `#` prints out that number.

Since there are no more printing commands, the rest of the code can be thought as filler.

## Next set of bytes!

**The next answer should use all characters with an odd ASCII value, or:**

```
!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}

```
> 3 votes

# Answer
# 9. Bash, 64 available bytes

Prints -13579.

```
/us?/???/ec?o	-13579	#
!%')+;=ACEGIKMOQSUWY[]_agikmqwy{}

```

Hexdump for clarification:

```
00000000: 2f75 733f 2f3f 3f3f 2f65 633f 6f09 2d31  /us?/???/ec?o.-1
00000010: 3335 3739 0923 0103 0507 0b0d 0f11 1315  3579.#..........
00000020: 1719 1b1d 1f21 2527 292b 3b3d 4143 4547  .....!%')+;=ACEG
00000030: 494b 4d4f 5153 5557 595b 5d5f 6167 696b  IKMOQSUWY[]_agik
00000040: 6d71 7779 7b7d 7f                        mqwy{}.

```

Try it online!

`/us?/???/ec?o` is a *glob*, which searches for a filename matching that pattern (where `?` can be any one character). The file this finds is `/usr/bin/echo` which is very useful for printing integers.

Next is a tab character, separating the executable from its argument, which is `-13579` (I thought I'd shake things up with a negative number!)

Then another tab character and a `#`, starting a comment. Then are all the remaining odd ASCII bytes (from 0x01 to 0x7F, excluding the ones already used), which Bash dutifully ignores. (although with a little bit of stderr moaning, at least on TIO's version)

---

Next arbitrary byte set is all bytes **except**:

* bytes greater than or equal to 0x9A
* ASCII lowercase letters
* ASCII uppercase letters C, T and S
* ASCII digits
* ASCII space, new line feed, and horizontal tab
* ASCII closing parenthesis, closing square bracket, and closing curly brace

This makes a total of 107 available bytes?
> 3 votes

# Answer
# 11. Lenguage, 2 available bytes

\[The program is too long to be displayed\]

Big thanks to the bois who made this Lenguage!

The program prints `2` by the way.

The program is basically a whopping `73788735513442661331` tabs and an acknowledgement. (Yes, an acknowledgement. It is in a program simply for it to follow the byte set of allowed by the previous answer)

---

The next program should use only and all alphanumeric characters upto `0x5A`, or:

`0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`
> 3 votes

# Answer
# 15. Neim, 1 available byte

```
A

```

Try it online!

Outputs `42`. I don't know why. I've never used this language before. I was literally just clicking through random languages on TIO and this happened to work...

It seems that repeating `A` just repeats the `42`, so I could've done an arbitrarily large integer in the form `42424242...`

---

The next answer should use the byte set `[48, 49, 50]` (characters `['0', '1', '2']`).
> 3 votes

# Answer
# 17. Whitespace, 32 available bytes

The available bytes were `0x01` through `0x20` inclusive.

```

```

Try it online!

STN translation:

```
SSSTSSTSSS[50 copies of T]N # Push a big number
TN STN # Print as integer? Not quite sure, I just copied this part from esolangs
NN # Terminate the program
[Garbage from 0x01 to 0x20]

```

Prints `82190693199511551`. As the code is easy enough to output larger numbers, I figured I'd output something large enough so no one needs to bother with output clashes. So I made a working program and padded the number literal with tabs until the program became exactly 100 bytes :)

---

Next answer: Use only `[]{}`, which is `0x5b 0x5d 0x7b 0x7d` in hex.
> 3 votes

# Answer
# 10. Keg, 107 avaliable bytes

```
E[``F;.#{(`Ï§∑¿∂•ɧ÷Ë≬ƒß‘“„«®©ëλº√₳¬≤Š≠≥Ėπ!"#$%&'*+,-./:<=>?@ABDEFGHIJKLMNOPQRUVWXYZ\\^_	⊂½‡™±¦→←↶↷✏█↗↘□²ⁿ║ṡ⟰⟱⟷ℤ

```

Try it online!

This outputs `69` (HA!)

Now, you're gonna say "but Lyxal... the answer said YOU CAN'T HAVE ASCII NEWLINE/TAB!! AND YET YOU STILL HAVE THOSE CHARACTERS!!!"

Normally, you'd be right to say that this is invalid, but this time you're wrong. Keg's *special*. We play with a SBCS... A SBCS which just happens to have the newline and tab in a different spot than they usually are.

Codepage

Don't judge my Poor Design Choices™

---

The next answer can only use the bytes with values `6` and `9` (haha funny number)
> 2 votes

# Answer
# 16. Bitwise Cyclic Tag But Way Worse, 3 available bytes

```
111011112000000

```

This outputs `7`. Try it online!

---

I found a language that used `0`, `1`, and `2`, took an educated guess at what an "output one character" program would look like, and tweaked it until it was a digit. ~~I'm... not really sure how this works.~~

After some investigation, it turns out that BCTBWW doesn't actually work like Bitwise Cyclic Tag (maybe that's why it's way worse). When BCT encounters an instruction like `10`, it conditionally enqueues a `0` to the data-string and moves to the next instruction after the `0`. BCTBWW uses the same enqueuing logic, but it doesn't skip over the bit that was enqueued--it executes the `0` as the next instruction. Here's how the above program works:

```
Instruction        Data-string   Comment
                   1             With empty input, data-string starts as 1
11                 11
 11                111
  10               1110
   0                110
    11              1101
     11             11011
      11            110111
       12           110111       12 is a no-op
        2           110111       2 converts the data-string to bytes and outputs it
         0           10111
          0           0111
           0           111
            0           11
             0           1
              0                  Data-string is empty, program halts

```

The output is thus the single byte `0b110111` = `0x37`, which is the digit `7`.

---

The next answer must use the byte set `0x01` through `0x20` (1 through 32, inclusive).
> 2 votes

# Answer
# 18. {} (Level 8), 4 available bytes

```
{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{{}{}{}{}{}}[]

```

`{} (Level 8)` is a brainfuck clone.

According to the esolangs wiki page, `{}` evaluates to `+` in brainfuck, and `{{}{}{}{}{}}` evaluates to `.`.

Here's the same program, translated to brainfuck: Try it online!

This program prints `9`.

`[]` does nothing in this program, since it isn't a command.

The next program must use the following 13 bytes taken from this thread: `[2,5,8,10,22,25,31,40,77,80,96,101,137]`

Or, as hex:

`02 05 08 0A 16 19 1F 28 4D 50 60 65 89` (courtesy of PkmnQ)
> 2 votes

# Answer
# 19. Beatnik, 13 available bytes

```
Pee
MeMeMeMeMeMeMeMeeMeMeMeMe
Pee
MeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeP
MeeeP
MeeeP
eeeeeeeeeeeeeeeee
(`‰

```

Yes, I deliberately used the words "Pee", "Meme", "Meep", and "E".

This (abominable) program outputs the integer `21`.

Try it online!

---

## Next byte set...

Only use all of the non-alphabetic and non-whitespace characters which can be typed while pressing the shift key on a standard QWERTY keyboard:

`!"#$%&()*+:<>?@^_{|}~`
> 2 votes

# Answer
# 20. MAWP v1.1, 21 available bytes

```
!!!!!!::::::"#$%&()*+<>?@^_{|}~

```

Try it!

Prints `111111`,

Using the bytes `!"#$%&()*+:<>?@^_{|}~`.

The first 12 bytes do the hard work(cloning the existing 1 and printing it), then the rest do a whole lot of nothing. `()` does othing since nothing is on the stack, and the rest fo the characters don't change anything since `:` needs to be there for outputting their result.

## Restriction

The next answer must only use the currency symbols shown here, and %:

`¤£€$¢¥₧ƒ%`

`[37,164,156,128,36,155,157,158,159]`

`[0x25,0xa4,0x9c,0x80,0x24,0x9b,0x9d,0x9e,0x9f]`

or

`0x24-0x25, 0x80, 0x9b-0x9f, 0xa4` (from Bubbler)
> 2 votes

# Answer
# 22. StupidStacklanguage, 27 available bytes

```
abaacdaiiiiiiiqmiiiiiiiqqqqfffffeghjklmnopqrstuvwxyz

```

Try it online!

This prints `88888`.

This uses `abcdefghijklmnopqrstuvwxyz` (Printable ascii alphabets and space) from the previous answer.

The next answer must use the following bytes which are palindromes in base 2:

`!-3?AIU]ckw¥½ÃÛçÿ`

`[33,45,51,63,65,73,85,93,99,107,119,127,165,189,195,219,231,255]`

`[0x21,0x2d,0x33,0x3f,0x41,0x49,0x55,0x5d,0x63,0x6b,0x77,0x7f,0xa5,0xbd,0xc3,0xdb,0xe7,0xff]`

---

## How it works:

`ab` pushes a 0 and pops it.

`aacd` pushes two 0's and subtracts them and decrements the result.

`aiiiiiii` pushes a 0 and adds 7 to it.

`qm` squares it.

`iiiiiii` adds 7 to that.

`qqqq` duplicates it 4 times.

`fffff` then displays that as printable ascii.

`e` takes in input. Since there is no input, the program errors and ends execution, and the rest of the program does nothing.
> 2 votes

# Answer
# 23. Trigger, 17 available bytes

```
333!333-333?AIU]ckw¥½ÃÛçÿ

```

Try it online!

Outputs `333`.

Not sure if these are the correct characters to show, but even if they aren't, the language spec says it doesn't matter.

The next answer must use all bytes except:

* Alphanumeric characters `0x30 to 0x39, 0x41 to 0x5A, 0x61 to 0x7A`
* The null byte `0x00`
* Brackets `0x40, 0x41, 0x5B, 0x5D, 0x7B, 0x7D`
* Mathematical operators `0x25, 0x42, 0x43, 0x45, 0x47`
* Bitwise operators `0x21, 0x26, 0x5E, 0x7C`
* Whitespace `0x09, 0x0A, 0x0C, 0x0D, 0x20`
* Common punctuation `0x22, 0x27, 0x2C, 0x2E, 0x3F`

Which leaves 167 bytes.
> 2 votes

# Answer
# 13. Poetic, 12 available bytes

```
QQQQQQQQQQQQQQQQQQQQQQQQ    QQQQQQQQQQQ@QQQQQ€QQQ QQQQQ QQQ QQQQQ QQQ QQQQQ QQQ QQQQQ QQQ QQQQQ QQQ QQ QQQQQQQ QQQQQQQQQQ

```

This code outputs the number `4`!

Uses the `Q`'s and `@`'s and other stuff specified by the previous answer.

---

## Next byte set...

Only use every accented ASCII alphabets and all the accents or diacritics in your code, or:

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

```

*Note: The degree (`°`) symbol has to be used as a diacritic*
> 1 votes

# Answer
# 14. , 68 available bytes

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

```

This outputs `65`. Try it online!

---

V is the perfect language for using accented letters.

* `Á` inserts the character that follows it into the buffer. We use this command over and over to insert 65 out of our 68 characters.
* `Ø` counts matches of the following regex and replaces the buffer with the count.
* `Ä` is a compressed regex that stands for `\D`. Thus, in the characters we inserted previously, we count the ones that are not digits--which is all 65 of them.

---

Let's get the hard one out of the way. The next answer must use only byte 65 (`0x41`), `A`.
> 1 votes

---
Tags: integer, answer-chaining
---


title: Naïve compression

text:
# Question
Title: Naïve compression
## using Prefixed Length Code

We are going to implement a compression of text (string, array/list of characters/bytes) by simple substitution of each character by a binary code, based on the frequency of that character in the text. The characters that occur more frequently will be replaced by shorter codes. The resulting bit array will be split on chunks with length 8.

## The code

Prefixed Length Code with length 3 is a code that consist of a prefix - 3 bits indicating the length of the field that follows, and a field. 3 bits are sufficient for 8 (2^3) different prefixes. Each prefix `n` in turn describes 2^n different fields, enumerated from 0 to 2^n-1.

`n = 0`; 1 entry (2^0)

```
000 – field with length 0;

```

`n = 1`; 2 entries (2^1)

```
001|0      (`|` is put for clarity)
001|1

```

`n = 2`; 4 entries (2^2)

```
010|00
010|01
010|10
010|11

```

`n = 7`; 128 entries (2^7)

```
111|0000000
111|0000001
111|0000010
…
111|1111111

```

Here’s a table of all the codes, enumerated from 0 to 254

```
┌──┬────────┬─────────┬─────────┬──────────┬──────────┬──────────┬──────────┬──────────┐
│  │0       │32       │64       │96        │128       │160       │192       │224       │
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│0 │000     │10100001 │110000001│110100001 │1110000001│1110100001│1111000001│1111100001│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│1 │0010    │10100010 │110000010│110100010 │1110000010│1110100010│1111000010│1111100010│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│2 │0011    │10100011 │110000011│110100011 │1110000011│1110100011│1111000011│1111100011│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│3 │01000   │10100100 │110000100│110100100 │1110000100│1110100100│1111000100│1111100100│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│4 │01001   │10100101 │110000101│110100101 │1110000101│1110100101│1111000101│1111100101│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│5 │01010   │10100110 │110000110│110100110 │1110000110│1110100110│1111000110│1111100110│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│6 │01011   │10100111 │110000111│110100111 │1110000111│1110100111│1111000111│1111100111│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│7 │011000  │10101000 │110001000│110101000 │1110001000│1110101000│1111001000│1111101000│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│8 │011001  │10101001 │110001001│110101001 │1110001001│1110101001│1111001001│1111101001│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│9 │011010  │10101010 │110001010│110101010 │1110001010│1110101010│1111001010│1111101010│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│10│011011  │10101011 │110001011│110101011 │1110001011│1110101011│1111001011│1111101011│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│11│011100  │10101100 │110001100│110101100 │1110001100│1110101100│1111001100│1111101100│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│12│011101  │10101101 │110001101│110101101 │1110001101│1110101101│1111001101│1111101101│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│13│011110  │10101110 │110001110│110101110 │1110001110│1110101110│1111001110│1111101110│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│14│011111  │10101111 │110001111│110101111 │1110001111│1110101111│1111001111│1111101111│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│15│1000000 │10110000 │110010000│110110000 │1110010000│1110110000│1111010000│1111110000│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│16│1000001 │10110001 │110010001│110110001 │1110010001│1110110001│1111010001│1111110001│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│17│1000010 │10110010 │110010010│110110010 │1110010010│1110110010│1111010010│1111110010│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│18│1000011 │10110011 │110010011│110110011 │1110010011│1110110011│1111010011│1111110011│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│19│1000100 │10110100 │110010100│110110100 │1110010100│1110110100│1111010100│1111110100│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│20│1000101 │10110101 │110010101│110110101 │1110010101│1110110101│1111010101│1111110101│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│21│1000110 │10110110 │110010110│110110110 │1110010110│1110110110│1111010110│1111110110│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│22│1000111 │10110111 │110010111│110110111 │1110010111│1110110111│1111010111│1111110111│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│23│1001000 │10111000 │110011000│110111000 │1110011000│1110111000│1111011000│1111111000│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│24│1001001 │10111001 │110011001│110111001 │1110011001│1110111001│1111011001│1111111001│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│25│1001010 │10111010 │110011010│110111010 │1110011010│1110111010│1111011010│1111111010│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│26│1001011 │10111011 │110011011│110111011 │1110011011│1110111011│1111011011│1111111011│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│27│1001100 │10111100 │110011100│110111100 │1110011100│1110111100│1111011100│1111111100│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│28│1001101 │10111101 │110011101│110111101 │1110011101│1110111101│1111011101│1111111101│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│29│1001110 │10111110 │110011110│110111110 │1110011110│1110111110│1111011110│1111111110│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│30│1001111 │10111111 │110011111│110111111 │1110011111│1110111111│1111011111│1111111111│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│31│10100000│110000000│110100000│1110000000│1110100000│1111000000│1111100000│          │
└──┴────────┴─────────┴─────────┴──────────┴──────────┴──────────┴──────────┴──────────┘

```

## The process

First we need to sort all the unique characters in the text in decreasing order by their frequency. Then we will assign each character a code – the most frequent one will get `000`, the next one - `0010` and so on. Now it’s time to traverse the text and replace each character with its corresponding code. At the end we split the resulting binary list to 8-bit chinks and convert them to decimal (or hexadecimal) integers. The last chunk may be shorter than 8 bits, so it should be filled to 8 bits. The fill is unimportant, so you can use whatever values you want – all 0, all 1 or any combination of 1 and 0. In order for the compressed data to be decompressable, we need to keep track of the length of the original message, as well as the sorted list of the characters.

## The task

Write two functions (or complete programs):

* Compress, which takes a string as an input and returns the compressed data. The compressed data should include the compressed list/array of decimal or hexadecimal integers, the length of the original input and the sorted list of characters. The three can be in an arbitrary order and can be stored as a list, array, tuple or any other structure, convenient for you. For example my test code in J returns an array of 3 boxed values :

```
   compress 'Hello World'
┌──┬────────┬────────────────┐
│11│loredWH │90 0 38 20 70 18│
└──┴────────┴────────────────┘

```

\** Note: If you don't need the length of the original input for your decompressor, you don't need to save it/print it in you compressor.

* Decompress, which takes a compressed data and returns the string after decompression.

## Scoring and winning criteria

Your score is the sum of the lengths in bytes of your two functions. The lowest score in every language wins.

## Test cases

1.

```
   compress 'Hello World'
┌──┬────────┬────────────────┐
│11│loredWH │90 0 38 20 70 18│
└──┴────────┴────────────────┘
   decompress 11;'loredWH ';90 0 38 20 70 18
Hello World

```
2.

```
   compress 'Code Golf Stack Exchange is a site for recreational programming competitions'
┌──┬───────────────────────┬───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│76│ oieatrncsmgplfxkhdSGEC│142 80 208 34 147 207 136 138 75 48 68 104 12 194 75 14 32 27 65 33 163 82 3 228 176 180 50 180 37 70 76 37 224 234 201 197 165 182 205 135 3 36 219 168 81 168 201 134 128│
└──┴───────────────────────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
   decompress 76;' oieatrncsmgplfxkhdSGEC'; 142 80 208 34 147 207 136 138 75 48 68 104 12 194 75 14 32 27 65 33 163 82 3 228 176 180 50 180 37 70 76 37 224 234 201 197 165 182 205 135 3 36 219 168 81 168 201 134 128
Code Golf Stack Exchange is a site for recreational programming competitions

```
3.

```
   compress 'GFFEEEDDDDCCCCCBBBBBBAAAAAAA'
┌──┬───────┬────────────────────────────────────────────────┐
│28│ABCDEFG│90 148 148 165 8 66 12 204 204 136 136 136 0 0 0│
└──┴───────┴────────────────────────────────────────────────┘
   decompress 28;'ABCDEFG';90 148 148 165 8 66 12 204 204 136 136 136 0 0 0
GFFEEEDDDDCCCCCBBBBBBAAAAAAA

```

## Note

The compressed data might differ between the languages due to the way sorting works on characters with equal frequency. This is not a problem, provided that your decompression code works correctly.

# Answer
# 05AB1E, ~~94~~ ~~89~~ ~~71~~ ~~64~~ ~~63~~ 61 (29+32) bytes

-25.5 bytes thanks to *@ovs*.
-2 bytes thanks to *@Neil*.

**Compressor:**

```
ÙΣ¢}R=āεb¦Dgb₄+¦ì}‡¤_9×«8ô¨C,

```

Try it online or verify all test cases.

**Decompressor:**

```
b₁b+€¦J¤Ü[D3£C3+ôć3.$1ìC<Isè?J¤F

```

First input is integer-list; second input is the string.
Stops the program with an error after it has output the correct result, which is allowed according to the meta.

Try it online or verify all test cases.

Neither of my compressor nor decompressor uses the length.

If the length of the resulting binary-string in the compressor is divisible by 8, it adds a trailing no-op integer to the output-list. (The decompressor obviously still handles both this, and binary-strings that are not divisible by 8, correctly.)

**Explanation:**

*Compressor:*

```
Ù           # Uniquify the characters of the (implicit) input-string
 Σ          # Sort these characters by:
  ¢         #  Their count in the (implicit) input-string
 }R         # After the sort: reverse it so the order is from most to least frequent
   =        # Output this string with trailing newline (without popping the string)
ā           # Push a list in the range [1,string-length] (without popping the string)
 ε          # Map each integer to:
  b         #  Convert it to a binary-string
   ¦        #  Remove its first digit
  Dg        #  Create a copy, and pop and push its length
    b       #  Convert this length to binary
            #  Pad it to length 3 with leading 0s by:
     ₄+     #   Adding 1000
       ¦    #   And then removing the first digit
        ì   #  Prepend this in front of the binary-string we've duplicated
}‡          # After the map: transliterate all sorted unique characters with these
            # strings in the (implicit) input-string
¤           # Push its last digit (without popping the string)
 _          # Invert the boolean (1 becomes 0; 0 becomes 1)
  9×        # Repeat that 9 times as string
    «       # And append it to the big string
     8ô     # Then split it into parts of size 8
       ¨    # Remove the trailing part
        C   # Convert each part from binary to an integer
         ,  # And pop and output it as well

```

*Decompressor:*

```
b           # Convert each integer in the (implicit) input-list to a binary-string
            # Pad each to length 8 with leading 0s by:
 ₁b         #  Pushing 256, and converting it to binary as well: 100000000
   +        #  Adding it to each binary string
    €¦      #  And then removing the first digit of each string
      J     # Join all binary-strings together to a single string
       ¤    # Push its last digit (without popping the string)
        Ü   # And right-strip all those trailing digits
[           # Loop indefinitely:
 D          #  Duplicate the binary-string
  3£        #  Pop the copy, and push its first 3 digits
    C       #  Convert that from binary to an integer
     3+     #  Add 3
       ô    #  Split the binary-string into parts of that size
  ć         #  Extract head; pop the remainder-list and first item separately
   3.$      #  Remove the first 3 digits of this first item
      1ì    #  Prepend a 1
        C   #  Convert it from binary to an integer as well
         <  #  And decrease it by 1
   I        #  Then push the second input-string
    s       #  Swap so the integer is at the top of the stack
     è      #  (0-based) index it into the input-string
      ?     #  Pop and output this character (without trailing newline)
   J        #  And join the remainder-list back to a string
    ¤       #  Push its first character (without popping the string),
            #  which will be either 0, 1, or an empty string
     F      #  Loop that many times, which will error for the empty string to exit the
            #  program

```
> 5 votes

# Answer
# K (ngn/k), 56 + 80 = 136 bytes

Try it online!

```
compress:{|(2/'8#'0N 8#,/(,/c[3],/:'c:{+!x#2}'!8)e?x;e:>#'=x;#x)}

```
* `{|(...;...;...)}` return a (reversed) three item list containing `(compressed data; sorted list of characters; length of input)`
    + `(...;...;#x)` get the length of the input string
    + `(...;e:>#'=x;...)` returns the characters in `x` sorted by their frequency (descending), storing in `e`
    + `(2/'8#'0N 8#,/(,/c[3],/:'c:{+!x#2}'!8)e?x;...;...)` compress the input
        - `(,/c[3],/:'c:{+!x#2}'!8)` generate all valid (compressed) bit patterns, i.e. `(0 0 0;0 0 1 0;0 0 1 1;0 1 0 0 0;...)`. this code is also used in `decompress`.
        - `(...)e?x` index into the bit patterns using the indices in `e` of each character in `x` (this ensures the most frequent characters in the input get the shortest compressed codes)
        - `8#'0N 8#,/` convert the compressed input into a list of 8-length chunks, with `8#'` ensuring each chunk contains a full 8 values
        - `2/'` converts each chunk of 8 bits into a decimal number

```
decompress:{*x{((*y),x(,/c[3],/:'c:{+!x#2}'!8)?d#t;(d:3+/2/3#t)_t:*|y)}[y]/("";,/+(8#2)\z)}

```
* `x{...}[y]/("";,/+(8#2)\z` set up a seeded-do-fold, run for `x` iterations (the number of characters), fixing `y` (the sorted list of characters), seeded with a two item list containing `(decompressed output;remaining compressed data)`. each iteration peels off one compressed character. confusingly, within the function, the fixed `y` becomes `x`, and the `("";...)` becomes `y`

+ `{(...;...)}` return a two item list, containing the updated `(decompressed output;remaining compressed data)`
* to calculate the remaining compressed data:

+ `t:*|y` store the remaining compressed data in `t`
    + `(d:3+/2/3#t)` determine how many bits the next character in the (compressed) input uses, storing in `d`
    + `(...)_t` drop this many "bits" from the compressed data
* to calculate the decompressed output:

+ `(...)?d#t` get the next compressed character, looking up its index in the...
    + `(,/c[3],/:'c:{+!x#2}'!8)` list of all valid compressed codes
    + `(*y),x(...)` retrieve the uncompressed character from `x`, and append it to `*y`, i.e. the `decompressed output`
* `{*...}` return just the first item, i.e. the decompressed string
> 4 votes

# Answer
# JavaScript (Node.js), 223 + 126 = 349 bytes

## Compressor, 223 bytes

```
s=>[s.length,a=[...new Set(s)].sort(g=(a,b)=>a?1/s.split(a).length-g(b):0),([...s].reduce((q,c)=>q<<3n+(x=(B=BigInt)(31-Math.clz32(i=a.indexOf(c)+1)))|x<<x|B(i)^1n<<x,1n)<<7n).toString(2).match(/\B.{8}/g).map(x=>+('0b'+x))]

```

Try it online!

### How?

Generating the sorted list `a[]` of unique characters:

```
a = [...new Set(s)]       // get the array of unique characters
.sort(g = (a, b) =>       // for each pair (a, b) of characters to be sorted:
  a ?                     //   if a is defined:
    1 / s.split(a).length //     compute 1 / (N + 1),
                          //     where N is the number of occurrences of a in s
    - g(b)                //     subtract the result of a recursive call
                          //     with a = b and b undefined
  :                       //   else:
    0                     //     stop the recursion
)                         // end of sort()

```

Generating the byte stream as a single BigInt:

```
[...s].reduce((q, c) =>      // for each character c in s, using q as the accumulator:
  q <<                       // left-shift q by:
    3n +                     //   3 + x positions,
    (x = (B = BigInt)(       //   where x is the number of bits required to write ...
      31 - Math.clz32(       //
        i = a.indexOf(c) + 1 //   ... the 1-indexed position i of c in a[]
      )                      //
    ))                       //
  |                          //   bitwise OR with:
  x << x                     //     x, left-shifted by x positions
  |                          //   bitwise OR with:
  B(i) ^ 1n << x,            //     i without the most significant bit
  1n                         //   start with q = 1 to preserve leading 0's
)                            // end of reduce()

```

Splitting the BigInt into a list of bytes:

```
(... << 7n)            // left-shift the final result to add 7 trailing 0's
.toString(2)           // convert to binary
.match(/\B.{8}/g)      // split by groups of 8 binary digits, ignoring the 1st one
.map(x => +('0b' + x)) // convert each group back to decimal

```

## Decompressor, 126 bytes

*19 bytes saved by @Neil!*

```
(n,a,b)=>(g=s=>n--?a['0b1'+s[S](3,x=2-~('0b'+s[S](0,3)))-1]+g(s[S](x)):'')(b.map(v=>(256+v).toString(2)[S='slice'](1)).join``)

```

Try it online!

### How?

Turning the byte stream into a binary string:

```
b.map(v =>         // for each byte v in b[]:
  (256 + v)        //  force a leading '1'
  .toString(2)     //  convert to binary
  [S = 'slice'](1) //  remove the leading '1'
).join``           // end of map(); join all strings together

```

Generating the output:

```
g = s =>                    // s = binary string
  n-- ?                     // decrement n; if it was not equal to 0:
    a[                      //   pick the next character from a[]:
      '0b1' +               //     the index of the character is 2 ** x + V - 1
      s[S](                 //     where V is defined
        3,                  //     as the x-bit value
        x = 2 -~(           //     whose length x (+3)
          '0b' + s[S](0, 3) //     is stored in the 3 leading bits
        )                   //
      ) - 1                 //
    ] +                     //   end of character lookup
    g(s[S](x))              //   recursive call with all processed bits removed
  :                         // else:
    ''                      //   stop the recursion

```
> 3 votes

# Answer
# Charcoal, ~~71~~ 64 + 32 = 96 bytes

## Compressor, 64 bytes:

```
≔Ｅθ⟦№θιι⟧ηＷ⁻ηυ⊞υ⌈ιＵＭυ⊟ι⭆¹⟦Ｌθ⪫υωＥ⪪⭆Ｅθ⍘⊕⌕υλ !⭆⟦⍘⁺⁷Ｌλ !λ⟧Φνρ⁸⍘◨λ⁸ !

```

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

```
≔Ｅθ⟦№θιι⟧η

```

Pair all of the input characters with their frequency.

```
Ｗ⁻ηυ

```

Repeat until all of the pairs have been sorted and deduplicated.

```
⊞υ⌈ι

```

Push the highest (i.e. most frequent) remaining pair to the predefined empty list.

```
ＵＭυ⊟ι

```

Drop the frequencies from the sorted, deduplicated list.

```
⭆¹⟦

```

Stringify the list of...

```
Ｌθ

```

... the length of the input, ...

```
⪫υω

```

... the concatenation of the characters in descending order of frequency, and:

```
Ｅθ⍘⊕⌕υλ !

```

For each character in the input string, find its (1-indexed, so I have to increment) popularity index, and convert it to base 2 using custom digits.

```
⭆...⭆⟦⍘⁺⁷Ｌλ !λ⟧Φνρ

```

For each converted character, add 7 to its length, convert that to base 2 using custom digits, and create a list of that and the converted string. Behead all of the strings and concatenate the bodies.

```
Ｅ⪪...⁸⍘◨λ⁸ !

```

Chop the string into substrings of length 8, right-pad the last one, and decode each substring as base 2 using the custom base characters (in particular, right-padding uses spaces, so this has to be the custom base character for 0).

Note that this version of the compressor resolves ties by taking the character with the highest ordinal, rather than the character with the first appearance that the previous version chose. I've updated the input to the decompressor link accordingly.

## Decompressor, 32 bytes:

```
Ｆ⮌ζＦ⁸⊞υ﹪÷ιＸ²κ²⭆θ§η⊖⍘⁺1⭆↨Ｅ³⊟υ²⊟υ²

```

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

```
Ｆ⮌ζ

```

Loop over the bytes in reverse.

```
Ｆ⁸

```

Loop over each bit in reverse.

```
⊞υ﹪÷ιＸ²κ²

```

Push the bit to the predefined empty list.

```
⭆θ

```

Map over each index, join and implicitly print:

```
§η⊖⍘⁺1⭆↨Ｅ³⊟υ²⊟υ²

```

Pop 3 bits from the list, decode as base 2, pop that many bits from the list, prefix `1`, decode as base 2, index into the string (0-indexed, so I have to decrement). (I could have used `BaseString` and `StringMap` twice.)
> 3 votes

# Answer
# Python 3, 190 + 128 = 318 bytes

Saved a whopping ~~28~~ ~~41~~ ~~55~~ ~~57~~ 82 bytes (and got below 400!) thanks to ovs!!!
Saved 10 bytes thanks to Neil!!!

## Compressor

# Python 3, 190 bytes

```
def c(r):j=''.join;s=j(sorted({*r},key=r.count))[::-1];i=s.index;g=j(f'{len(bin(i(c)+1)[3:]):03b}'+bin(i(c)+1)[3:]for c in r)+8*'0';return[int(g[a:a+8],2)for a in range(0,len(g),8)],len(r),s

```

Try it online!

## Decompressor

# Python 3, 128 bytes

```
def d(a,l,s):
 d=''.join(f'{d:08b}'for d in a);r=''
 while len(r)<l:b=3+int(d[:3],2);r+=s[~-int('1'+d[3:b],2)];d=d[b:]
 return r

```

Try it online!

Decompression uses the original string's length.
> 3 votes

# Answer
# Husk, ~~119~~ ~~103~~ 95 (55+40) bytes

*Edit: -8 bytes thanks to Neil*

**Compressor (55 bytes):**

```
,₁¹B256ḋS+ö`R0%8_Lṁ!ṁλm+tḋ+8¹(motḋ→½ŀ`^2→))ŀ8m€₁¹
↔Ö#¹u

```

Try it online!

**Decompressor (40 bytes):**

```
mö!²ḋ:1↓3↑I¡λ§,↓↑+3ḋ↑3¹)Ṡ+ö`R0%8_LḋB256⁰

```

Try it online!

**How does it work?**

**Compressor:**

1. Sort letters by frequency (helper function ):

```
↔Ö#¹u

```
2. Substitute letters by their rank by frequency:

```
m€₁

```
3. Genrate prefix-length-code:

```
ṁ                      ŀ8       # for each integer x from 0 to 7
 λm+                            # join
    tḋ+8¹                       # zero-padded binary digits of x to
         (motḋ→½ŀ`^2→))         # zero-padded binary digits of 1..x

```
4. Look-up each prefix-length-code from each letter rank:

```
ṁ!

```
5. Pad end with digits to multiple-of-8:

```
S+ö`R0%8_L

```
6. Convert from binary to base-256:

```
B256ḋ

```
7. And finally pair with letters sorted by frequency:

```
,₁¹

```

**Decompressor:**

1. Convert first argument from base-256 to binary digits:

```
ḋB256⁰

```
2. Pad start with digits up to multiple-of-8:

```
Ṡ+ö`R0%8_L

```
3. Sequentially get prefix-length-codes:

```
  ¡λ          )                 # apply function repeatedly:
         3ḋ↑3¹                  # remove first 3 digits & convert to number
    §,↓↑+                       # split remaining list at this position
                                # (this keeps going forever, so the list ends-up
                                # with a lot of empty elements)
↑I                              # finally, just keep the truthy prefixes

```
4. Convert to each element to a number:

```
   ↓3                           # discard the first 3 digits
 :1                             # and add a '1' at the start
                                # (equivalent to converting the 3 digits
                                # to a value from binary and adding it: Thanks Neil! )
ḋ                               # and convert it all to a value from binary

```
5. Look up the letter from second argument:

```
mö!²

```
> 2 votes

# Answer
# Perl 5, 354 bytes

```
@c=map{$c=$_;map{sprintf"%0*b%0*b",$c?3:2,$c,$c,$_}0..2**$c-1}0..7;
sub c{$_=pop;my%f;$f{$_}++for/./g;my%c;@c{@f=sort{$f{$b}<=>$f{$a}}keys%f}=@c;y///c,join('',@f),map oct(substr"0b$_".'0'x7,0,10),join('',@c{/./g})=~/.{1,8}/g}
sub d{($l,$f,@i)=@_;@d{@c}=0..255;join'',map$f=~/^.{$d{$_}}(.)/,(join('',map sprintf('%08b',$_),@i)=~/@{[join'|',@c]}/g)[0..$l-1]}

```

Try it online!

Run this to compress with function c() and decompress with d().

```
my @c1 = c('Hello World');
my @c2 = c('Code Golf Stack Exchange is a site for recreational programming competitions');
print join('|',@c1)."\n";
print join('|',@c2)."\n";
print "Bytes in 1st compression: ".(@c1-2)."\n";
print "Bytes in 2nd compression: ".(@c2-2)."\n";
print d(@c1)."|\n";
print d(@c2)."|\n";

```

Output:

```
11|loredWH |90|0|38|20|70|18
76| oieatrncsmgplfxkhdSGEC|142|80|208|34|147|207|136|138|75|48|68|104|12|194|75|14|32|27|65|33|163|82|3|228|176|180|50|180|37|70|76|37|224|234|201|197|165|182|205|135|3|36|219|168|81|168|201|134|128
Bytes in 1st compression: 6
Bytes in 2nd compression: 49
Hello World|
Code Golf Stack Exchange is a site for recreational programming competitions|

```
> 1 votes

# Answer
# , 70 + 95 = 165 bytes

Encoder returns `length;table;bytes` just as in the description. The fill for the last chunk is the last generated bit.

```
#;[(];[:#.@($~8,~#>.@%8:)@;(~.(128#3+i.8)<@$"0 1#:i.4^5){~i.~)~.\:#/.

```

Decoder using the exact same format for the input:

```
>@{.$>@{~&1({~(~.(128#3+i.8)<@$"0 1#:i.4^5)i.l<@{.])"1[:(}.~l=:3+3#.@{.])^:(<_)128,@}.@#:@,>@{:

```

Try it online!

### How it roughly works

Code table that is used in both:

* `#:i.4^5` 0…1024 in binary.
* `128#3+i.8` repeat every number in 3…11 for 128 times
* `<@$"0` for 0…127 take the first 3 digits, for 128…255 take the first 4 digits, …
* `~.` take the unique elements of the result.

Encoder:

* `~.\:#/.` sort the unique characters in the input based on occurrences. That is the character table.
* `(table){~i.~` map input to character table positions and get the corresponding code.
* `($~8,~#>.@%8:)@;` concatenate all the codes together and split them into chunks of 8.
* `#;…];#.@` convert back to integers and prepend the character table and the length.

Decoder:

* `128,@}.@#:@,>@{` take bytes and convert them back to bits. Have to prepend 128 temporarily to pad the results to 8 bits.
* `[:(}.~l=:3+3#.@{.])^:(<_)` parse the first 3 bits `n`, and remove them and the next `n` bits from the bit array. Do this until the bit array is empty. Return all intermediate results (so starting positions for the codes).
* `(table)i.l<@{.]` again, parse the starting bits and look them up in the code table.
* `>@{~&1({~` and look the index up in the character table.
* `>@{.$` trim the output down to the length of the string.
> 1 votes

# Answer
# Julia, 331 bytes

```
p(s)=Meta.parse("0b"*s)
s(n,p)=last(bitstring(n),p)
b(i,n=0,B=2^n)=2B<=i ? b(i,n+1) : s(n,3)s(i-B,n)
c(s,u=sort(unique(s),by=x->count(==(x),s),rev=0<1))=join(u),p.(i.match for i=eachmatch(r".{8}",join(b.(findlast(==(i),u) for i=s))*'1'^7))
d(u,N,s=join(s.(N,8)),n=p(s[1:3]))=u[n<1||2^n+p(s[4:3+n])]*try d(u,0,s[4+n:end])catch;""end

```

Try it online!

I don't want to separate compression and decompression because I use the functions `p` and `s` for both.

`c` is for compression, returns the sorted letters and the compressed string (missing bits are filled with 1s)

`d`is for decompression, doesn't need the length of the original string (it discards the last invalid caracter)
> 1 votes

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


title: Make a one sequence

text:
# Question
Title: Make a one sequence
A sequence of integers is a one-sequence if the difference between any two consecutive numbers in this sequence is -1 or 1 and its first element is 0.

More precisely: \\$a\_1, a\_2, ..., a\_n\\$ is a one-sequence if:

$$\forall k \\::\\: 1\le k\<n, |a\_k-a\_{k+1}| = 1 \\ a\_1 = 0$$

**Input**

* \\$n\\$ \- number of elements in the sequence
* \\$s\\$ \- sum of elements in the sequence

**Output**

* a one-sequence set/list/array/etc of length \\$n\\$ with sum of elements \\$s\\$, if possible
* an empty set/list/array/etc if not possible

**Examples**

For input `8 4`, output could be `[0 1 2 1 0 -1 0 1]` or `[0 -1 0 1 0 1 2 1]`. There may be other possibilites.

For input `3 5`, output is empty `[]`, since it cannot be done.

**Rules**

This is a code golf, shortest answer in bytes wins. Submissions should be a program or function. Input/output can be given in any of the standard ways.

# Answer
## CJam, ~~56 47 44~~ 34 bytes

A lot of scope for improvement here, but here goes the first attempt at this:

```
L0aa{{[~_(]_)2++}%}l~:N;(*{:+N=}=p

```

Credits to Dennis for efficient way of doing the `{ ... }%` part.

Prints the array representation if possible, otherwise `""`

Try it online here
> 7 votes

# Answer
# JavaScript (E6) 79  ~~82~~

```
F=(n,t,
  d=n+n*~-n/4-t/2,
  l=1,
  q=[for(x of Array(n))d<n--?++l:(d+=~n,--l)]
)=>d?[]:q

```

No need of brute force or enumeration of all tuples.

See a sequence of length *n* as *n*-1 steps, each step being increment or decrement.
Note, you can only swap an increment for a decrement, sum varies by 2, so for any given length the sum is always even or always odd.
Having all increments, the sequence is 0, 1, 2, 3, ..., n-1 and we know the sum is (n-1)\*n/2
Changing the last step, the sum changes by 2, so the last step weighs 2.
Changing the next to last step, the sum changes by 4, so the last step weighs 4. That's because the successive step builds upon the partial sum so far.
Changing the previous step, the sum changes by 6, so the last step weighs 6 (not 8, it's not binary numbers).
...
Changing the first step weighs (n-1)\*2

*Algorithm*

```
Find the max sum (all increments)
Find the difference with the target sum (if it's not even, no solution)
Seq[0] is 0
For each step
  Compare current difference with the step weight
  if is less
     we have an increment here, seq[i] = seq[i-1]+1
  else
     we have a decrement here, seq[i] = seq[i-1]-1.
     Subtract we current weight from the current diff.
If remaining diff == 0, solution is Seq[]. Else no solution

```

**Ungolfed code**

```
F=(len,target)=>{
  max=(len-1)*len/2
  delta = max-target
  seq = [last=0]
  sum = 0
  weight=(len-1)*2
  while (--len > 0)
  {
    if (delta >= weight)
    {
      --last
      delta -= weight;
    }
    else
    {
      ++last
    }
    sum += last
    seq.push(last);
    weight -= 2;
  }
  if (delta) return [];
  console.log(sum) // to verify

  return seq
}

```

**Test** In Firefox / FireBug console

```
F(8,4)

```

*Output*

```
[0, -1, 0, -1, 0, 1, 2, 3]

```
> 8 votes

# Answer
## GolfScript (41 39 bytes)

```
[][1,]@~:^;({{.-1=(+.)))+}%}*{{+}*^=}?`

```

Online demo

Thanks to Dennis for 41-\>39.
> 5 votes

# Answer
# Jelly, 11 bytes

```
’Ø-ṗÄS=¥ƇḢŻ

```

Try it online!

Although I originally had `’2*ḶBz0Z-*ÄS=¥ƇḢŻ`, this is close enough to caird's solution in principle now that I'm almost tempted to just suggest it in the comments. In the case that you really really want `[]` over `0`, maybe it's just +3 bytes?, maybe it's +5.

```
 Ø-            [-1, 1]
   ṗ           to the Cartesian power of
’              n - 1.
    Ä          Cumulative sums.
        Ƈ      Keep only those for which
     S ¥       the sum
      =        is equal to s.
         Ḣ     Take the first survivor
          Ż    and slap a 0 on the start of it.

```
> 5 votes

# Answer
## Mathematica, 73 bytes

```
f=FirstCase[{0}~Join~Accumulate@#&/@Tuples[{-1,1},#-1],l_/;Tr@l==#2,{}]&;

```

Simple brute force solution.

I'm generating all choices of steps. Then I turn those into accumulated lists to get the one-sequences. And then I'm looking for the first one whose sum is equal to the second parameter. If there is non, the default value is `{}`.
> 3 votes

# Answer
## Haskell, 56 bytes

```
n%s=[x|x<-scanl(+)0`map`mapM(\_->[1,-1])[2..n],s==sum x]

```

Explanation:

* Build a list with the permutations of `1,-1` and length n-1: `replicateM n-1[-1,1]`
Example: `replicateM 2 [-1,1]` == `[[-1,-1],[-1,1],[1,-1],[1,1]]`
* Build the one-sequence out of it. `scanl` has poor performance, but it does the right job here.
* Filter all possible one-sequences with length `n` where the sum is `s`
> 3 votes

# Answer
# Husk, <sup>~~14~~</sup> 16 bytes

```
ḟo=⁰ΣmΘm∫π←²fIṡ1

```

Try it online!

Same idea as Unrelated String's answer. ~~I'll add in a version that returns `[]` once I can find a way to make `if` work properly.~~

Now works as advertised!
> 3 votes

# Answer
# Python, 138

```
from itertools import*
def f(n,s):
 for i in[list(accumulate(x))for x in product([-1,1],repeat=n-1)]:
  if sum(i)==s:return[0]+i
 return[]

```
> 2 votes

# Answer
# Python 3, 80 bytes

```
f=lambda l,s,a=[0]:l>1and max(f(l-1,s,a+[a[-1]+x])for x in(1,-1))or(sum(a)==s)*a

```

Try it online!
> 2 votes

# Answer
# Jelly, ~~18~~ 16 bytes

```
’Ø-œċŒ!€ẎÄS=¥ƇḢŻ

```

Try it online!

Returns `0` if no such list exists. If you insist on returning `[]`, +5 bytes.

-2 bytes thanks to Unrelated String

## How it works

Rather than generating all possible lists of length \\$n\\$ and comparing to specific parameters, this instead generates all possible partial differences, then filters sequences on that

```
’Ø-œċŒ!€ẎÄS=¥ƇḢŻ - Main link. Takes n on the left and s on the right
’                - n-1
 Ø-              - [-1, 1]
   œċ            - Combinations with replacement
     Œ!€         - Get the permutations of each
        Ẏ        - Tighten into a list of partial differences
         Ä       - Compute the forward sums
             Ƈ   - Filter; Keep those sequences k where the following is true:
            ¥    -   Group the previous 2 links into a dyad f(k, s):
          S      -     Sum of k
           =     -     Equals s
              Ḣ  - Take the first sequence or 0 if there are none
               Ż - Prepend a 0 if a list

```
> 1 votes

# Answer
## CJam, ~~65~~ ~~58~~ 54 bytes

Barely shorter than my Mathematica solution, but that's mostly my fault for still not using CJam properly:

```
0]]l~:S;({{_1+\W+}%}*{0\{+_}%);}%_{:+S=}#_@\i=\0>\[]?p

```

It's literally the same algorithm: get all `n-1`-tuples of `{1, -1}`. Find the first one whose accumulation is the same as `s`, prepend a `0`. Print an empty array if none is found.
> 0 votes

# Answer
# CJam, 40

Another approach in CJam.

```
ri,W%)\_:+ri-\{2*:T1$>1{T-W}?2$+\}/])!*p

```
> 0 votes

# Answer
**Ruby(136)**

```
def one_sequences(n)
  n.to_s.chars.map(&:to_i).each_cons(2).to_a.select{|x|x[0] == 0 && (x[1] == 1 || x[1]
  == -1)}.count
end

```
> 0 votes

# Answer
# J, 47 chars

Checks every sequence like many other answers. Will try to make a shorter O(n) solution.

```
   f=.4 :'(<:@#}.])(|:#~y=+/)+/\0,|:<:2*#:i.2^<:x'

   8 f 4
0 1 2 1 0 1 0 _1

   3 f 5
[nothing]

```
> 0 votes

# Answer
## APL 38

```
{⊃(↓a⌿⍨⍺=+/a←+\0,⍉1↓¯1*(⍵⍴2)⊤⍳2*⍵),⊂⍬}

```

Example:

```
     4 {⊃(↓a⌿⍨⍺=+/a←+\0,⍉1↓¯1*(⍵⍴2)⊤⍳2*⍵),⊂⍬}8
0 1 2 1 0 1 0 ¯1

```

This one as many others just brute forces through every combination to find one that matches, if not found returns nothing. Actually it tries some combinations more than once to make the code shorter.
> 0 votes

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


# Question
Title: Find the missing number in an undelimited string
The challenge is to identify the missing number in a string of undelimited integers.

You are given a string of digits (valid input will match the regular expression `^[1-9][0-9]+$`). The string represents a sequence of integers. For example, `1234567891011`. All numbers in the sequence are in the range from `1` and `2147483647` inclusive.

The sequence is a series of numbers where each number is one greater than its predecessor. However, this sequence *may* contain one and only one missing number from the sequence. It is possible that a given string also contains no missing numbers from the sequence. The string will always contain at least two numbers from the sequence.

The code must output or return the missing value, or `0` (this is a `0` \- not a falsy value) in the event that the no missing values were found.

The following are valid inputs and their output/return:

```
input                         output    actual sequence (for refrence)
123467                        5         1 2 3 4 _ 6 7
911                           10        9 __ 11
123125126                     124       123 ___ 125 126
8632456863245786324598632460  8632458   8632456 8632457 _______ 8632459 8632460
123                           0         1 2 3
8632456863245786324588632459  0         8632456 8632457 8632458 8632459

```

While all of this is described as a 'string' as input, if the language is capable of handling arbitrarily large numbers (`dc` and `mathematica`, I'm looking at you two) the input may be an arbitrarily large number instead of a string if that makes the code easier.

For reference, this was inspired by the Programmers.SE question: Find missing number in sequence in string

# Answer
## Haskell, ~~115~~ 112 bytes

```
g b|a<-[b!!0..last b]=last$0:[c|c<-a,b==filter(/=c)a]
maximum.map(g.map read.words.concat).mapM(\c->[[c],c:" "])

```

The first line is a helper function definition, the second is the main anonymous function. Verify test cases (I had to run shorter tests because of time restrictions).

## Explanation

This is a brute force solution: split the string into words in all possible ways, parse the words to integers, see whether it's a range with one element missing (returning that element, and `0` otherwise), and take the maximum over all splittings. The range-with-missing-element check is done in the helper function `g`, which takes a list `b` and returns the sole element in the range `[head of b..last of b]` that's not in `b`, or `0` if one doesn't exist.

```
g b|                         -- Define g b
    a<-[b!!0..last b]=       -- (with a as the range [head of b..last of b]) as:
    last$0:[...]             --  the last element of this list, or 0 if it's empty:
            c|c<-a,          --   those elements c of a for which
            b==filter(/=c)a  --   removing c from a results in b.
mapM(\c->[[c],c:" "])        -- Main function: Replace each char c in input with "c" or "c "
map(...)                     -- For each resulting list of strings:
  g.map read.words.concat    --  concatenate, split at spaces, parse to list of ints, apply g
maximum                      -- Maximum of results (the missing element, if exists)

```
> 5 votes

# Answer
# C, ~~183~~ ~~168~~ ~~166~~ 163 bytes

```
n,l,c,d,b[9];main(s,v,p)char**v,*p;{for(;s>1;)for(d=s=0,n=atoi(strncpy(b,p=v[1],++l)),p+=l;*p&&s<2;)p+=memcmp(p,b,c=sprintf(b,"%d",++n))?d=n,s++:c;printf("%d",d);}

```

## Ungolfed

```
n,l,c,d,b[9];

main(s,v,p)char**v,*p;
{
    /* Start at length 1, counting upwards, while we haven't
       found a proper number of missing numbers (0 or 1) */
    for(;s>1;)
        /* Start at the beginning of the string, convert the
           first l chars to an integer... */
        for(d=s=0,n=atoi(strncpy(b,p=v[1],++l)),p+=l;*p&&s<2;)
            /* If the next number is missing, then skip, otherwise
               move forward in the string.... */
            p+=memcmp(p,b,c=sprintf(b,"%d",++n))?d=n,s++:c;

    printf("%d",d); /* print the missing number */
}

```
> 2 votes

# Answer
# JavaScript (ES6), 117 bytes

```
s=>eval(`for(i=l=0;s[i];)for(n=s.slice(x=i=m=0,++l);s[i]&&!x|!m;x=s.slice(x?i:i+=(n+"").length).search(++n))m=x?n:m`)

```

## Explanation

Fairly efficient approach. Finishes instantly for all test cases.

Gets each substring from the beginning of the input string as a number `n` and initialises the missing number `m` to `0`. It then repeatedly removes `n` from the start of the string, increments `n` and searches the string for it. If `index of n != 0`, it checks `m`. If `m == 0`, set `m = n` and continue, if not, there are multiple missing numbers so stop checking from this substring. This process continues until the entire string has been removed.

```
var solution =

s=>
  eval(`                     // use eval to use for loops without writing {} or return
    for(
      i=                     // i = index of next substring the check
      l=0;                   // l = length of initial substring n
      s[i];                  // if it completed successfully i would equal s.length
    )
      for(
        n=s.slice(           // n = current number to search for, initialise to subtring l
          x=                 // x = index of n relative to the end of the previous n
          i=                 // set i to the beginning of the string
          m=0,               // m = missing number, initialise to 0
          ++l                // increment initial substring length
        );
        s[i]&&               // stop if we have successfully reached the end of the string
        !x|!m;               // stop if there are multiple missing numbers
        x=                   // get index of ++n
          s.slice(           // search a substring that starts from the end of the previous
                             //     number so that we avoid matching numbers before here
            x?i:             // if the previous n was missing, don't increment i
            i+=(n+"").length // move i to the end of the previous number
          )
          .search(++n)       // increment n and search the substring for it's index
      )
        m=x?n:m              // if the previous number was missing, set m to it
  `)                         // implicit: return m
```

```
<input type="text" id="input" value="8632456863245786324598632460" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
> 2 votes

# Answer
# JavaScript (ES6) 114

```
s=>eval("for(d=0,n=-9,z=s;z=z.slice((n+'').length);z.search(++n)?z.search(++n)?n=(z=s).slice(x=0,++d):x=n-1:0);x")

```

**Less golfed** and explained

```
f=s=>{
  d = 0  // initial digit number, will be increased to 1 at first loop
  n = -9 // initial value, can not be found
  z = s  // initializa z to the whole input string
  // at each iteration, remove the first chars of z that are 'n'
  // 'd' instead of 'length' would be shorter, but the length can change passing from 9 to 10
  for(; z=z.slice((n+'').length); )
  {
    ++n; // n is the next number expected in sequence
    if (z.search(n) != 0)
    {
      // number not found at position 0
      // this could be the hole
      // try to find the next number
      ++n;
      if (z.search(n) != 0)
      {
        // nope, this is not the correct sequence, start again
        z = s; // start to look at the whole string again
        x = 0; // maybe I had a candidate result in xm but now must forget it
        ++d;   // try a sequence starting with a number with 1 more digit
        n = z.slice(0,d) // first number of sequence
      }
      else
      {
        // I found a hole, store a result in x but check the rest of the string
        x = n-1
      }
    }
  }
  return x // if no hole found x is 0
}

```

**Test**

```
F=s=>eval("for(d=0,n=-9,z=s;z=z.slice((n+'').length);z.search(++n)?z.search(++n)?n=(z=s).slice(x=0,++d):x=n-1:0);x")

console.log=x=>O.textContent+=x+'\n'

elab=x=>console.log(x+' -> '+F(x))

function test(){ elab(I.value) }

;['123467','911','123125126','8632456863245786324598632460',
  '123','124125127','8632456863245786324588632459']
.forEach(t=>elab(t))
```

```
<input id=I><button  onclick='test()'>Try your sequence</button>
<pre id=O></pre>
```
> 2 votes

# Answer
# Jelly, 16 bytes

```
ŒṖḌI’ḂƑƊƇḢ.ịr/ḟƲ

```

Try it online!

Input as a list of digits. Outputs a singleton list `[a]` containing the missing element, or `[]` if there isn't one. +1 byte to output `0` instead, and +1 byte to input as a single integer.

## How it works

```
ŒṖḌI’ḂƑƊƇḢ.ịr/ḟƲ - Main link. Takes a list of digits D on the left
ŒṖ               - All partitions of D
  Ḍ              - Convert back to integers
       ƊƇ        - Keep those for which the following is true:
   I             -   Forward differences
    ’            -   Decrement
     ḂƑ          -   This list is invariant under bit i.e. all 1 or 0
         Ḣ       - Take the first, R
               Ʋ - Over R:
          .ị     -   Take the first and last elements
            r/   -   Yield a range between them
              ḟ  -   Remove the elements that are in R
                   This returns the single element that is in the range but not R

```
> 1 votes

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


title: The Untouchables

text:
# Question
Title: The Untouchables
# Untouchable Numbersα

An untouchable number is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer (including the untouchable number itself).

For example, the number 4 is not untouchable as it is equal to the sum of the proper divisors of 9: 1 + 3 = 4. The number 5 is untouchable as it is not the sum of the proper divisors of any positive integer. 5 = 1 + 4 is the only way to write 5 as the sum of distinct positive integers including 1, but if 4 divides a number, 2 does also, so 1 + 4 cannot be the sum of all of any number's proper divisors (since the list of factors would have to contain both 4 and 2).

The number 5 is believed to be the only odd untouchable number, but this has not been proven: it would follow from a slightly stronger version of the Goldbach conjecture. β

There are infinitely many untouchable numbers, a fact that was proven by Paul Erdős.

A few properties of untouchables:

* No untouchable is 1 greater than a prime
* No untouchable is 3 greater than a prime, except 5
* No untouchable is a perfect number
* Up to now, all untouchables aside from 2 and 5 are composite.

# Objective

Create a *program or function* that takes a natural number `n` via **standard input or function parameters** and prints the first `n` untouchable numbers.

The output must have separation between the numbers, but this can be anything (i.e. newlines, commas, spaces, etc).

This should be able to work at least `1 <= n <= 8153`. This is based on the fact that the b-file provided for the OEIS entryγ goes up to `n = 8153`.

Standard loopholes are disallowed, as per usual.

# Example I/O

```
1    -> 2
2    -> 2, 5
4    -> 2, 5, 52, 88
10   -> 2, 5, 52, 88, 96, 120, 124, 146, 162, 188
8153 -> 2, 5, 52, 88, 96, 120, ..., ..., ..., 59996

```

This is , so least number of bytes wins.

---

α - Wikipedia,  β - MathWorld,  γ - OEIS

---

For some reason this was marked as a duplicate to the 'finding semiperfect numbers' question, however the tasks are completely different. In this case, you must check to make sure that no sum of perfect divisors of any natural number can equal a certain number.

# Answer
> 6 votes
# Pyth, 21 bytes

```
.f!fqZsf!%TYStTSh^Z2Q

```

Warning: Incredibly slow. Test run and timing below.

```
$ time pyth -c '.f!fqZsf!%TYStTSh^Z2Q' <<< 3
[2, 5, 52]

real    2m46.463s
user    2m46.579s
sys 0m0.004s

```

It's basically as brute force as possible, tests factorizations up to the potential lonely number squared plus one.

# Answer
> 4 votes
# C, 104 bytes

```
j,i,z,w;u(y){for(z=2;y;z++)for(w=0;(++w<z*z||0&printf("%i ",z)+y--)&&j^z;)for(i=j=0;++i<w;j+=i*!(w%i));}

```

It will take a few minutes for *y* \> 20, but whatever.

# Answer
> 3 votes
# Java, 310 Bytes

```
class U{int[] p;U(int e){p=new int[(int)4e9];for(int i=1,c=0;c<e;i++)if(u(i)>0){System.out.println(i);c++;}}int p(int n){if(p[n]!=0)return p[n];int i,s=1;for(i=2;i<=n-1;i++)s+=n%i==0?i+(n/i!=i?n/i:0):0;return(p[n]=s);}int u(int n){if(n==1)return 0;for(int i=2;i<=(n-1)*(n-1);i++)if(p(i)==n)return 0;return 1;}}

```

Golfed as well as I could but, I was more interested in making sure it ran in reasonable time. The unglofed version is probably more interesting

```
public class Untouchable {
    int[] properDivisorSumMap;

    public Untouchable(int estimatedMaxium){
        properDivisorSumMap = new int[(estimatedMaxium-1)*(estimatedMaxium-1)];
    }

    public int properDivisorSum(int n){
        if(properDivisorSumMap[n] != 0){
            return properDivisorSumMap[n];
        }

        int sum = 1;
        for(int i=2;i<=(int)Math.sqrt(n);i++){
            if(n%i==0){
                sum+=i;
                if(n/i != i){
                    sum+=n/i;
                }
            }
        }
        properDivisorSumMap[n] = sum;
        return sum;
    }

    public boolean untouchable(int n){
        if(n==1){
            return false;
        }
        for(int i=2;i<=(n-1)*(n-1);i++){
            if(properDivisorSum(i) == n){
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args){
        Untouchable test = new Untouchable(8480);

        int elements = Integer.parseInt(args[0]);

        for(int i=1,count=0;count < elements;i++){
            if(test.untouchable(i)){
                System.out.printf("%4d: %4d%n",count,i);
                count++;
            }
        }
    }
}

```

# Answer
> 1 votes
## Go, 396 bytes

Not really golfed, but it can do all of the required range. Runs in about ~20min and needs ~7GB (independent of n). Makes a giant array to compute the sum of divisors for all numbers up to 59997 squared.

```
func untouchable(n int) {
    const C = 59997
    const N = C * C
    s := make([]uint16, N)
    for d := 1; d < N; d++ {
        for i := 2 * d; i < N; i += d {
            v := int(s[i]) + d
            if v > C {
                v = C + 1 // saturate at C+1
            }
            s[i] = uint16(v)
        }
    }
    var m [C]bool
    for i := 2; i < N; i++ {
        if s[i] < C {
            m[s[i]] = true
        }
    }
    for i := 2; n > 0; i++ {
        if !m[i] {
            println(i)
            n--
        }
    }
}

```

# Answer
> 0 votes
# Jelly, ~~10~~ 9 bytes

```
2²Æṣ€ḟƑƊ#

```

Try it online!

Times out on TIO for \\$n \> 3\\$, but works in theory for all \\$n\\$. Relies on the assumption that for a given \\$x \ge 2\\$, \\$x\\$ is untouchable if none of the proper divisor sums between \\$1\\$ and \\$x^2\\$ equals \\$x\\$. Takes \\$n\\$ on STDIN.

## How it works

```
2²Æṣ€ḟƑƊ# - Main link. Takes no arguments
       Ɗ  - Group the previous 3 links together into a monad f(k):
 ²        -   k²
    €     -   Over each 1, 2, ..., k²:
  Æṣ      -     Proper divisor sum
      Ƒ   -   Is the list of proper divisor sums unchanged after:
     ḟ    -     removing k from it?
2       # - Count up k = 2, 3, ... until n such k's return true under f(k)

```

# Answer
> 0 votes
# , 122 bytes

```
function(n)while(n){T=T+1
m=T^2
t=0
while(m<-m-1){i=s=0;while((i=i+1)<m)if(!m%%i)s=s+i;t=t+(T==s)}
if(!t){print(T);n=n-1}}

```

Try it online!

Anyone familiar with  programming will certainly wince when they look at this. Loops in general are horribly inefficient in , and the fast and idiomatic way to tackle this kind of question would normally be to use vectorized functions.

Unfortunately, the maximum size of a vector in  is 2^31-1 elements, which is smaller than the square of 59996, the highest number that we need to test for untouchability, so we can't easily find divisors by checking a large vector.

So here we use a set of nested `while` loops to avoid making the big vectors that we really want. If you aren't used to , this will probably seem quite unremarkable, and you'll probably also be surprised at just how slowly it runs (n=4 times-out on TIO!).

If only  used *un*-signed integers to index vectors, and so could manage vectors with 2^32 elements, the code would be only 80 bytes:

**Imaginary  with 2^32-sized vectors, 80 bytes**

```
function(n,m=1:4e9,a=!m){for(y in m)a[sum(which(!y%%(2:y-1)))]=T
which(!a)[1:n]}

```

Try it online! (but it won't work for large n)

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


title: Integer Interpretator

text:
# Question
Title: Integer Interpretator
## The Challenge

Given a finite list of integers, split it into the fewest partitions possible such that no partition contains a number more than once.

## Rules

Input can be in any format and any order.

Output can be in any format, as long as it's clear that each group is separate.

This is , so lowest score wins!

## Example I/O

```
Input: [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2]
Output: [[1,2],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1]]

Input: [1,3,4,2,6,5,1,8,3,8]
Output: [[1,3,4,2,6,5,8],[1,3,8]]

Input: [5,9,12,5,2,71,23,4,7,2,6,8,2,4,8,9,0,65,4,5,3,2]
Output: [[5,9,12,2,71,23,4,7,6,8,0,65,3],[5,4,8,9,2],[4,5,2],[2]]

```

# Answer
# Jelly, 3 bytes

```
ĠZị

```

A monadic Link accepting a list, which yields a shortest set-wise partition such that each part is a set.

**Try it online!**

### How?

```
ĠZị - Link: list, L                      e.g. [8,2,4,2,9,4,1]
Ġ   - group indices of L by their values      [[7],[2,4],[3,6],[1],[5]]
 Z  - transpose                               [[7,2,3,1,5],[4,6]]
  ị - index into L                            [[1,2,4,8,9],[2,4]]

```
> 10 votes

# Answer
# Python 2, 50 bytes

```
l=input()
while l:s=set(l);print s;map(l.remove,s)

```

Try it online!

Repeatedly prints the unique of elements of the list, then removes one of each such element. A rare imperative use of `map`.
> 20 votes

# Answer
# Haskell, 39 bytes

First we collect all equal elements in separate lists using `sort` and then `group`. By `transpose`ing the resulting list of lists we get at most one of each of those elements in the resulting lists.

```
import Data.List
f=transpose.group.sort

```

Try it online!

### Example

```
                     [1,2,3,2,4,2,1,5] --input
                sort$[1,2,3,2,4,2,1,5] --[1,1,2,2,2,3,4,5]
          group.sort$[1,2,3,2,4,2,1,5] --[[1,1],[2,2,2],[3],[4],[5]]
transpose.group.sort$[1,2,3,2,4,2,1,5] --[[1,2,3,4,5],[1,2],[2]]

```
> 14 votes

# Answer
# , ~~20~~ 17 bytes

```
_<@-."1~0|:1%%/.~

```

Try it online!

```
             %      divide 1 by each, 0 becomes infinity
              /.~   group equal values, every group gets padded with zeroes
           1%       invert back
        0|:         transpose
_<@-."1~            remove the infinities, put each row in a box

```

I suspect `0|:1%%/.~` is acceptable, we get

```
5 9 12 2 71 23 4 7 6 8 0 65 3
5 9  _ 2  _  _ 4 _ _ 8 _  _ _
5 _  _ 2  _  _ 4 _ _ _ _  _ _
_ _  _ 2  _  _ _ _ _ _ _  _ _

```
> 6 votes

# Answer
# Jelly, 4 bytes

```
¹ƙ`Z

```

Try it online!

A monadic link that takes a list of integers and returns a list of lists of integers. Simply groups identical numbers and then transposes.
> 5 votes

# Answer
# Haskell, 54 bytes

```
(a:b)%n|elem n a=a:b%n|s<-n:a=s:b
_%n=[[n]]
foldl(%)[]

```

Try it online!

We define a function `%` which takes a single number and adds it to a partition scheme and we fold it across the input starting with an empty partition scheme.
> 5 votes

# Answer
# Japt, 3 bytes

```
ü y

```

Try it

Sorts & partitions by value and then transposes the result.
> 5 votes

# Answer
# JavaScript (ES6), 59 bytes

```
a=>a.map(o=n=>b[i=o[n]=-~o[n],--i]=[...b[i]||[],n],b=[])&&b

```

Try it online!
> 4 votes

# Answer
# Perl 6, 30 bytes

```
{roundrobin map &[xx],.Bag.kv}

```

Try it online!

Inspired by the Jelly answers.

### Explanation

```
{                            }  # Anonymous block
                      .Bag      # Convert to Bag (multiset)
                          .kv   # Key-value sequence
            map &[xx],  # Repeat each key n times
 roundrobin  # Transpose

```

### Old solution, 32 bytes

```
{(.Bag,{$_∖.Set}...^!*)>>.Set}

```

Try it online!

### Explanation

```
{                            }  # Anonymous block
      ,         ...^    # Create sequence
  .Bag                  # starting with input converted to Bag (multiset)
       {$_∖.Set}        # Decrease weights by one each iteration
                    !*  # Until bag is empty
 (                    )>>.Set  # Convert all bags to sets

```
> 4 votes

# Answer
# , 54 bytes

```
for(i in 1:max(t<-table(scan())))print(names(t)[t>=i])

```

Try it online!

Builds a table of the counts of the values. For input `1 3 4 2 6 5 1 8 3 8`, this gives

```
t = 1 2 3 4 5 6 8
    2 1 2 1 1 1 2

```

where the first row is `names(t)` (the different values in the input) and the second is the counts in `t`.

Then in the for loop, at iteration `i`, print only the names corresponding to counts ≥`i`.
> 4 votes

# Answer
# , 23 bytes

```
(}:,(~:</.])&>@{:)^:_@<

```

Try it online!
> 3 votes

# Answer
# Pyth, 4 bytes

```
.T.g

```

Try it online!
> 3 votes

# Answer
# Burlesque, 6 bytes

```
rasgtp

```

Try it online!

```
ra # Read input as array
sg # Sort and group like values
tp # Transpose

```
> 3 votes

# Answer
# Red, ~~67~~ 61 bytes

```
func[b][until[print a: unique b foreach e a[alter b e]b =[]]]

```

Try it online!

Inspired by xnor's Python answer \- don't forget to upvote it!

This was a rare opportunity to use `alter`\- `If a value is not found in a series, append it; otherwise, remove it`
> 2 votes

# Answer
# Charcoal, 17 bytes

```
ＩＥ⌈Ｅθ№θιΦθ⁼№…θμλι

```

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

```
    θ               Input array
   Ｅ                Map over elements
     №              Count of
       ι            Current element in
      θ             Input array
  ⌈                 Maximum
 Ｅ                  Map over implicit range
         θ          Input array
        Φ           Filter elements where
           №        Count of
               λ    Current element in
             θ      Input array
            …       Truncated to length
              μ     Inner index
          ⁼         Is equal to
                ι   Outer index
Ｉ                   Cast to string
                    Implicitly print

```
> 2 votes

# Answer
# C (gcc) with `-m32` flag, ~~231~~ ~~213~~ ~~210~~ 209 bytes

Thanks to ceilingcat (-22 bytes) for the suggestions.

The function goes through the list of values and builds a reverse list of the unique values, incrementing its count on a match. After the list has been built, the function then goes through the list again, printing any values that have a non-zero count and decrementing the count: It repeats this until all values have a zero count.

```
g(v,c,p)int*v,*p;{int*i=p,w[3]={p,*v,!c};if(c){for(;i&&i[1]-w[1];i=*i);2[i=i?:w]++;g(++v,--c,p=i-w?p:i);}else for(;w[2];p=*w)for(w[2]=!puts("");p;p=*p)p[2]?printf("\t%d",p[1]),p[2]-=w[2]=1:0;}f(v,c){g(v,c,0);}

```

Try it online!
> 2 votes

# Answer
# Perl 6, 25 bytes

```
*.classify({%.{$_}++}){*}

```

Try it online!

Groups each element of the input by how many times it has appeared in the sequence so far, then take only the values
> 2 votes

# Answer
# C (gcc), 114 bytes

```
W;*P;S(D,E)int*D,*E;{do for(P=D;P<E;*P==W?printf("%d ", W),*P=*D,*D++=W,P=E:++P);while(++W);puts("");D-E&&S(D,E);}

```

This solution takes a while to run because it iterates over all possible integer values from -2^31 to 2^31-1. Here is a TIO link to a slightly longer solution that runs a lot faster, the only difference is, that it uses short instead of int. Groups are separated by line breaks.

Try it online!

How does it work?

```
For every possible integer value
    if value in array
        print value
        remove found value entry from list
print endline
if array is not empty
    recursively call function on remaining array

```

```
int W;
int *P;

S(int* D, int* E)
{
    // this loop will run once for every possible integer value
    do
    {
        // search for the integer value W
        for(P=D;P<E;++P)
            // if the value is found
            if (*P == W)
            {
                // output the value, can happen only once per integer value
                printf("%d ", W);
                // overwrite the found value with the first value of the array
                // because we have to output the first value later
                *P = *D;
                // reduce the size of the remaining array by one
                D++;
                // jump out of for loop to seach for next possible value of W
                P = E;
            }
    }
    while(++W); // after the while loop W==0 again

    puts("");   // output new line

    if (D!=E)
        S(D,E); // if end is not reached, search again in ramaining array
}

```
> 2 votes

# Answer
# Zsh, 58 bytes

```
for x (${(u)@})<<<$x&&argv[$@[(i)$x]]=
<<<"
${*:+`$0 $@`}"

```

Try it online!

Yay, recursion! For each element `$x` of `(u)`nique `${@}`rguments, print it, and set the first `(i)`nstance of it to the empty string.

Finally, print a newline as a list delimiter, and if the remaining arguments are nonempty, substitute `$0 $@`, which is this program, called with all remaining nonempty elements.
> 2 votes

# Answer
# , 41 bytes

```
split(sort(s<-scan()),sequence(table(s)))

```

Try it online!

Like Robin Ryder's answer, this makes use of `table` to get counts of the unique elements in the input.

A fuller explanation to follow.
> 2 votes

# Answer
# 05AB1E, 4 bytes

```
{γζþ

```

Try it online or verify all test cases.

**Explanation:**

```
{     # Sort the (implicit) input-list
      #  i.e. [5,9,12,5,2,71,23,4,7,2,6,8,2,4,8,9,0,65,4,5,3,2]
      #   → [0,2,2,2,2,3,4,4,4,5,5,5,6,7,8,8,9,9,12,23,65,71]
 γ    # Group it into chunks of the same subsequent value
      #  → [[0],[2,2,2,2],[3],[4,4,4],[5,5,5],[6],[7],[8,8],[9,9],[12],[23],[65],[71]]
  ζ   # Zip/transpose; swapping rows/columns, with a space character as filler by default
      #  → [[  0, 2,   3,   4,   5,   6,   7,   8,   9,  12,  23,  65,  71],
      #     [' ', 2, ' ',   4,   5, ' ', ' ',   8,   9, ' ', ' ', ' ', ' '],
      #     [' ', 2, ' ',   4,   5, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
      #     [' ', 2, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']]
   þ  # Remove all spaces by only keeping digits
      #  → [[0,2,3,4,5,6,7,8,9,12,23,65,71],[2,4,5,8,9],[2,4,5],[2]]
      # (after which the result is output implicitly)

```
> 2 votes

# Answer
# C++ (clang), ~~230~~ \\$\cdots\\$ ~~198~~ 162 bytes

Saved 11 bytes thanks to @ErikF!!!
Saved ~~8~~ a whopping 44 bytes thanks to ceilingcat!!!

```
#import<bits/stdc++.h>
void f(std::vector<int>v){for(;v.size();puts(""))for(int e:std::set<int>(&v[0],&*end(v)))printf("%d ",e),v.erase(find(begin(v),end(v),e));}

```

Try it online!

Basic port of @xnor's algorithm without the clever stuff.
> 1 votes

# Answer
# Husk, 3 bytes

```
TkI

```

Try it online!

Key on value, then transpose.
> 1 votes

# Answer
# Perl 5 `-a`, 46 bytes

```
say%k=()while s/\d+/$k{$&}++?$&:(say$&)&&''/ge

```

Try it online!

Input is on one line, whitespace separated.

Output is one element per line with a blank line between groups.
> 0 votes

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