# Question
Title: What are the five most powerful characters in your language?
Choose any five characters your language supports. There are 5! = 5×4×3×2×1 = 120 ways these can be arranged into a 5-character string that contains each character once; 120 permutations.

Choose your characters such that, when each of the 120 strings is run in your language, the 120 outputs produced will be as many unique integers from 1 to 120 (inclusive) as possible.

That is, for each of the 120 permutations of your 5 characters that produce runnable code that outputs a single number, you want the set of all those numbers to match as close as possible to the set of integers from 1 through 120.

So, ideally, your first permutation would output `1`, the next `2`, the next `3`, all the way up to `120`. But that ideal is likely impossible for most languages and characters.

The 5-character strings may be run as:

* a program with no input
* a function with no arguments
* a REPL command

Different strings can be run in different ways if desired

For the output to count, it must be a single integer output in a normal way, such as:

* being printed to stdout
* returned by the function
* the result of the REPL expression

The code should terminate normally (which may involve erroring out as long as the number has been output first). Code that does not run at all is fine, just the (nonexistent) output doesn't count. The numbers output should be in decimal unless a different base is the norm for your language.

**The submission that generates the most distinct numbers from 1 through 120 wins. The earlier submission wins in case of a tie.**

## Notes

* Your 5 characters do not all need to be different, but of course having duplicate characters reduces the effective number of permutations.
* Float outputs such as `32.0` count as well as plain `32`. (But `32.01` would not.)
* Leading zeroes such as `032` count as well as plain `32`.
* Valid outputs should be deterministic and time invariant.
* We are dealing with *characters*, not bytes.

# Example

The characters `123+*` are a reasonable first choice for Python's (or many language's) REPL. The resulting 120 permutations and outputs are:

```
123+* n/a
123*+ n/a
12+3* n/a
12+*3 n/a
12*3+ n/a
12*+3 36
132+* n/a
132*+ n/a
13+2* n/a
13+*2 n/a
13*2+ n/a
13*+2 26
1+23* n/a
1+2*3 7
1+32* n/a
1+3*2 7
1+*23 n/a
1+*32 n/a
1*23+ n/a
1*2+3 5
1*32+ n/a
1*3+2 5
1*+23 23
1*+32 32
213+* n/a
213*+ n/a
21+3* n/a
21+*3 n/a
21*3+ n/a
21*+3 63
231+* n/a
231*+ n/a
23+1* n/a
23+*1 n/a
23*1+ n/a
23*+1 23
2+13* n/a
2+1*3 5
2+31* n/a
2+3*1 5
2+*13 n/a
2+*31 n/a
2*13+ n/a
2*1+3 5
2*31+ n/a
2*3+1 7
2*+13 26
2*+31 62
312+* n/a
312*+ n/a
31+2* n/a
31+*2 n/a
31*2+ n/a
31*+2 62
321+* n/a
321*+ n/a
32+1* n/a
32+*1 n/a
32*1+ n/a
32*+1 32
3+12* n/a
3+1*2 5
3+21* n/a
3+2*1 5
3+*12 n/a
3+*21 n/a
3*12+ n/a
3*1+2 5
3*21+ n/a
3*2+1 7
3*+12 36
3*+21 63
+123* n/a
+12*3 36
+132* n/a
+13*2 26
+1*23 23
+1*32 32
+213* n/a
+21*3 63
+231* n/a
+23*1 23
+2*13 26
+2*31 62
+312* n/a
+31*2 62
+321* n/a
+32*1 32
+3*12 36
+3*21 63
+*123 n/a
+*132 n/a
+*213 n/a
+*231 n/a
+*312 n/a
+*321 n/a
*123+ n/a
*12+3 n/a
*132+ n/a
*13+2 n/a
*1+23 n/a
*1+32 n/a
*213+ n/a
*21+3 n/a
*231+ n/a
*23+1 n/a
*2+13 n/a
*2+31 n/a
*312+ n/a
*31+2 n/a
*321+ n/a
*32+1 n/a
*3+12 n/a
*3+21 n/a
*+123 n/a
*+132 n/a
*+213 n/a
*+231 n/a
*+312 n/a
*+321 n/a

```

There are 36 numbers generated, all luckily within 1 to 120:

```
36, 26, 7, 7, 5, 5, 23, 32, 63, 23, 5, 5, 5, 7, 26, 62, 62, 32, 5, 5, 5, 7, 36, 63, 36, 26, 23, 32, 63, 23, 26, 62, 62, 32, 36, 63

```

However, only 8 of them are unique:

```
36, 26, 7, 5, 23, 32, 63, 62

```

So such a submission would only score 8 out of a maximal 120.

# Answer
# Python3, ~~21~~ 27 values

Characters: `3479%`

Unique numbers: `[1,2,3,4,5,6,7,8,9,11,12,19,20,21,24,29,34,35,36,37,39,43,46,47,49,73,74]`

As it was requested, here are the permutations that fell in the range **\[1, 120\]**. Try it online!

```
347%9   5
349%7   6
34%79   34
34%97   34
374%9   5
379%4   3
37%49   37
37%94   37
394%7   2
397%4   1
39%47   39
39%74   39
3%479   3
3%497   3
3%749   3
3%794   3
3%947   3
3%974   3
437%9   5
439%7   5
43%79   43
43%97   43
473%9   5
479%3   2
47%39   8
47%93   47
493%7   3
497%3   2
49%37   12
49%73   49
4%379   4
4%397   4
4%739   4
4%793   4
4%937   4
4%973   4
734%9   5
739%4   3
73%49   24
73%94   73
743%9   5
749%3   2
74%39   35
74%93   74
793%4   1
794%3   2
79%34   11
79%43   36
7%349   7
7%394   7
7%439   7
7%493   7
7%934   7
7%943   7
934%7   3
937%4   1
93%47   46
93%74   19
943%7   5
947%3   2
94%37   20
94%73   21
973%4   1
974%3   2
97%34   29
97%43   11
9%347   9
9%374   9
9%437   9
9%473   9
9%734   9
9%743   9

```
> 42 votes

# Answer
# Python, 18 numbers

```
237#-

```

Produces as valid results:

```
1, 2, 3, 4, 5, 7, 16, 23, 24, 25, 27, 32, 35, 37, 69, 71, 72, 73

```

---

**EDIT:** I can attest that TuukkaX's solution is optimal for Python. I ran the following code bruteforcing all possible combinations of 5 printable ASCII characters:

```
from itertools import permutations,combinations_with_replacement

def perms(chars):
  result=set()
  for permut in permutations(chars):
    try:
      current=eval(''.join(permut))
      assert str(int(current))==str(current)
      result.add(int(current))
    except:
      pass
  return sum([1 for x in result if 1<=x<=120])

best=1
for c in combinations_with_replacement(' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~',5):
    string=''.join(c)
    r=perms(string)
    if r>=best:
        best=r
        print(r,string,end='\n')

```

The results (after running for almost 7 hours) showed that the optimal solution is in fact 27 different numbers, produced by three different solutions all using four numbers and mod (`%`): `%3479`, `%5679` and `%5789`.
> 34 votes

# Answer
# 05AB1E, ~~27~~ ~~38~~ 41 numbers

```
4·>Ìn

```

Generates the unique numbers:

`[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 25, 27, 32, 33, 34, 35, 36, 37, 38, 49, 50, 52, 54, 64, 65, 66, 67, 72, 73, 74, 81, 83, 98, 100, 101, 102]`

Uses the constant `4` with the operations `+1`, `+2`, `*2` and `^2`.
> 33 votes

# Answer
# Java 8, ~~2~~ 4 numbers

```
n->12  // returns 12
n->21  // returns 21
n1->2  // returns 2
n2->1  // returns 1

```

Weren't expecting a Java answer, were you?

This is a lambda that can only be arranged one of two ways (and with any two different digits!) for a total of two unique numbers. Everything else isn't a valid lambda.

Actually improved the answer, thanks to some help from comments! Didn't see that 0 wasn't valid, and forgot that variables could, y'know, be more than one character. We've got 4!

## An even worse solution

`()->1`

But, on the bright side, two unique answers in Java!
> 24 votes

# Answer
# Jelly, ~~26~~ ~~30~~ 32 numbers

```
‘’3²Ḥ

```

This (and its anagrams) are full programs, that take no input, and produce output on standard output.

The outputs from the 120 programs are, in the order Jelly generates them if you ask it to generate permutations of the program:

```
018 036 06 03 09 03 18 116 116 117 125 135 06 03 14 15 13 22 19 13 24
28 33 42 018 036 06 03 09 03 -132 -164 -120 -119 -149 -137 26 43 18 17
33 24 -19 13 -216 -210 53 44 18 36 30 31 49 63 18 36 10 9 25 17 18 19
18 17 18 18 36 48 36 26 36 36 06 03 14 15 13 22 06 03 -18 -17 -13 -24
06 07 06 05 06 06 03 12 03 -14 03 03 09 03 14 18 03 12 09 03 -116 -110
23 14 09 015 09 05 09 09 03 12 03 -14 03 03

```

If you just take the unique outputs in numerical order, you get:

```
-216 -210 -164 -149 -137 -132 -120 -119 -116 -110 -24 -19 -18 -17 -14 -13
03 05 06 07 09 10 12 13 14 15 17 018 19 22 23 24 25 26 28 30 31 33 036 42
43 44 48 49 53 63 116 117 125 135

```

Many of these are too small, and 135 is too large, but there are still 32 that are in range.

The basic idea is to use mostly monadic instructions (in a program with only monads and nilads, these each just transform the previous output), and ones that allow the value to diverge quickly. The exception is with `3`, which is a nilad (the constant value 3). If it appears at the start of the program, all the operations will be done from 3. If it appears in the middle, it splits the program into two halves, each of which outputs an integer (and as they each print to standard output, the results end up getting concatenated, thus giving us "concatenate" as an additional operation to generate numbers).

The operations we have here, in the context the program generates them in, are: increment; decrement; constant 3; square; and double. Increment and decrement are unfortunately opposites, and decrement has an unfortunate tendency to produce a -1 or -2 in the first section (thus leading to a negative number overall), but this still gave a greater spread of outputs than the other things I tried. In particular, we get a pretty good spread of both the first and second halves of the number (note that the first half can be the null string, if `3` is the first character in the program).
> 19 votes

# Answer
# Brachylog, 26 numbers

```
3+*^-

```

This outputs the following numbers: `[2,3,4,5,6,7,8,9,10,16,17,18,19,20,25,26,30,31,32,35,36,37,48,49,63,64]`

### Explanation

* `3` is the integer 3, obviously.
* `+` is increment
* `*` is double
* `^` is square
* `-` is decrement

There are a lot of situations where the program simply errors: for example `*+^3-` errors because it asks *“Take 0, double it, increment, square, the result of that square is 3, decrement”* which is obviously wrong.

Any program that ends with `3` will either output `3` or not work.

Any program that starts with `*3` will loop infinitely because of a bug (Brachylog is attempting to find a list of sublists which product result in 3 which is not possible).
> 16 votes

# Answer
## JavaScript, 27 numbers

Very similar to TuukkaX's answer, with another set of digits.

```
5789%

```

The 27 distinct values are:

```
589 %   7 -> 1
987 %   5 -> 2
978 %   5 -> 3
879 %   5 -> 4
985 %   7 -> 5
958 %   7 -> 6
975 %   8 -> 7
 95 %  87 -> 8
  9 % 875 -> 9
 97 %  85 -> 12
 89 %  75 -> 14
 95 %  78 -> 17
 78 %  59 -> 19
 79 %  58 -> 21
 98 %  75 -> 23
 87 %  59 -> 28
 89 %  57 -> 32
 97 %  58 -> 39
 98 %  57 -> 41
 57 %  98 -> 57
 58 %  97 -> 58
 59 %  87 -> 59
 75 %  98 -> 75
 78 %  95 -> 78
 79 %  85 -> 79
 85 %  97 -> 85
 87 %  95 -> 87

```
> 16 votes

# Answer
## Vim, 16 numbers

```
i1234

```

print

```
1, 2, 3, 4, 12, 13, 14, 21, 23, 24, 31, 32, 34, 41, 42, 43

```
> 11 votes

# Answer
# Brain-Flak 1

```
(())#

```

Brain-Flak requires balanced braces, so a 5 character program is only valid if one of the characters starts a comment. That leaves us with 4 characters to work with. Of those, 2 have to be `(` and `)` otherwise nothing would get pushed onto the stack. Those have to go first and 4th with the comment last (`(..)#`). Now we can put `()`, `{}`, `<>`, or `[]` inside. `{}`, `<>`, and `[]` each evaluate to 0, but `()` is 1. That means that `(())#` is the only 5 character string that produces a valid Brain-Flak program.

Try it Online!

If the question were instead "what are the *6* most powerful characters", the answer would be `(){}[]` as Brain-Flak is turing complete using only this subset.
> 11 votes

# Answer
# Jelly, 33 numbers

```
Ḥ23+c

```

double(left);
`2` literal 2;
`3` literal 3;
`+` add(left, right); and
`c` choose(left, right), i.e. number of ways to choose right objects from a collection of left objects.

Numbers yielded with an example program:

```
 1 +32Ḥc   18 3Ḥc2+    45 2+3Ḥc
 2 c3Ḥ+2   20 2+Ḥc3    47 23c+Ḥ
 3 c2Ḥ+3   21 2Ḥ+3c    48 c+23Ḥ
 4 +2Ḥc3   22 3Ḥc+2    53 2c+Ḥ3
 5 2+3cḤ   23 23cḤ+    56 3Ḥ+2c
 6 3c+2Ḥ   24 cḤ+23    63 c+2Ḥ3
 8 2c+3Ḥ   30 3+c2Ḥ    65 32c+Ḥ
 9 3c2+Ḥ   32 32cḤ+    66 c+32Ḥ
12 +3cḤ2   33 cḤ+32    72 3c+Ḥ2
13 +2cḤ3   36 3+Ḥc2    82 c+3Ḥ2
15 +3Ḥc2   42 cḤ3+2   120 3+2Ḥc

```

I tried to choose easy to parse ones, but some are rare and slightly strange to parse, for example `23` is:

```
23cḤ+: (23 c (2 * 23)) + 23 = (23 c 46) + 23 = 0 + 23 = 23

```

...and `72` and `13` use implicit printing:

```
3c+Ḥ2: z = (3 c 0) + (3 * 2); print(z); z = 2; print(z)
       z =    1    +    6   ; print(z); z = 2; print(z)

+2cḤ3: z = (0 + 2) c (2 * 0); print(z); z = 3; print(z)
       z =    2    c    0   ; print(z); z = 3; print(z)
       z =         1        ; print(z); z = 3; print(z)

```

---

Note that `Ḥ34+c` also produces `33` unique values in `[1,120]`.
> 11 votes

# Answer
# IA-32 machine code, 8 numbers

Hexadecimal byte values:

```
2c 40 48 b0 c3

```

The code is run as a function returning the value in `al`.

Valid permutations:

```
b0 2c c3 xx xx => 2c (mov al, 2c)

b0 40 c3 xx xx => 40 (mov al, 40)

b0 48 c3 xx xx => 48 (mov al, 48)

b0 2c 40 c3 48 => 2d (mov al, 2c; inc eax)

b0 2c 48 c3 40 => 2b (mov al, 2c; dec eax)

b0 40 48 c3 2c => 3f (mov al, 40; dec eax)

b0 48 40 c3 2c => 49 (mov al, 48; inc eax)

b0 48 2c 40 c3 => 8 (mov al, 48; sub al, 40)

```

I did a brute-force search, with the following constraints:

* The first byte is `b0` \- to initialize the `al` register
* The last byte is `c3` \- return; following bytes are discarded
* Possible opcode bytes are:
    + 0x04 - `add`
    + 0x0c - `or`
    + 0x24 - `and`
    + 0x2c - `sub`
    + 0x34 - `xor`
    + 0xd4 - `aad`
    + 0x40 - `inc`
    + 0x48 - `dec`

This leaves only 3 changeable bytes with a maximum of 15 possible results. Of these, a maximum of 9 can be distinct (in fact, this happens for only one set of bytes!). One of the values is out of range, so this leaves 8 values. There is another set of bytes

```
34 40 48 b0 c3

```

which also gives 8 distinct values - the programs are the same, except for `sub` replaced by `xor`, which makes two of the possible outputs identical.

All other sets of bytes give 7 or fewer possible results.
> 11 votes

# Answer
## Hexagony, 13 numbers

```
)24!@

```

These are the 13 printable numbers with one possible program for each of them:

```
)!@24 1
2!@)4 2
2)!@4 3
4!@)2 4
4)!@2 5
)2!@4 12
)4!@2 14
24!@) 24
24)!@ 25
2)4!@ 34
42!@) 42
42)!@ 43
4)2!@ 52

```

The programs should be fairly self-explanatory. `@` terminates the program, `!` prints the current value, `)` increments it, `2` and `4` append themselves to the current value (where the initial value is `0`). The actual hexagonal layout of the source code is irrelevant here, the programs can simply be read from left to right.

This *should* be optimal, although instead of `2` and `4` you can pick any pair digits `x` and `y` such that `2 ≤ x ≤ y-2`.

The above solution was found by (almost exhaustive) brute force, requiring one `!` (otherwise it wouldn't print anything), one `@` (otherwise the program won't terminate), and filling the remaining three characters with any (repeated) combination from the following set of characters:

```
#[]\/_|<>)!0123456789$

```

I can't see how any of the other commands could possibly generate more variety.
> 9 votes

# Answer
# Octave, 18

This was found using a bruteforce search on the symbols `*+-/0123456789:;<\^|~%`. But it took way too long to compute...

```
-139%

```

Possible outputs:

```
1, 2, 3, 4, 6, 8, 9,13,16,19,22,31,38,39,88,91,92,93

```
> 8 votes

# Answer
# Perl, 27 numbers

`3479%`

Perl doesn't have a built-in REPL, so you can use `re.pl` from Devel::REPL.

Results:

```
%9743 -> N/A
9%743 -> 9
97%43 -> 11
974%3 -> 2
9743% -> N/A
%7943 -> N/A
7%943 -> 7
79%43 -> 36
794%3 -> 2
7943% -> N/A
%7493 -> N/A
7%493 -> 7
74%93 -> 74
749%3 -> 2
7493% -> N/A
%7439 -> N/A
7%439 -> 7
74%39 -> 35
743%9 -> 5
7439% -> N/A
%9473 -> N/A
9%473 -> 9
94%73 -> 21
947%3 -> 2
9473% -> N/A
%4973 -> N/A
4%973 -> 4
49%73 -> 49
497%3 -> 2
4973% -> N/A
%4793 -> N/A
4%793 -> 4
47%93 -> 47
479%3 -> 2
4793% -> N/A
%4739 -> N/A
4%739 -> 4
47%39 -> 8
473%9 -> 5
4739% -> N/A
%9437 -> N/A
9%437 -> 9
94%37 -> 20
943%7 -> 5
9437% -> N/A
%4937 -> N/A
4%937 -> 4
49%37 -> 12
493%7 -> 3
4937% -> N/A
%4397 -> N/A
4%397 -> 4
43%97 -> 43
439%7 -> 5
4397% -> N/A
%4379 -> N/A
4%379 -> 4
43%79 -> 43
437%9 -> 5
4379% -> N/A
%9734 -> N/A
9%734 -> 9
97%34 -> 29
973%4 -> 1
9734% -> N/A
%7934 -> N/A
7%934 -> 7
79%34 -> 11
793%4 -> 1
7934% -> N/A
%7394 -> N/A
7%394 -> 7
73%94 -> 73
739%4 -> 3
7394% -> N/A
%7349 -> N/A
7%349 -> 7
73%49 -> 24
734%9 -> 5
7349% -> N/A
%9374 -> N/A
9%374 -> 9
93%74 -> 19
937%4 -> 1
9374% -> N/A
%3974 -> N/A
3%974 -> 3
39%74 -> 39
397%4 -> 1
3974% -> N/A
%3794 -> N/A
3%794 -> 3
37%94 -> 37
379%4 -> 3
3794% -> N/A
%3749 -> N/A
3%749 -> 3
37%49 -> 37
374%9 -> 5
3749% -> N/A
%9347 -> N/A
9%347 -> 9
93%47 -> 46
934%7 -> 3
9347% -> N/A
%3947 -> N/A
3%947 -> 3
39%47 -> 39
394%7 -> 2
3947% -> N/A
%3497 -> N/A
3%497 -> 3
34%97 -> 34
349%7 -> 6
3497% -> N/A
%3479 -> N/A
3%479 -> 3
34%79 -> 34
347%9 -> 5
3479% -> N/A

```

Brute-forced using the following program:

```
use strict;
use warnings 'all';
use 5.010;

use Algorithm::Combinatorics qw(combinations);
use Algorithm::Permute;
use Scalar::Util::Numeric qw(isint);

my @chars = ( 0..9, qw(+ - * / . ; ' " \ @ $ # ! % ^ & ( ) { } =) );
my $iter  = combinations(\@chars, 5);
my $max   = 0;
my @best;

while (my $combo = $iter->next) {
    my $count = count_valid([@$combo]);

    if ($count > $max) {
        $max  = $count;
        @best = @$combo;
    }
}

say "$max -> @best";

sub count_valid {
    my ($chars) = @_;

    my $iter = Algorithm::Permute->new($chars);
    my %results;

    while (my @perm = $iter->next) {
        no warnings;
        my $val = eval join '', @perm;
        use warnings 'all';

        $results{$val} = 1 if isint($val) && $val > 0 && $val <= 120;
    }

    return scalar keys %results;
}

```
> 7 votes

# Answer
# R, ~~15~~ 18 numbers

Not a huge number but it may be the best that can be done with R. I searched all combinations of digits `0..9`, operators `+ - * / ^` and the comment char `#`, and the following eight all output 18 unique integers between 1 and 120.

```
-#146
-#157
-#237
-#238
-#256
-#267
-#278
-#378
-#467
-#568

```

As an example, let's take `-#146`. Here are the 18 integers we can get:

```
1#-46      = 1
6-4#1      = 2
4-1#6      = 3
4#-16      = 4
6-1#4      = 5
6#-14      = 6
14-6#      = 8
16-4#      = 12
14#-6      = 14
16#-4      = 16
41-6#      = 35
41#-6      = 41
46-1#      = 45
46#-1      = 46
61-4#      = 57
61#-4      = 61
64-1#      = 63
64#-1      = 64

```

If you're curious about the (ugly) code used to test all the possible combinations, here it is. It outputs the number of unique integers between 1 and 120 for each character combination of length 5 to a file called "datafile" in the current working directory.

```
allchars = c("1","2","3","4","5","6","7","8","9","0","+","-","*","/","^")
apply(gtools::combinations(n=15, r=5, v=allchars, repeats.allowed=TRUE),
      1,
      function(chars) {
        x = apply(apply(e1071::permutations(length(chars)),
                        1,
                        function(i) chars[i]
                        ),
                  2,
                  paste, collapse=""
            )
        u = unique(x)
        o = as.numeric(unlist(sapply(u, function(i) eval(try(parse(t=i),TRUE)))))

        f = factor(unique(o[o<=120 & o>=1 & o%%1==0]))
        write(paste(nlevels(f), paste(chars, collapse="")), "datafile", append=TRUE)
      }
)

```
> 7 votes

# Answer
# Octave, 15 numbers

Not much to brag about, but this is the best I can get in Octave:

```
124+%

```

It gives the numbers:

```
1    2    3    4    5    6   12   14   16   21   24   25   41   42   43

```

---

I got 16 too, but it seems it's identical to Sefa's answer...

```
1234%

1    2    3    4   12   13   14   21   23   24   31   32   34   41   42   43

```
> 5 votes

# Answer
# PHP, 15 numbers

```
1230\r

```

Uses the fact that php prints anything outside its tags verbatim (without using this you can do exactly 1 number with something like `<?=1;`). Also uses an actual carriage return character rather than `\r`.

Creates (sorted, removed leading 0s):

```
 1 1 2 2 3 3 10 10 12 12 12 12 13 13 13 13 20 20 21 21 21 21 23 23 23 23 30 30 31 31 31 31 32 32 32 32 102 102 103 103 120 120 123 123 123  123  130  130  132  132  132  132  201  201  203  203  210  210  213  213  213  213  230  230  231  231  231  231  301  301  302  302  310  310  312  312  312  312  320  320  321  321  321  321  1023  1023  1032  1032  1203  1203  1230  1230  1302  1302  1320  1320  2013  2013  2031  2031  2103  2103  2130  2130  2301  2301  2310  2310  3012  3012  3021  3021  3102  3102  3120  3120  3201  3201  3210  3210

```

of which the valid unique numbers are:

```
1 2 3 10 12 13 20 21 23 30 31 32 102 103 120

```
> 4 votes

# Answer
# Cubix, 7 numbers

```
"2)@O

```

Outputs these numbers:

```
")O2@ ->  1
")2O@ ->  2
"2)O@ ->  3
2"O@) -> 41
)"O@2 -> 50
2"O)@ -> 64
2")O@ -> 65

```

---

Any valid Cubix program for this challenge has to have an `O` to output an integer, and an `@` to terminate the program (Cubix has never even heard of "errors"). This gives us 3 chars to play around with to generate the most outputs. Furthermore, because of the way Cubix arranges code on a cube, the first char will be useless unless one of the others is a directional char.

The most efficient way I have found to generate multiple numbers is to use `"` to push a string of char-codes to the stack. With careful rearrangement, we can fit several chars in the last spot and simply output their char-codes. By using `)` to increment the top item, we can create extra outputs from several of these arrangements.

There are two basic program types in use here. The first is this:

```
"2)O@

```

which expands to

```
  "
2 ) O @
  .

```

The resulting program pushes `2` to the stack, increments it with `)`, outputs with `O`, and terminates with `@`.

The second is this:

```
2")O@

```

which expands to

```
  2
" ) O @
  .

```

The resulting program pushes the char-codes of `)`, `O`, and `@`, increments the last one with `)`, outputs with `O`, and terminates with `@`.
> 4 votes

# Answer
# Groovy, 10 Numbers

Man JVM solutions are BAD for this... Who knew?

```
1200+

```

Results in:

```
[3, 10, 12, 17, 21, 30, 66, 80, 102, 120]

```

Wait, what? How the hell does it make 17 you ask?

```
20+10 is 30.
0120+ is invalid.
2+001 is 3.
201+0 is 201.
2+100 is 102.
0+012 is 10.
21+00 is 21.
02+01 is 3.
0210+ is invalid.
10+20 is 30.
200+1 is 201.
0+210 is 210.
1200+ is invalid.
0201+ is invalid.
+0021 is 17.
1+002 is 3.
210+0 is 210.
100+2 is 102.
010+2 is 10.
00+12 is 12.
20+01 is 21.
01+20 is 21.
0+120 is 120.
+0120 is 80.
0+021 is 17.
+1020 is 1020.
0012+ is invalid.
02+10 is 12.
102+0 is 102.
012+0 is 10.
+2100 is 2100.
12+00 is 12.
00+21 is 21.
+2001 is 2001.
+0210 is 136.
+1200 is 1200.
1020+ is invalid.
0102+ is invalid.
2001+ is invalid.
001+2 is 3.
+0012 is 10.
2+010 is 10.
0021+ is invalid.
10+02 is 12.
2100+ is invalid.
+0201 is 129.
2010+ is invalid.
020+1 is 17.
1002+ is invalid.
+2010 is 2010.
1+020 is 17.
1+200 is 201.
01+02 is 3.
+1002 is 1002.
120+0 is 120.
0+102 is 102.
+0102 is 66.
002+1 is 3.
0+201 is 201.
021+0 is 17.

```

Trade secret, in Groovy/Java integers preceded with a 0 are octals. Code I used for testing Groovy answers incase someone wants to beat me:

```
("1200+" as List).permutations().collect{
    it.join()
}.collect {
    print "$it is "
    x=-1;
    try {
        x=Eval.me(it);
        println "$x."
    } catch(Exception e) {
        println "invalid."
    }
    x<=120?x:-1;
}.unique().sort();

```
> 4 votes

# Answer
# TI-BASIC, 12 numbers

```
23+4!

```

There is most likely a better combination, but I wasn't able to find it.

All \\$24\\$ valid permutations are as follows:

```
23+4!   -> 47
24+3!   -> 30
2+4!3   -> 74
2+3!4   -> 26
2!4+3   -> 11
2!+43   -> 45
2!+34   -> 36
2!3+4   -> 10
32+4!   -> 56
34+2!   -> 36
3+4!2   -> 51
3+2!4   -> 11
3!4+2   -> 26
3!+42   -> 48
3!+24   -> 30
3!2+4   -> 16
43+2!   -> 45
42+3!   -> 48
4+2!3   -> 10
4+3!2   -> 16
4!2+3   -> 51
4!+23   -> 47
4!+32   -> 56
4!3+2   -> 74

```

Of which there are \\$12\\$ unique values:

\\$10,11,16,26,30,36,45,47,48,51,56,74\\$
> 4 votes

# Answer
# Befunge, 11 numbers

Befunge is a bit limited because it only supports single digit literals. So the best I could come up with was 11 numbers, assuming the calculation must leave us with one and only one number on the stack.

**Best characters:** `358*%`

**Generated numbers:** (just one example of each)

```
58*3% => 1
358*% => 3
38*5% => 4
538*% => 5
35*8% => 7
835*% => 8
385%* => 9
583%* => 10
358%* => 15
53%8* => 16
35%8* => 24

```
> 3 votes

# Answer
# \>\<\>, 6 numbers

Gained 2 numbers thanks to *Teal Pelican*

```
1ln";

```

Produces the unique numbers `[1, 4, 5, 49, 59, 108]`

We need `n` to print a number.
We need `;` to terminate.

That leaves us only 3 chars to work with.

A few different combinations of `value` & `operator` together with `"` confirmed to produce 6 unique values, but I haven't found anything better than that.
> 3 votes

# Answer
# MATL, 15 numbers

```
0123%

```

`%` is the comment operator, so it will "cut" in all possible places once, helping to create all possible combinations of the given digits and subsets of them:

```
1
2
3
10
12
13
20
21
23
30
31
32
102
103
120

```
> 3 votes

# Answer
# J , 16 Numbers

```
1234]

```

Nothing fancy, just tested `1234` with all the 1-character verbs that were reasonable. `]` selects its right argument.

The unique numbers produced are

```
0 4 3 34 43 2 24 42 23 32 234 243 324 342 423 432 1 14 41 13 31 134 143 314 341 413 431 12 21 124 142 214 241 412 421 123 132 213 231 312 321 1234 1243 1324 1342 1423 1432 2134 2143 2314 2341 2413 2431 3124 3142 3214 3241 3412 3421 4123 4132 4213 4231 4312 4321

```

of which 16:

```
4 3 34 43 2 24 42 23 32 1 14 41 13 31 12 21

```

Are in the range \[1,120\].

Tested with

```
# (#~e.&(>:i.120)) ~. (". :: 0:)"1 (A.~ i.@!@#) '1234]'

```
> 3 votes

# Answer
# Japt, 41 numbers

Pretty much just trial and error so there may be a better solution. Uses integers `3` & `4` and the Japt shortcuts for squaring, adding `1` & multiplying by `2`. All 120 programmes output an integer `>0` but only 78 are `<=120` and only 41 of those are unique.

```
34²ÄÑ

```

Generates the numbers:

```
1,3,4,5,6,7,8,9,13,14,17,20,21,26,27,29,30,31,32,33,34,35,36,37,38,39,42,43,44,45,47,56,59,68,69,72,73,86,87,92,93

```

View the list of numbers or the collection of valid programmes

---

## Explanation

A few things to note about Japt that are relevant here are:

1. If a programme doesn't start with (in this case) one of the digits then the first input variable `U`, which defaults to `0`, is automatically inserted at the beginning,
2. If either or both of the digits immediately follow one of the shortcuts for a mathematical operation then they are appended to it (e.g. `3Ä4 = 3+14 = 17` and, similarly, `4Ñ² = 4*2**2 = 16`), and,
3. If one of the digits immediately follows the `²` then the `²` and everything before it are, essentially, ignored.

Explanations for a few of the programmes (producing `1`, `3`, `37` and `93`, respectively):

```
²Ñ34Ä  :Square 0, multiply by 234 and add 1
4ÄÑ²3  :Add 1 multiplied by 2 squared to 4, ignore that and return the 3
3²Ä4Ñ  :Square 3 and add 14 multiplied by 2
4Ñ3Ä²  :Multiply 4 by 23 and add 1 squared

```
> 3 votes

# Answer
# Python, 16 numbers

```
1234#

```

Uses # to comment out all unnecessary numbers.
> 2 votes

# Answer
# dc, 19 numbers

```
*3zO+

```

Output is on top of stack, and errors (including stack underflow) are ignored. The valid permutations are:

```
+O3*z:   1
+O*3z:   2
+Oz3*:   3
O*z3+:   4
O*3z+:   5
+O3z*:   6
+z3*O:  10
3*zO+:  11
3*Oz+:  12
Oz3*+:  13
O3z*+:  16
+3Oz*:  20
3Oz*+:  23
+zO3*:  30
O3*z+:  31
Oz+3*:  33
3Oz+*:  36
Oz3+*:  40
O3z+*:  50
TOTAL COUNT = 19 numbers

```

Here's the Python program I used to show those results:

```
#!/usr/bin/python

import sys
import itertools
import subprocess

if len(sys.argv[1]) != 5:
    print("Invalid input")
    sys.exit(1)

devnull = open("/dev/null", 'w');

r = dict()
for s in itertools.permutations(sys.argv[1]):
    p = "".join(s)
    try:
        e = (subprocess.check_output(['dc', '-e', p, '-e', 'p'], stderr=devnull))
        e = int(e)
        if 0 < e <= 120:
            r[e] = p
    except e:
        pass

for i in sorted(r):
    print("%5s: %3d" % (r[i], i))

print("TOTAL COUNT = %d numbers" % len(r))

```

---

Two other strings which give the same score of 19 are `32d+*` and `*4zO+`.
> 2 votes

# Answer
## Smalltalk, 26 numbers

```
1235r

```

Explanation: 12r35 is a notation for using radix 12, and is thus 3\*12+5.
This can be verified in Squeak:

```
((Array streamContents: [:s |
    '1235r'  permutationsDo: [:each |
        | eval |
        eval := [Compiler evaluate: each] ifError: [nil].
        (eval isInteger and: [eval >=1 and: [eval <= 120]]) ifTrue: [s nextPut: each copy -> eval]]])
  collect: #value as: Set) sorted

```

gives:

```
#(1 2 3 5 28 31 33 37 38 41 42 47 55 58 63 66 67 68 71 76 82 86 105 107 108 116)

```

If we replace last line with:

```
    sorted: #value ascending)

```

we then get the expressions:

```
'235r1' -> 1
'253r1' -> 1
'325r1' -> 1
'352r1' -> 1
'523r1' -> 1
'532r1' -> 1
'135r2' -> 2
'153r2' -> 2
'315r2' -> 2
'351r2' -> 2
'531r2' -> 2
'513r2' -> 2
'125r3' -> 3
'152r3' -> 3
'215r3' -> 3
'251r3' -> 3
'521r3' -> 3
'512r3' -> 3
'123r5' -> 5
'132r5' -> 5
'213r5' -> 5
'231r5' -> 5
'321r5' -> 5
'312r5' -> 5
'23r15' -> 28
'25r13' -> 28
'13r25' -> 31
'15r23' -> 33
'32r15' -> 37
'35r12' -> 37
'5r123' -> 38
'12r35' -> 41
'5r132' -> 42
'15r32' -> 47
'52r13' -> 55
'53r12' -> 55
'5r213' -> 58
'12r53' -> 63
'5r231' -> 66
'13r52' -> 67
'31r25' -> 67
'21r35' -> 68
'35r21' -> 71
'25r31' -> 76
'5r312' -> 82
'5r321' -> 86
'51r23' -> 105
'53r21' -> 107
'21r53' -> 108
'23r51' -> 116

```

I wanted to cheat and define a method r in Integer as

```
Integer>>r
    ^self \\ 120 + 1

```

Unfortunately, the compiler chops on 1235r because it recognizes an unfinished number with radix rather than a message r sent to 1235...
I could easily change the compiler too, but it's a bit too much of a cheat to my taste.
> 2 votes

# Answer
# Runic Enchantments, 19 numbers

```
234p@

```

Essentially 3 literals, the pow operator, and a "print the entire stack and terminate" command. `234p@` prints 812 (3^4 conxatenated with a 2). Full permutation list, note that `@` has been replaced by `ak@` in order to generate a newline between each result and a `>` has been added to insure that each line executes independently. Note also that the outputs are not in the same order as the programs that generated them (as some programs may terminate more quickly).

Many permutations print nothing (eg. `@234p` or `p234@`), but 19 do result in output within the allowable range.

Numbers possible (and one possible program that results in it; `.` indicates that those positions may be any of the remaining characters as it isn't executed):

```
2@...        2
3@...        3
4@...        4
23p@.        8
32p@.        9
42p@.       16
32@..       23
42@..       24
23@..       32
43@..       34
24@..       42
34@..       43
23p4@       48
32p4@       49
43p@.       64
34p@.       81
423p@       84
432p@       94

```
> 2 votes

# Answer
# APL, 27 numbers

The best set after brute-forcing all permutations of characters that made sense.

```
5789⊤

```

All permutations

```
[ 7958⊤ ] N/A
[ 98⊤75 ] 75
[ 985⊤7 ] 7
[ 98⊤57 ] 57
[ 8⊤957 ] 5
[ 8⊤795 ] 3
[ 8⊤975 ] 7
[ ⊤9587 ] N/A
[ 897⊤5 ] 5
[ 75⊤89 ] 14
[ 785⊤9 ] 9
[ 78⊤59 ] 59
[ 8579⊤ ] N/A
[ 8597⊤ ] N/A
[ 79⊤85 ] 6
[ ⊤5789 ] N/A
[ ⊤5879 ] N/A
[ 7⊤895 ] 6
[ 7⊤985 ] 5
[ 578⊤9 ] 9
[ 59⊤87 ] 28
[ 9758⊤ ] N/A
[ 7589⊤ ] N/A
[ 7598⊤ ] N/A
[ ⊤8759 ] N/A
[ 789⊤5 ] 5
[ ⊤8597 ] N/A
[ 9⊤578 ] 2
[ 8975⊤ ] N/A
[ 9⊤587 ] 2
[ 7859⊤ ] N/A
[ 57⊤98 ] 41
[ 895⊤7 ] 7
[ 89⊤57 ] 57
[ 978⊤5 ] 5
[ 58⊤97 ] 39
[ 8759⊤ ] N/A
[ 875⊤9 ] 9
[ 87⊤59 ] 59
[ 975⊤8 ] 8
[ 97⊤58 ] 58
[ ⊤7958 ] N/A
[ 7⊤859 ] 5
[ 85⊤79 ] 79
[ 5⊤798 ] 3
[ 5⊤978 ] 3
[ 95⊤87 ] 87
[ 859⊤7 ] 7
[ 8⊤579 ] 3
[ 759⊤8 ] 8
[ ⊤9758 ] N/A
[ 7⊤958 ] 6
[ 587⊤9 ] 9
[ 59⊤78 ] 19
[ 879⊤5 ] 5
[ 9875⊤ ] N/A
[ ⊤7589 ] N/A
[ ⊤5798 ] N/A
[ ⊤5978 ] N/A
[ 95⊤78 ] 78
[ 7985⊤ ] N/A
[ 987⊤5 ] 5
[ 8⊤597 ] 5
[ ⊤9857 ] N/A
[ 89⊤75 ] 75
[ 758⊤9 ] 9
[ ⊤7895 ] N/A
[ ⊤7985 ] N/A
[ 9578⊤ ] N/A
[ 9587⊤ ] N/A
[ 5798⊤ ] N/A
[ 5789⊤ ] N/A
[ 798⊤5 ] 5
[ ⊤9785 ] N/A
[ ⊤9875 ] N/A
[ 5⊤789 ] 4
[ 5⊤879 ] 4
[ 57⊤89 ] 32
[ 598⊤7 ] 7
[ 9785⊤ ] N/A
[ ⊤8579 ] N/A
[ 78⊤95 ] 17
[ ⊤8957 ] N/A
[ 9⊤758 ] 2
[ 8957⊤ ] N/A
[ 9⊤857 ] 2
[ 5978⊤ ] N/A
[ 5987⊤ ] N/A
[ 9⊤785 ] 2
[ 9⊤875 ] 2
[ 7895⊤ ] N/A
[ 579⊤8 ] 8
[ 97⊤85 ] 85
[ 589⊤7 ] 7
[ 8795⊤ ] N/A
[ ⊤7598 ] N/A
[ ⊤8795 ] N/A
[ ⊤8975 ] N/A
[ 7⊤589 ] 1
[ 857⊤9 ] 9
[ ⊤5897 ] N/A
[ ⊤5987 ] N/A
[ 85⊤97 ] 12
[ 8⊤759 ] 7
[ 958⊤7 ] 7
[ 5⊤897 ] 2
[ 5⊤987 ] 2
[ 5879⊤ ] N/A
[ 5897⊤ ] N/A
[ 75⊤98 ] 23
[ 795⊤8 ] 8
[ 79⊤58 ] 58
[ ⊤9578 ] N/A
[ 7⊤598 ] 3
[ 58⊤79 ] 21
[ 597⊤8 ] 8
[ 87⊤95 ] 8
[ 9857⊤ ] N/A
[ ⊤7859 ] N/A
[ 957⊤8 ] 8

```
> 2 votes

# Answer
# Vyxal, 27 values

```
45²›d

```

And the numbers produced are:

```
[12, 11, 10, 5, 6, 50, 100, 25, 26, 36, 9, 8, 4, 32, 64, 16, 17, 92, 91, 110, 109, 90, 108, 45, 54, 46, 55]

```
> 2 votes

# Answer
# OIL, 5 numbers

`\n4120` (`\n` is the newline character)

For an OIL program to print anything, the print command (4) must be alone on a line. That can't be if the newline isn't somewhere inbetween the other characters. If the first character is a `4`, followed by a newline and the other characters, the program will either:

* print `0` (because it will try to print e.g. the 120th cell, which is empty, which is mapped to 0)
* print `4`, because e.g. `021` isn't a number (in OIL) and mapped to 0, and the 0th line contains a 4.

If the program starts with three characters, followed by the newline and then 4, the program prints the first line, because a missing argument from a non-existing line maps to 0. There are 6 possible permutations of that, but only four of them are integers in the range (012, 021, 102, 120).

The 5 legal numbers possible with this set of characters is therefore `4`, `012`, `021`, `102`, and `120`.

---

I believe this is the best possible set of numbers for OIL. I found another set with which I get 4 numbers (0, 1, 2, 21): `\n\n124`.
> 1 votes

# Answer
## Mathematica, 16 numbers

```
;1234

```

Not very interesting, but I can't seem to find anything better using arithmetic. The only thing that *might* work is using `!` for factorial or double factorial, but this is so prone to generating massive numbers that it's impossible to brute force.

The 16 numbers (in range) that can be generated from the above 5 characters are:

```
1, 2, 3, 4, 12, 13, 14, 21, 23, 24, 31, 32, 34, 41, 42, 43

```
> 1 votes

# Answer
## W, 5 numbers

```
3S*4+

```

The permutations can be printed by the following program, given that the Python interpreter is in your PATH. Don't count the preceding & trailing 0's as they are simply return codes:

```
import itertools
import os
for i in list(itertools.permutations("3S*4+",5)):
    os.system("echo "+''.join(list(i))+">code.w")
    os.system("W.py code.w []")
    print("END CASE")

```

This, with all the trailing/preceding 0's removed, is this.

Uniquified: `{'43', '34', '3', '12', '4'}`
> 1 votes

# Answer
# Pyth, 18 numbers

```
579 t

```

Another challenge where being infix rather than prefix would be nice. This uses the space to "hide" some of the numbers and the decrement to get more numbers.

Here's all of the outputs.

```
[ 57 t9 ] => '57'
[ 57t 9 ] => '57\n8'
[ 59 t7 ] => '59'
[ 59t 7 ] => '59\n6'
[ 5 7t9 ] => '5\n8'
[ 5 9t7 ] => '5\n6'
[ 5 t79 ] => '5'
[ 5 t97 ] => '5'
[ 5t7 9 ] => '5\n6'
[ 5t9 7 ] => '5\n8'
[ 5t 79 ] => '5\n78'
[ 5t 97 ] => '5\n96'
[ 75 t9 ] => '75'
[ 75t 9 ] => '75\n8'
[ 79 t5 ] => '79'
[ 79t 5 ] => '79\n4'
[ 7 5t9 ] => '7\n8'
[ 7 9t5 ] => '7\n4'
[ 7 t59 ] => '7'
[ 7 t95 ] => '7'
[ 7t5 9 ] => '7\n4'
[ 7t9 5 ] => '7\n8'
[ 7t 59 ] => '7\n58'
[ 7t 95 ] => '7\n94'
[ 95 t7 ] => '95'
[ 95t 7 ] => '95\n6'
[ 97 t5 ] => '97'
[ 97t 5 ] => '97\n4'
[ 9 5t7 ] => '9\n6'
[ 9 7t5 ] => '9\n4'
[ 9 t57 ] => '9'
[ 9 t75 ] => '9'
[ 9t5 7 ] => '9\n4'
[ 9t7 5 ] => '9\n6'
[ 9t 57 ] => '9\n56'
[ 9t 75 ] => '9\n74'
[  57t9 ] => '8'
[  59t7 ] => '6'
[  5t79 ] => '78'
[  5t97 ] => '96'
[  75t9 ] => '8'
[  79t5 ] => '4'
[  7t59 ] => '58'
[  7t95 ] => '94'
[  95t7 ] => '6'
[  97t5 ] => '4'
[  9t57 ] => '56'
[  9t75 ] => '74'
[  t579 ] => ''
[  t597 ] => ''
[  t759 ] => ''
[  t795 ] => ''
[  t957 ] => ''
[  t975 ] => ''
[ t57 9 ] => '56'
[ t59 7 ] => '58'
[ t5 79 ] => '4'
[ t5 97 ] => '4'
[ t75 9 ] => '74'
[ t79 5 ] => '78'
[ t7 59 ] => '6'
[ t7 95 ] => '6'
[ t95 7 ] => '94'
[ t97 5 ] => '96'
[ t9 57 ] => '8'
[ t9 75 ] => '8'
[ t 579 ] => '578'
[ t 597 ] => '596'
[ t 759 ] => '758'
[ t 795 ] => '794'
[ t 957 ] => '956'
[ t 975 ] => '974'
{96, 97, 4, 5, 6, 7, 8, 9, 74, 75, 78, 79, 56, 57, 58, 59, 94, 95}

```
> 1 votes

# Answer
# Brainfuck, 3

```
<>+-.

```

It can produce -1 (or whatever the wraparound value is in the implementation), 0, or 1.

Unfortunately, since output in a loop is not counted, Brainfuck is very limited, since any loop is guaranteed to end on a 0, and the character space is too small to have both loop operators, +,-, output, and a register shift.
> -3 votes

---
Tags: code-challenge, number, permutations, source-layout, integer
---


title: Verify a Superpowerset

text:
# Question
Title: Verify a Superpowerset
A superpowerset (analogous to superpermutation) on \\$n\\$ symbols is a string over the alphabet \\$\\{1,2,...,n\\}\\$ such that every subset of \\$\\{1,2,...,n\\}\\$ appears as a substring (in some order). For instance, `12342413` is a superpowerset on four symbols because it contains `1`, `2`, `3`, `4`, `12`, `13`, `41`, `23`, `24`, `34`, `123`, `241`, `413`, `234`, `1234`.

The lengths of the shortest such strings and some examples are given in this sequence: A348574

## The Challenge

Given a string composed of \\$n\\$ unique symbols (and, optionally, \\$n\\$), output whether it is a superpowerset on \\$n\\$ symbols.

## Rules

* This is so the shortest answer in bytes wins.
* Assume only valid input will be given.
* Assume \\$n\\$ is greater than \\$0\\$
* Input and output can assume whatever form is most convenient, e.g. the series of symbols can be a string, a list, an integer, a set of n bitmasks, etc, so long as it is indicated in the answer. Additionally, anything may be used as a symbol provided it is distinct from all the other symbols.

## Test Cases

```
In: 1234
Out: False

In: 1
Out: True

In: 11111111
Out: True

In: 123
Out: False

In: 1234512413
Out: False

In: 12342413
Out: True

In: 123424133333333
Out: True

In: 1234567214573126431523674256147325716357
Out: True

In: 122331
Out: False

```

# Answer
> 5 votes
# Jelly, 9 bytes

```
ŒPḊfƑɓẆṢ€

```

A dyadic Link accepting the alphabet size, `N`, on the left and the candidate string, `S`, on the right as a list of integers that yields `1` if the string is a superpowerset of that alphabet size.

**Try it online!**

### How?

```
ŒPḊfƑɓẆṢ€ - Link: integer, N; list of integers, S
ŒP        - powerset of [1..N]
  Ḋ       - dequeue - removes the empty list
     ɓ    - new chain with swapped arguments:
      Ẇ   -   all sublists of S
       Ṣ€ -   sort each
    Ƒ     - is the dequeued powerset invariant under:
   f      -   filter keep the sorted sublists

```

# Answer
> 4 votes
# Python, 90 bytes

```
lambda i,n:f(*i)+2>>2**n
f=lambda a,*i,k=0:1<<(l:=k|1<<a-1)|(i>()and(l>k)*f(*i,k=l)|f(*i))
```

Attempt This Online!

Takes a list of integers `i` and the integer `n` as arguments. Uses bitmasks to avoid lengthy *frozensets*.

Using one less layer of bitmasks might be a bit clearer, but costs a byte.

# Answer
> 4 votes
# Husk, ~~11~~ ~~10~~ ~~8~~ 7 bytes

*Edit: -2 bytes after inspiration from caird coinheringaahing, and then -1 byte by stealing the I/O idea from emanresu A's answer*

```
-ṁPQ¹Ṗu

```

Try it online!

Outputs a list of an empty list (`[[]]`) if a superpowerset, or a list containing nonempty lists otherwise.

```
      u       # Get uniqe elements of input,
     Ṗ        # and get all subsequences
-             # now remove from this
 ṁP           # all permutations of
   Q¹         # all contiguous sublists of the input.

```

# Answer
> 3 votes
# Jelly, 10 bytes

```
ŒPŒ!ẇ€SɗƇƑ

```

Try it online!

Takes \\$n\\$ on the left, and a list of integers up to \\$n\\$ on the right

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

```
Length[{}⋃Union/@Subsequences@#]==2^#2&

```

Try it online!

# Answer
> 3 votes
# Vyxal, 9 bytes

```
ÞSvs?Uṗ$F

```

Try it Online!

Returns a list containing the empty list (`⟨ ⟨ ⟩ ⟩`) for truthy and a list containing nonempty lists for falsy.

```
ÞS        # Sublists...
  vs      # Sort each
       $F # Remove from...
      ṗ   # Powerset of...
    ?U    # Unique symbols of input

```

# Answer
> 2 votes
# Ruby, ~~83~~ 76 bytes

```
->l,n{!(z=*1..n).uniq{|w|[*z.combination(w)]-l.each_cons(w).map(&:sort)}[1]}

```

Try it online!

# Answer
> 2 votes
# Wolfram Language (Mathematica), 84 bytes

```
And@@(Subsequences@s~ContainsAny~Permutations@#&/@Subsets@Union[s=IntegerDigits@#])&

```

Try it online!

# Answer
> 1 votes
# Python 3, 98 bytes

```
lambda i,s:len(f(i))>>s
f=lambda i,*t:i and{1,len(i)>len({*i})or frozenset(i),*f(*t,i[1:],i[:-1])}

```

Try it online!

Takes a list of numbers and the number of symbols.

In python, you can't have a set of sets, instead you have to use the immutable frozenset. The algorithm is quite simple, just check every substring. To do that, you can use the vararg-sublist trick, where f is called for every sublist of the input in length order. The recursion is stopped when we encounter the empty list. This means that if this is really a superpowerset, then the resulting set will contain \\$2^s\\$ elements (every subset, except the empty set plus a 1). We can then use a bitshift to check for that condition.

It's possible to replace `frozenset(i)` with `(*{*i},)` for -5 bytes, but I'm not sure if the order of the set expansion is well defined.

# Answer
> 1 votes
# JavaScript (ES10), 86 bytes

*Saved 14 bytes thanks to @tsh!*

Expects an array of symbols. Returns \\$0\\$ or \\$1\\$.

```
a=>(g=a=>new Set(a).size)(a.flatMap(x=>p=[...p,y=1<<x].map(v=>v&y?0:v|y),p=[0]))>>g(a)

```

Try it online!

# Answer
> 1 votes
# Factor \+ `math.combinatorics math.unicode`, 74 bytes

```
[ dup members all-subsets rest swap all-subseqs [ natural-sort ] map ⊂ ]

```

Try it online!

*"Is the power set of the input's alphabet a subset of the sorted sub-sequences of the input?"*

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

```
â à eÈá d@øX

```

Try it

```
â         - unique elements
  à       - combinations
    eÈ    - all?
á           * permutations of that combination
  d@        * any?
    øX        in input U

```

# Answer
> 1 votes
# 05AB1E, ~~8~~ 7 bytes

```
êæIŒ€{K

```

Only takes the string as input. Outputs `[""]` for truthy, and a list with additional items as falsey, which is allowed because of the flexible rule "*output can assume whatever form is most convenient. ... Additionally, anything may be used as a symbol provided it is distinct from all the other symbols.*" (taken from *@emanresuA*'s Vyxal answer).
If a truthy/falsey value was mandatory, a trailing `g` (length) could be added, because only `1` is truthy in 05AB1E.

Try it online or verify all test cases.

**Explanation:**

```
ê        # Sorted uniquify the digits in the (implicit) input
 æ       # Pop and push its powerset list
  I      # Push the input
   Œ     # Pop and push its substrings
    €{   # Sort each substring
      K  # Remove those from the powerset-list
         # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Charcoal, 53 bytes

```
Ｗ⁻⪪θ¹υ⊞υ⌊ι≔⟦⟧ηＦＬθＦＥ⊕ι✂θκ⊕ιＦ⬤κ⁼¹№κλ⊞ηΣＸ²Ｅκ⌕υμ¬⁻…¹Ｘ²Ｌυη

```

Try it online! Link is to verbose version of code. Takes a string as input and outputs a Charcoal boolean, i.e. `-` for a superpowerset, nothing if not. Explanation:

```
Ｗ⁻⪪θ¹υ⊞υ⌊ι

```

Get the unique elements of the input.

```
≔⟦⟧η

```

Start collecting integers representing sets of unique elements.

```
ＦＬθＦＥ⊕ι✂θκ⊕ι

```

For each substring, ...

```
Ｆ⬤κ⁼¹№κλ

```

... if this substring only contains unique elements, then ...

```
⊞ηΣＸ²Ｅκ⌕υμ

```

... collect a bitmask of the unique elements.

```
¬⁻…¹Ｘ²Ｌυη

```

Check that all possible bitmasks were collected.

34 bytes for a specific input format:

```
ＦＬηＦＥ⊕ι✂ηκ⊕ιＦ⬤κ⁼¹№κλ⊞ηΣＸ²κ¬⁻…¹Ｘ²θη

```

Try it online! Link is to verbose version of code. Uses the same algorithm, but takes an integer `n` and a list of integers less than `n` as input.

---
Tags: code-golf, combinatorics
---


title: Chunk Sort a Sequence

text:
# Question
Title: Chunk Sort a Sequence
Your task is to input a sequence of integers and chunk sort it. You may assume the input list can always be chunked into groups of 1, 2, and 3.

# Definition

*Chunk sorting* (a term I made up for the purpose of this challenge) is the action of first chunking a sequence into groups of 1, 2, and 3 in a cycle and then sorting each group.

# Test cases

```
[1, 2, 3, 4, 5, 6, 7, 8, 9] => [[1], [2, 3], [4, 5, 6], [7], [8, 9]]
[5, 9, -2, 8, -6, 4, 5, 9, 1] => [[5], [-2, 9], [-6, 4, 8], [5], [1, 9]]
[8, 3, -1, 6, -8, 7, -1] => [[8], [-1, 3], [-8, 6, 7], [-1]]

```

# Scoring

The shortest code wins!

# Rules

No standard loopholes, please.

# Answer
> 12 votes
# Jelly, ~~10~~ 8 bytes

```
3Rṁx@JṢƙ

```

Try it online!

## How it works

```
3Rṁx@JṢƙ - Main link. Takes L on the left
3R       - [1,2,3]
  ṁ      - Mold to length L, repeating
     J   - Yield [1,2,...,len(L)]
   x@    - Repeat 1 once, 2 twice, 3 thrice, 4 once, 5 twice, etc.
      Ṣƙ - Sort chunks of L, grouped by the elements of [1,2,2,3,3,3,4,...]

```

# Answer
> 12 votes
# Ruby, 49 bytes

```
->l{x=5;l.chunk{441[(x+=1)%12]}.map{|a,b|b.sort}}

```

Try it online!

Literally: chunk, then sort.

The magic number 441 is a bitmask with 1,2,3 binary digits alternatively seto to 1 or 0:

```
000 11 0 111 00 1

```

Since there are only 2 binary digits, I can't make it 3 chunks, so I make it 6 and so I use mod 12 to rotate.

# Answer
> 8 votes
# 05AB1E, 10 bytes

```
3LI∍£€{ʒgĀ

```

Try it online or verify all test cases.

Or alternatively (thanks to *@ovs* for `N6%tò`):

```
.yN6%tò}€{

```

Try it online or verify all test cases.

**Explanation:**

```
3L          # Push list [1,2,3]
  I∍        # Extend the [1,2,3] list to the same size as the input-list
    £       # Split the (implicit) input-list into those parts,
            # which includes trailing empty lists at the end
     €{     # Sort each inner list
       ʒgĀ  # Remove the empty lists:
       ʒ    #  Filter the list of lists:
        gĀ  #   Check if the list-length is not 0
            # (after which the result is output implicitly)

.y          # Adjacent group the (implicit) input-list by:
  N         #  Push the 0-based group-by index
   6%       #  Modulo-6
     t      #  Take the square-root of that
      ò     #  Round it to the nearest integer
 }€{        # After the group-by: sort each inner list
            # (after which the result is output implicitly)

```

The `N6%tò` results in the sequence `[0,1,1,2,2,2,0,1,1,2,2,2,...]`, causing the adjacent group-by to split the input-list into parts of sizes `[1,2,3,1,2,3,...]`, which is what we want.

---

The first program could be 9 bytes if the input-length is guaranteed to be \\$n\>1\\$:

```
3LI∍£€{Ô¨

```

See all test cases, and how it unfortunately fails for `[1]`. (Adding `Ć` after `I` would fix that edge-case, but unfortunately we'll then have another 10-bytes alternative.)

# Answer
> 8 votes
# Husk, 6 bytes

```
mOC¢ḣ3

```

Try it online!

**How?**

```
    ḣ3      # 1..3
   ¢        # repeated infinitely;
  C         # now split the input into sublists
            # of these lengths (discarding any
            # extra, unused lengths);
m           # finally, for each sublist:
 O          # sort it.

```

# Answer
> 7 votes
# Jelly, 10 bytes

```
J%6B§=1ÄṢƙ

```

Try It Online!

```
J%6B§=1ÄṢƙ  Main Link
J           [1, 2, 3, ..., len(input)]
 %6         [1, 2, 3, 4, 5, 0, 1, 2, 3, ...]
   B        Binary; [[1], [1, 0], [1, 1], [1, 0, 0], [1, 0, 1], [0], ...]
    §       Sum each; [1, 1, 2, 1, 2, 0, ...]
     =1     Equal to 1?; [1, 1, 0, 1, 0, 0, ...]
       Ä    Cumulative sum; [1, 2, 2, 3, 3, 3, 4, 5, 5, 6, 6, 6, ...]
        Ṣƙ  Sort chunks of the input grouped based on equal elements on the left side

```

# Answer
> 7 votes
# Python, ~~86~~ ~~65~~ 63 bytes

```
def f(a,i=0):
 for x in a:a[i:i%3-~i]=sorted(a[i:i%3-~i]),;i+=1
```

Attempt This Online!

Modifies the list in-place; kinda cursed.

# Answer
> 7 votes
# Python 2, 50 bytes

```
f=lambda a,i=1:a and[sorted(a[:i])]+f(a[i:],i%3+1)

```

Try it online!

# Answer
> 6 votes
# Pip `-xp`, ~~24~~ ~~23~~ 18 bytes

```
$AL:SN*_^@^13Ma<>6

```

Replit! Or, here's a 20-byte equivalent in Pip classic (with a header to simulate the -x flag): Try it online!

### Explanation

```
$AL:SN*_^@^13Ma<>6
              a     First command-line arg
               <>6  Group into length-6 chunks
             M      Map this function to each chunk:
          ^13        Split 13 into a list of digits [1;3]
       _^@           Split the argument at those indices
    SN*              Sort each sublist using numeric comparison
$AL:                Fold the result on append-list (flattening by one level)

```

# Answer
> 6 votes
# , ~~70~~ ~~63~~ 59 bytes

```
function(a)Map(sort,split(a,rep(l<-seq(!a)-1,l%%3+1)[l+1]))

```

Try it online!

# Answer
> 6 votes
# Wolfram Language (Mathematica), 53 bytes

```
Sort/@TakeList[#,i=0;UpTo@Mod[++i,4]&/@#]/.{}->Set@$&

```

Try it online!

-6 bytes thanks to @alephalpha
-3 bytes thanks to @theorist
-2 bytes thanks to @att

# Answer
> 5 votes
# JavaScript (ES6), 61 bytes

*-4 and -1 thanks to Arnauld*

```
x=>(f=n=>x+x&&[x.splice(0,++n).sort((w,z)=>w-z),...f(n%3)])``

```

# Answer
> 4 votes
# , 59 bytes

```
function(x,`*`=`[<-`)Map(sort,split(x,x*rep(seq(x),x*1:3)))

```

Try it online!

# Answer
> 4 votes
# Retina, 24 bytes

```
5,6,S`,
%,,2S`,
%N`[^,]+

```

Try it online! Explanation:

```
5,6,S`,

```

Split the input into groups of up to six values. Limits are 0-indexed in Retina 1, so the first six values are numbered `0` to `5` and therefore the comma after the sixth value is also numbered `5`, however subsequent splits are every six commas as expected, until the end of the input.

```
%,,2S`,

```

Split each group into groups of 1, 2 and 3 values (if possible). The syntax `,,2` is short for `,2,2` so it only splits on the first and third comma; `,2` would be a range and so would also split on the second comma.

```
%N`[^,]+

```

Sort the values in each group.

# Answer
> 4 votes
# Bash 4.4.23, 142 bytes

```
f()(
i=1
a=("$@")
while [ ${#a[@]} -gt 0 ]
do
r=$r"["$(printf "%s\n" "${a[@]:0:$i}" |sort -n)"]"
a=("${a[@]:${i}}")
((i=i==3?1:i+1))
done
echo $r
)

```

Try it here!

## Explanation

```
i=1                                           > used to keep track of chunk size
a=("$@")                                      > transforms the parameters as an array
while [ ${#a[@]} -gt 0 ]                      > while there is still some elements to "chuck sort"
do
r=$r[$(printf "%s\n" "${a[@]:0:$i}"|sort -n)] > construct the final result by picking only the required chunk from the array and sorts it. Store sort result in r and ad some delimiters
a=("${a[@]:${i}}")                            > remove processed chunk from the array
((i=i==3?1:i+1))                              > set size of next chunk
done
echo $r

```

# Answer
> 4 votes
# BQN, ~~24~~ ~~23~~ ~~22~~ ~~21~~ 20 bytes

*-1 thanks to Dominic van Essen*

```
∧¨⊢⊔˜¯1+`(0=∾↑↕3)⥊˜≠

```

Anonymous tacit function that takes an array of numbers as its right argument. Run it online!

### Explanation

The explanation uses an example argument of `⟨ 8 3 ¯1 6 ¯8 7 ¯1 ⟩`:

```
∧¨⊢⊔˜¯1+`(0=∾↑↕3)⥊˜≠
          (      )      Generate the array ⟨ 1 1 0 1 0 0 ⟩:
               ↕3         Range(3): ⟨ 0 1 2 ⟩
              ↑           Prefixes: ⟨ ⟨⟩ ⟨ 0 ⟩ ⟨ 0 1 ⟩ ⟨ 0 1 2 ⟩ ⟩
             ∾             Join: ⟨ 0 0 1 0 1 2 ⟩
           0=              Equal 0: ⟨ 1 1 0 1 0 0 ⟩
                  ⥊˜   Reshape it to
                     ≠  the length of the argument: ⟨ 1 1 0 1 0 0 1 ⟩
        +`              Cumulative sum
      ¯1                starting at -1: ⟨ 0 1 1 2 2 2 3 ⟩
    ⊔˜                 Using that list as a categorizer, group
   ⊢                   the argument: ⟨ ⟨ 8 ⟩ ⟨ 3 ¯1 ⟩ ⟨ 6 ¯8 7 ⟩ ⟨ ¯1 ⟩ ⟩
∧¨                     Sort each: ⟨ ⟨ 8 ⟩ ⟨ ¯1 3 ⟩ ⟨ ¯8 6 7 ⟩ ⟨ ¯1 ⟩ ⟩

```

# Answer
> 3 votes
# Vyxal, 7 bytes

```
ẏǒʀÞṁvs

```

Try it Online!

I'm way late to the party, but who cares when the program looks like it spells something with heavy skamtebord vibes.

## Explained

```
ẏǒʀÞṁvs
ẏ       # The range [0...len(input)]
 ǒ      # modulo each by 3 to get the chunk sizes
  ʀ     # cast each to range [0...n] for shape
   Þṁ   # mold the input to that, without repeating elements
     vs # sort each sublist

```

# Answer
> 2 votes
# , 24 15 bytes

```
<@/:~/.~#$#\##\

```

Try it online!

# Answer
> 2 votes
# Charcoal, ~~48~~ 40 bytes

```
≔⮌ＡθＷθ⊞υＥ⊕﹪Ｌυ³⊟θＩＥυ✂⟦⌊ι⁻Σι⁺⌊ι⌈ι⌈ι⟧⁰χ⁻⁴Ｌι

```

Try it online! Link is to verbose version of code. Explanation: Charcoal really struggles here as it has no variable length split, flatten or sort primitive (at least not on TIO).

```
≔⮌Ａθ

```

Reverse the input array.

```
Ｗθ

```

Repeat until the input array has been chunked.

```
⊞υＥ⊕﹪Ｌυ³⊟θ

```

Create a chunk of size depending on the number of chunks so far.

```
ＩＥυ✂⟦⌊ι⁻Σι⁺⌊ι⌈ι⌈ι⟧⁰χ⁻⁴Ｌι

```

For each chunk, get the minimum, middle and maximum elements, but skip the middle if the chunk's size is less than `3` and skip the maximum if its size is less than `2`.

Previous 48-byte version didn't require the input to be completely chunkable:

```
ＷθＦ³«⊞υ✂θ⁰⊕κ≔✂θ⊕κＬθ¹θ»ＩＥΦυι✂⟦⌊ι⁻Σι⁺⌊ι⌈ι⌈ι⟧⁰χ⁻⁴Ｌι

```

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

```
Ｗθ

```

Repeat until the input is empty.

```
Ｆ³«

```

Take three chunks.

```
⊞υ✂θ⁰⊕κ

```

Save the chunk.

```
≔✂θ⊕κＬθ¹θ

```

Remove the chunk from the input.

```
»ＩＥΦυι✂⟦⌊ι⁻Σι⁺⌊ι⌈ι⌈ι⟧⁰χ⁻⁴Ｌι

```

For each non-empty chunk, get the minimum, middle and maximum elements, but skip the middle if the chunk's size is less than `3` and skip the maximum if its size is less than `2`.

# Answer
> 2 votes
# HBL, 17 bytes

```
?.(1(%(0,.))('?(2,.)(+(?(<,<),
).1

```

Try it!

### Explanation

The first line is a recursive function that does most of the work. It takes two arguments, a list and an integer, where the integer represents the current chunk size (1, 2, or 3).

```
?.(1(%(0,.))('?(2,.)(+(?(<,<),
?                               If
 .                              Argument 1
                                is truthy (non-empty):
  (1                             Construct a list from
        ,                         Argument 2
      (0  )                       Take that many elements of
         .                        Arg1
    (%     )                      Sorted
                                 prepended to
            ('?                   Recursive call with two arguments:
               (2,.)               Drop (arg2) elements of arg1
                                  and
                    (+             Increment
                      (?            If
                          ,         Arg2
                        (<  )       is less than
                           <        3:
                             ,       Arg2
                                    Else, 0
                                Else, empty list

```

Then the main function on the second line is simply:

```
)    Call the previous function with these arguments:
 .    Argument 1 of the main function
     and
  1   1

```

# Answer
> 2 votes
# Stax, 6 bytes

```
£ñ+Ü5▬

```

Run and debug it

# Answer
> 2 votes
# C (gcc), ~~73~~ 70 bytes

```
l;f(a,n)int*a;{for(l=0;n;n-=l,a+=l,l%=3)qsort(a,++l,4,L"\x62b078bǃ");}

```

Try it online!

Inputs a pointer to an array of integers and its length (because pointers in C carry no length info).
Chunk sorts the array in place.

# Answer
> 2 votes
# Haskell, ~~76~~ 71 bytes

```
import Data.List
f=(%)1
n%[]=[]
n%x=sort(take n x):(mod n 3+1)%drop n x

```

Try it Online!

-5 bytes thanks to xnor

Calling f on a list chunk sorts it.

# Answer
> 2 votes
# tinylisp, ~~194~~ ~~170~~ 146 bytes

```
(load library
(d C(q((L P)(i L(c(map head(zip L(1to P)))(i(e P 3)(C(t(t(t L)))1)(i(e P 2)(C(t(t L))3)(C(t L)2))))(
(d S(q((L)(map merge-sort(C L 1

```

Try it online!

-24 thanks to DLosc suggesting implementing `take` instead of the hodge-podge mess of `c`s I was using before. -24 again by implementing `take` more golfily.

# Answer
> 1 votes
# Pari/GP, 53 bytes

```
a->i=0;c=2;[vecsort(a[i+1..i=j+1])|b<-a,#a>j=i+c++%3]

```

Try it online!

# Answer
> 0 votes
# PHP, 131 bytes

```
function(&$a){for($a=array_chunk($a,3),$i=-1;$a[++$i];sort($a[$i]))!$a[$i][1]|$i%3?:array_splice($a,$i,0,[[array_shift($a[$i])]]);}

```

Try it online!

This is a first take, it feels awfully long, there has to be a better way.. damn these "array\_" prefixes!

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


title: Pristine Polyglots

text:
# Question
Title: Pristine Polyglots
As the title says, you are to create a pristine program in as many languages as possible. A pristine program, taken from here, is:

> Let's define a *pristine program* as a program that does not have any errors itself but will error if you modify it by removing any contiguous substring of \\$N\\$ characters, where \\$1 \le N \< \text{program length}\\$.
>
> For example, the three character Python 2 program
>
> ```
> `8`
>
> ```
>
> is a pristine program <sup>(thanks, Sp)</sup> because all the programs resulting from removing substrings of length 1 cause errors (syntax errors in fact, but any type of error will do):
>
> ```
> 8`
> ``
> `8
>
> ```
>
> and also all the programs resulting from removing substrings of length 2 cause errors:
>
> ```
> `
> `
>
> ```
>
> If, for example, ``8` had been a non-erroring program then ``8`` would not be pristine because **all** the results of substring removal must error.

You are to write, in as many languages as possible, a pristine program.

* Your program must produce a non-empty output when unaltered.

+ This output can be anything you like, can vary depending on different inputs, or anything else, so long as, when run, unaltered and with no/empty input, it produces a non-empty output (note that `0`, or your language's null value is non-empty).
    + The output may **not** be to STDERR (or your language's equivalent), as this would fall under the definition of an "erroring program" below.
    + The output does not have to consistent across languages, or when executed twice in the same language.
* Your code must work in a minimum of two distinct languages and must be at least 2 bytes long
* Different versions of a language do not count as different languages. Therefore, Python 2 and Python 3 are considered the same language.
* Your program must be pristine in all languages used
* An error is defined as anything that causes the program to either entirely fail to run or to terminate with a nonzero exit code after a finite amount of time.
* This is , so the answer with the most languages wins

+ In case of a tie breaker, the *longest* solution, in bytes, wins

---

I would also be interested in proofs of impossibility for certain pairs/groups of languages. If you find a particularly interesting proof, please leave it in the comments (or, preferably, a link to the full write up), and I'll invite you to post as an answer so I can award it a bounty if I agree that its especially interesting. Please **do not** post these proofs unless I have said I will award it a bounty, I don't want all the answers to be filled by such proofs and actual answers be buried. Proofs posted without me asking you to will not be considered valid

# Answer
> 7 votes
# 6 languages

## Bash, 4 bytes

```
echo

```

Try it online!

## Zsh, 4 bytes

```
echo

```

Try it online!

## fish, 4 bytes

```
echo

```

Try it online!

## tcsh, 4 bytes

```
echo

```

Try it online!

## ksh, 4 bytes

```
echo

```

Try it online!

## , 4 bytes

```
echo

```

Try it online!

Kicking things off with a boring one. If I understand the rules, I think it's legal though.

The shells are clear enough and output a newline. Removing any contiguous substring will result in "command not found".

In J, `echo` is a built in function, and prints its argument with a newline appended. J doesn't have 0-argument functions, so you have to call it with something. However, anything works, including the empty string `''`, which is the conventional choice for calling a function when the argument doesn't matter.

# Answer
> 1 votes
# 3 languages, 5 bytes

## Ruby

`print`

## Python 2

`print`

## Perl 5

`print`

# 2 languages, 20 bytes

## Scala

`System.out.println()`

## Javascript

`System.out.println()`

This does about the same thing that the answer by Jonah does, except because a lot less languages use `print`, it features 3 or 2 languages. Still felt like answering however.

These all print the empty string.

---
Tags: polyglot, code-bowling, rosetta-stone, pristine-programming
---


title: Russian Roulette

text:
# Question
Title: Russian Roulette
Write a program which plays Russian Roulette!

If the program is started,

* there should be a 5 in 6 chance of it ending normally after printing "I survived!"
* there should be a 1 in 6 chance of the program crashing. (segmentation fault, etc.)

No input, and no other outputs are allowed.

The randomness must be fair: it must have a uniform probability distribution. This means an uninitialized variable (or a RNG without seed) MOD 6 will not be sufficient.

If the solution works with only one dedicated operating system / platform, you will receive a 6 byte penalty to the score.

Shortest code wins, not sooner than 10 days after first valid answer.

# Answer
> 4 votes
# 05AB1E, ~~13~~ 12 bytes

```
6LΩiFë“IÐ–d!

```

-1 byte thanks to *@Emigna*.

05AB1E actually shouldn't be able to error at all, but since the new version of 05AB1E still has some issues compared to the legacy version, I can take that to my advantage to error out for this challenge.

Try it online.

**Explanation:**

```
6L          # Create the list [1,2,3,4,5,6]
  Ω         # Get a random choice from this list
   i        # If it is 1:
    F       #  Do a ranged loop, which currently results in a "(RuntimeError) Could not
            #  convert  to integer." error when no argument is given
   ë        # Else:
    “IÐ–d!  #  Push dictionary string "I survived!" (which is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `“IÐ–d!` is `"I survived!"`.

# Answer
> 11 votes
## PHP 38 bytes

```
<?~$$s[rand(+$s=sssss,5)]?>I survived!

```

Placing a `+` before a non-numeric string will evaluate to `0`. Should `rand(0,5)` return `5`, `$s[rand(0,5)]` will be the empty string (since `$s` is only five characters long), and subsequently `$$s[rand(0,5)]` will be an uninitialized variable. Attempting to take the inversion will halt on Unsupported Operand Type. Any other value, `0-4` will return `s`, and because `$s` is defined, you will survive.

Note: as of php version 4.2.0, the random number generator is seeded automatically.

# Answer
> 7 votes
## Dyalog APL - 25 22 21 20 Charachters

```
'I Survived!'⊣1÷6⊤?6

```

Prints `DOMAIN ERROR` as the error, due to division by zero.

Shortest non-division by zero solution I could come up with is 23 characters.

```
('I Survived!'1)[~6⍷?6]

```

It throws an `INDEX ERROR`

Try it here

APL Font here

# Answer
> 7 votes
## R 30

```
"I survived!"[6*runif(1)<5||Z]

```

One time out of six, it will throw an error: `Error: object 'Z' not found`

# Answer
> 6 votes
## Python, 96

```
from ctypes import*
from random import*
randrange(5)or pointer(c_int())[9**9]
print'I survived!'

```

If `randrange(5)` returns 0, then python will crash due to a segmentation fault.

# Answer
> 6 votes
## Ruby, 24-28

```
p rand(6)<5?"I survived!":1/0

```

Approx each 6 time, there is a `ZeroDivisionError`

There is even a shorter version with 24 characters (Thanks to ugoren and histocrat):

```
6/rand(6);p"I survived!"

```

If you don't accept the `"` in the output, then I need 3 more characters. The first option (`puts`) adds a newline, the second (`$><<`) makes no newline:

```
6/rand(6);puts"I survived!"
6/rand(6);$><<"I survived!"

```

There is a question about random number in ruby at SO. The seed with `srand` is automatically called with the seed being from the current time if it wasn't already called. (see Julians comment)

---

Primo had the idea for an extra bonus to those solutions which don't rely on division by zero.

My first solution can be shortened (28 characters) with a `undefined local variable or method ``a' for main:Object (NameError)`

```
p rand(6)<5?"I survived!":a

```

# Answer
> 6 votes
## J, 18

```
'I survived!'[q:?6

```

Failing with `domain error` when trying to factorise 0.

# Answer
> 5 votes
## vba, 27

```
?1/int(6*rnd),"I Survived!"

```

used in immediate window.
On failure, an error window stating:
appears

# Answer
> 5 votes
# Befunge - 48 chars

```
 v >91+"!devi"v
/?>?<v"I surv"<
 / / :
   :,_@#

```

Befunge's only randomness is the `?` operator, which sends you heading in one of four posible directions (`1/4` chance). By blocking one or two directions, you have `1/3` or `1/2` chance, and by combining these, you get `1/6` chance to get out of the program "alive".

The program crashes by doing a divive-by-zero. I guess it's implementation-specific what will happen (on Wikipedia it says the program should ask for the desired answer), but befungee.py sort of crashes, or exits angrily:

```
$ for i in {1..6} ; do ./befungee.py roulette.befunge ; done
Error (1,2): integer division or modulo by zero
Error (3,2): integer division or modulo by zero
Error (1,2): integer division or modulo by zero
I survived!
Error (0,1): integer division or modulo by zero
I survived!

```

# Answer
> 4 votes
## C, 67 65 62 chars

`rand()%8` doesn't lose fairness. Division crashes for `t=0`, gives true for 1 and 2 (retry), gives false for 3..7 (survived).
**EDIT:** The previous version used a temporary variable, which ended up completely unneeded. `2/(rand()%8)` implements both needed conditions.

```
main(){
        for(srand(time(0));2/(rand()%8););
        puts("I survived!");
}

```

# Answer
> 4 votes
# T-SQL 56 44 40 + 6

```
 if 1/cast(ceiling(rand()*6)-1as int)<2print'I Survived!'

```

Credit Sean Cheshire for calling out cast as unnecessary

```
 if 1/ceiling(rand()*6-1)<2print'I Survived!'

```

Credit personal message from Sean Cheshire for suggestion to change ceiling to floor.

```
 if 1/floor(rand()*6)<1print'I Survived!'

```

Death Err Msg: Msg 8134, Level 16, State 1, Line 3 Divide by zero error encountered.

# Answer
> 3 votes
## **Python, 70 characters**

With inspiration from grc's answer.

```
from random import*
if randrange(5)<1:exec'()'*9**5
print'I survived!'

```

randrange(5) returns a value between 0 and 5.
If it returns a 0, Python crashes while attempting to exec(ute) a string of code that contains 9^5 sets of parentheses.

# Answer
> 3 votes
Using the usual divide by zero method:

Perl 5.8 Version

```
1/(int rand 6)&&print "I survived!"

```

Perl 5.10 Version

```
1/(int rand 6)&&say "I survived!"

```

On failure, these will display:

```
Illegal division by zero at -e line 1.

```

Using the bless function which is used for creating objects in perl.

Perl 5.8 Version

```
print (int rand 6?"I survived!":bless me);

```

Perl 5.10 Version

```
say (int rand 6?"I survived!":bless me);

```

On failure, these will display:

```
Can't bless non-reference value at -e line 1.

```

# Answer
> 3 votes
## GolfScript, 21 chars

```
,6rand/;'I survived!'

```

Like most of the answers, this one has a one in six chance of crashing with a ZeroDivisionError. The shortest solution I could manage *without* using division by zero is 23 chars:

```
5,6rand=+;'I survived!'

```

which has a 1/6 chance of crashing with `undefined method `+' for nil:NilClass (NoMethodError)`.

(Ps. While developing this, I found what might be a bug in the GolfScript interpreter: code like `0,1>` appears to leave a `nil` value on the stack, which will later crash the program if you try to do anything with that value except pop it off and throw it away with `;`. Unfortunately, the fact that I do need to use the value somehow to trigger a crash means that even exploiting this bug didn't help me get below 23 chars.)

# Answer
> 3 votes
# PHP - 30 bytes

```
<?rand(0,5)?:~[]?>I survived!

```

Requires PHP 5.4+ for the short array syntax, invalid operator idea shamelessly stolen from @primo.

As stated, `rand()` is automatically seeded on first use.

# Answer
> 3 votes
# Befunge, 38

```
v>25*"!devivrus I",,,,,,,,,,,@
?^
v
?^
<1

```

Pretty straight-forward. Crashing is done by pushing 1s onto the stack until it overflows. I made a few attempts at cutting out those 11 commas and replacing them with some more efficient loop to print everything, but couldn't get it under 11 characters.

Note that counting characters in Befunge is a little tricky... For instance there's only one character on the third line, but I'm counting an extra one there since execution could travel through that location.

# Answer
> 3 votes
# Python3.8.10 : 45

```
int(set('12345 ').pop());print('I survived!')

```

I hope it follows the challenge specification. I did some statistics with this method and it seems to have a uniform probability distribution (the program crashes 10416 times over 60000 calls from the console)

# Answer
> 2 votes
**Javascript, 42**

`(Math.random()*6|0)?alert('i survived!'):b`

The bitwise or floors the result of the multiplication thus a value between 0 and 5 results. 0 gets implictly casted to false, so in 5 of 6 cases the alert appears in the 6th case a certain `b` is referenced, crashing the process.

# Answer
> 2 votes
## CMD Shell (Win XP or later), 40 +6

I'm only doing this one because DOS is not something that should even be thought of for code golf, and the whitespace is important

```
set/a1/(%RANDOM% %% 6)&&echo I Survived!

```

On failure, it will print

> Divide by zero error.

# Answer
> 2 votes
# R, 50 44 42 36

```
ifelse(!is.na(sample(c(NA,1:5),1)),'I Survived!',)

```

```
ifelse(floor(runif(1,0,5))>0,'I Survived!',)

```

```
ifelse(floor(runif(1,0,5)),'I Survived!',)

```

```
ifelse(sample(0:5,1),'I Survived!',)

```

Death Err Message:

> Error in ifelse(!is.na(1/sample(c(NA, 1:5), 1)), "I Survived!", ) : argument "no" is missing, with no default

# Answer
> 2 votes
## Emacs-Lisp, 42 characters

```
(if (= (random 6) 5)
    z (message "I survived!")
    )

```

# Answer
> 2 votes
## Javascript, 40 chars

In Javascript the divide-by-zero trick doesn't even work: it just returns Infinity. Therefore, referencing a non-existing variable:

```
alert(6*Math.random()|0?"I survived!":f)

```

Not so short, though fun :)

# Answer
> 2 votes
**PowerShell, 40 Chars**

```
IF(6/(Get-Random -Max 6)){'I Survived!'}

```

On Failure: "Attempted to divide by zero."

# Answer
> 2 votes
# Python, 53 bytes

Here's a short 53 byte python index out of range program:

```
import time
[0][time.time()%6<1]
print("I survived!")

```

# Answer
> 2 votes
# Befunge-98 (FBBI), 28 bytes

```
r?<?
"< <@,ka"I survived!
 =

```

Try it online!

Errors with a segmentation fault.

## Explanation

Befunge-98 adds some extra features (`r`, `k`, and `=`) that can be used to further golf Joe K's Befunge-93 answer.

The first line (`r?<?`) calculates the 1/6 chance. The `r` initially reflects the IP to the left, where it reaches the second `?` and goes in a random direction. If it goes right, the `r` reflects it and it tries again. If it goes up or down, it moves onto the second line, and if it goes left, it moves onto the first `?`. There are three ways the IP can leave, so there is a 1/3 chance it moves onto the first `?`. If it gets there, it again goes in a random direction. If it goes horizontally, it gets reflected (with either `r` or `<`) and tries again. This means that there are only two ways that the IP can leave, and they are equally likely. Either it goes down onto the second line, or it goes up and hits the `=` on the third line.

There is a 1/6 chance that `=` is executed (1/3 from the second `?` times 1/2 from the first). If it is, it does a system-execute call on the stack (which is empty and interpreted as an empty string). FBBI's implementation of this runs a C `system()` call on the empty string, which segfaults.

This leaves a 5/6 chance that the IP reaches the second line. If it does, it gets sent left with `<`, and pushes the string `"!devivrus I"` onto the stack. `ak,` prints the top 11 characters of the stack, outputting `I survived!` Finally, `@` ends the program.

# Answer
> 2 votes
# Jelly, 12 bytes

```
6X’’Xṛ“`:ƭ÷»

```

Try it online!

## Explanation

```
6X            Generate a random number between 1 and 6 inclusive (using python randrange)
  ’’          Decrement it twice
    X         Generate a random number from 1 to the above value. 0 if the value is 0. Error if the value is negative (1/6 chance)
     ṛ        Right Argument; ignore the above value and instead return
      “`:ƭ÷»  "I survived!"

```

Unfortunately, taking the reciprocal of 0, dividing or integer-dividing by 0, and modulo by 0 all give either inf or nan, and don't actually error.

# Answer
> 1 votes
## Groovy, 39

```
1/new Random().next(6);print"I survived!"

```

Picks a random number between 0 and 5 inclusive. If 0, throws a divide by zero exception.

# Answer
> 1 votes
**Java, 149**

```
public class R{public static void main(String[]s){int[]a={1,1,1,1,1};System.out.println(a[new java.util.Random().nextInt(7)]>0?"I survived!":"");}}

```

Fails with an "Array out of bounds" error. Managed to shave a few characters by using anonymous Random object (no imports).

# Answer
> 1 votes
## Python (56), Haskell (77)

This crashes with an IndexError when the generated number is 1:

```
from random import*
print['I survived!'][1/randint(1,7)]

```

The Haskell solution has the same idea:

```
import System.Random
main=putStrLn.(["I survived!"]!!).div 1=<<randomRIO(1,6)

```

# Answer
> 1 votes
## Python, 59 55 53, 65 59 56

```
import os
1/(ord(os.urandom(1))%6)
print"I survived!"

```

`ZeroDivisionError` when `ord(os.urandom(1))%6` evaluates to 0

```
import os
print(["I survived!"]*5)[ord(os.urandom(1))%6]

```

`IndexError` when `ord(os.urandom(1))%6` evaluates to 5

# Answer
> 1 votes
## VBA - 39/46

I don't love Sean Cheshire's numeric output (though still a good answer, it technically fails the `No input, and no other outputs are allowed.` from the spec...), plus he uses `/0`, so here are my alternatives:

```
?Mid("I Survived!",IIf(Int(6*Rnd),1,0))

```

This resolves to a `Run-time error '5': Invalid procedure` when trying to reach character 0 (VBA is 1-based indexing).

```
n="I Survived!":If Int(6*Rnd) Then ?n Else ?-n

```

This resolves to a `Run-time error '13': Type mismatch` when applying a negative switch to a string.

# Answer
> 1 votes
# TI-BASIC (TI-84+/SE), 36 bytes

```
startTmr→rand:1/(1<randInt(1,6:"I survived!

```

There is no input, as the challenge specifies.
Output is `I survived!` if successful, a `DIVIDE BY 0` error otherwise.

The `DIVIDE BY 0` error screen looks like the following:

```
ERR:DIVIDE BY 0
1:Quit
2:Goto

```

Selecting either option (and returning to home screen if `2` is selected) shows `Error` after the program call.

**Examples:**

```
prgmCDGFE
           Error
prgmCDGFE
I survived!
prgmCDGFE
I survived!
prgmCDGFE
           Error

```

**Explanation:**

```
startTmr→rand:1/(1<randInt(1,6:"I survived!   ;full program

startTmr→rand                                 ;store the current time into "rand"
                                              ; this is necessary because "rand" is 0 after
                                              ; factory reset, the default state for TI-BASIC
                                              ; submissions
                   randInt(1,6                ;get a random integer in [1,6]
                 1<                           ;is greater than 1?  1 if true, 0 if false
              1/(                             ;divide 1 by the result
                                              ; throws "DIVIDE BY 0" error if result was
                                              ; false
                               "I survived!   ;leave this string in "Ans"
                                              ;implicitly print "Ans"

```

---

**Notes:**

* TI-BASIC is a tokenized language. Byte count does ***not*** equal character count.
* Lowercase letters are **two bytes** each.

+ Lowercase letters can be enabled using this assembly program.
* `startTmr` is a command only on the TI-84+ and TI-84+ SE calculators. Said calculators have different operating systems.

# Answer
> 1 votes
GNU Bash -- 37 bytes

`!` followed by nothing doesn't trigger history substitution. `$[...]` is alternative syntax for arithmetic. `(...)` is a subshell.

This solution is portable. `bash` itself does `fork` but doesn't `exec` any other programs.

```
(exit $[$RANDOM%6])&&echo I survived!

```

# Answer
> 1 votes
# Japt v1.4.5, 16 bytes

```
6ö
ªí
`I s¨viv!

```

Try it

-1 byte thanks to @Shaggy!

Throws `TypeError: U.í is not a function` when a random number in the range `[0,6)` is `0`.

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 48 bytes

```
Write(1/new Random().Next(6)<9?"I survived!":"")

```

Try it online!

Throws `Attempted to divide by zero.` if a random number in the range `[0,6)` is `0`.

# Answer
> 1 votes
# VB.Net, 38 bytes

```
If(CInt(Rnd() * 6), "I survived!", Dir())

```

Throws : System.ArgumentException 'Dir' function must first be called with a 'PathName' argument.

Spaces removed :

```
If(CInt(Rnd()*6),"I survived!",Dir())

```

# Answer
> 1 votes
# Commodore C64/128, C64Mini and compatibles, 101 95 92 tokenised BASIC bytes + 6 penalty bytes for only working in Commodore BASIC

As Commodore keyword abbreviations, you may enter it as follows:

```
 0a$="i survived":fOi=0to5:a$(i)=a$:nE:a$(rN(.)*6)="":x=6*rN(.)
 1?len(a$(x))/len(a$(x))"{left}{left}"a$

```

I found a six-tokenised byte saving by not using the `INT` keyword when assigning a value with `RND` and CBM BASIC will automatically convert the key value to it's integer by ignoring the decimal places.

Non-obfuscated for explanatory purposes:

```
 0 let a$="i survived"
 1 for i=0 to 5
 2 let a$(i)=a$
 3 next i
 4 let a$(int(rnd(0)*6)=""
 5 let x=int(rnd(0)*6)
 6 print len(a$(x))/len(a$(x));"{left}{left}";a$(x)

```

Firstly, we set up `a$` as a string and we later use it as an array; in Microsoft \[Commodore\] BASIC that appeared on the PET, VIC-20, C64 etc... you can set up the first 11 elements of a zero-indexed array without expressly declaring it first, though it saves space on the variable stack if you do and you have fewer than 11 elements.

So our string array of six elements are set to the string literal of `i survived`. One of those elements is randomly reset to an empty string.

The `x` variable is then used to select which of the six will be displayed (one of which is empty). Finally, we try to divide the length of that element with itself; usually this would produce an output of `1` except where the string length of the element is `0`, so `0/0` will produce an error (one in six chance) and halt the execution of the symbolic listing; otherwise, the `print` command moves the cursor position back two spaces to overwrite the output with the string literal of the array element `x`, or `i survived`.

This answer assumes that the `division by zero` error reported by BASIC (which halts the programs execution by the interpreter) is acceptable as `the program crashing` as cited above.

# Answer
> 1 votes
# Python 2, 49 bytes

```
import os
print["I survived!"][os.urandom(1)<'+']

```

Try it online!

Utilises the idea from this answer of using `os.urandom`, but we save some bytes by avoiding the `ord` call.

`os.urandom(n)` generates `n` random bytes. By checking if they are smaller than `chr(math.ceil(256.0/6)) (== '+')`, we get an approximately `1/6` chance of `True (== 1)`.

# Answer
> 1 votes
# Vyxal `O`, 13 bytes

```
6ʁ℅ḭ`I ¦⟇d!`,

```

Try it Online!

Fixed thanks to Razetime!

When run offline, 11 bytes (thanks to Aaron Miller)

```
6ʁ℅ḭ`I ¦⟇d!

```

Try it Online!

# Answer
> 0 votes
# Tcl, 64 bytes

```
puts [expr srand([clock se])*0+int(rand()*6)%6?"I survived":1/0]

```

Try it online!

# Answer
> 0 votes
## C++, 105 bytes

```
#include<iostream>
#include<ctime>
int f(){srand(time(0));delete(int*)!(rand()%6);printf("I survived!");}

```

In C++, `delete` behavior is that on 0 ( or nullptr ), nothing occurs

Not as cool ( nor dangerous ) as CommitStrip's russian roulette

# Answer
> 0 votes
# Microscript II, 20 bytes

```
6R("I survived!"ph)f

```

Generates a random integer on `[0,5]`, printing the message and halting if the generated integer is nonzero. If the generated integer is 0, it instead crashes with an IllegalArgumentException because the `f` instruction is invoked on a nonstring value

# Answer
> 0 votes
# Forth (gforth), 51 bytes

```
include random.fs
: f 1 6 random / ." I Survived!";

```

Try it online!

### Explanation

Randomly gets a number between 0 and 5 (inclusive) Divides 1 by the result Crashes with divide by zero error if random number is 0

### Code Explanation

```
include random.fs       \ include the library file necessary for random to work
: f                     \ start a new word definition
  1                     \ place 1 on the stack
  6 random              \ get a random number between 0 and 5 (inclusive)
  /                     \ divide 1 by the result of the random call
  ." I Survived!"       \ print "I Survived!"
;                       \ end word definition

```

# Answer
> 0 votes
# JVM Bytecode `-noverify`, 372 bytes

Works by passing a wrong type to the print function if Random.nextInt(6) is 0.

Hexdump of the class:

```
$ xxd.exe Code.class
00000000: cafe babe 0003 002d 0020 0c00 1900 1f01  .......-. ......
00000010: 0016 285b 4c6a 6176 612f 6c61 6e67 2f53  ..([Ljava/lang/S
00000020: 7472 696e 673b 2956 0100 106a 6176 612f  tring;)V...java/
00000030: 7574 696c 2f52 616e 646f 6d01 0006 3c69  util/Random...<i
00000040: 6e69 743e 0c00 0400 0803 0000 0006 0700  nit>............
00000050: 1001 0003 2829 5607 0014 0100 0443 6f64  ....()V......Cod
00000060: 6501 0004 6d61 696e 0900 0900 0101 000a  e...main........
00000070: 536f 7572 6365 4669 6c65 0100 076e 6578  SourceFile...nex
00000080: 7449 6e74 0c00 1100 1a01 0013 6a61 7661  tInt........java
00000090: 2f69 6f2f 5072 696e 7453 7472 6561 6d01  /io/PrintStream.
000000a0: 0007 7072 696e 746c 6e0a 0013 001d 0700  ..println.......
000000b0: 0301 0010 6a61 7661 2f6c 616e 672f 5379  ....java/lang/Sy
000000c0: 7374 656d 0a00 1300 050a 0007 000f 0100  stem............
000000d0: 0428 4929 4907 000a 0100 036f 7574 0100  .(I)I......out..
000000e0: 1528 4c6a 6176 612f 6c61 6e67 2f53 7472  .(Ljava/lang/Str
000000f0: 696e 673b 2956 0100 0b49 2073 7572 7669  ing;)V...I survi
00000100: 7665 6421 0800 1b0c 000e 0017 0100 0001  ved!............
00000110: 0015 4c6a 6176 612f 696f 2f50 7269 6e74  ..Ljava/io/Print
00000120: 5374 7265 616d 3b00 2000 1800 1300 0000  Stream;. .......
00000130: 0000 0100 0900 0b00 0200 0100 0a00 0000  ................
00000140: 2900 0500 0100 0000 1db2 000c bb00 1359  )..............Y
00000150: b700 1512 06b6 0012 9a00 0812 06a7 0005  ................
00000160: 121c b600 16b1 0000 0000 0001 000d 0000  ................
00000170: 0002 001e                                ....

```

Jasmin code to generate:

```
.source ""
.class Code
.super java/util/Random
.method public static main([Ljava/lang/String;)V
    .limit stack 3
    getstatic java/lang/System/out Ljava/io/PrintStream;
    new java/util/Random
    dup
    invokenonvirtual java/util/Random/<init>()V
    ldc 6
    invokevirtual java/util/Random/nextInt(I)I
    ifne Survive
    ldc 6
    goto Print
    Survive:
    ldc "I survived!"
    Print:
    invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V
    return
.end method

```

Must to be run with java -noverify to prevent Java from realizing that the class is messed up.

Also it's very wrong this time but CFR output for fun:

/*
 * Decompiled with CFR 0.142.
 */
import java.io.PrintStream;
import java.util.Random;

class Code
extends Random {
    public static void main(String[] arrstring) {
        if (new Random().nextInt(6) != 0) {
            String string = "I survived!";
        }
        System.out.println((String)6);
    }
}
```
</code></pre>

# Answer
> 0 votes
# C (gcc), ~~58~~ 53 bytes<br>

-5 bytes by using &i in place of time(0) - thanks ceilingcat
`Floating point exception` when `rand()` is divisible by 6

```
main(i){i/=(srand(&i)+rand()%6);puts("I survived!");}

```

Try it online!

# Answer
> 0 votes
# Perl 6, 34 bytes

```
(^6 .roll&&say "I survived!")||die

```

Throws an exception to crash.

Try it online!

# Answer
> 0 votes
# MathGolf, 15 bytes

```
6rw/;'I ûÄ%$╦'!

```

Try it online!

## Explanation

```
6r                push [0, 1, 2, 3, 4, 5]
  w               random item from list
   /              divide implicit zero by the random element
    ;             discard TOS (needed for non-crashes)
     'I           push single character "I"
                  space character
        ûÄ%       push "Ä%"
           $      convert to ordinal (from base 256 to base 10)
            ╦     fetch single dictionary word "survived"
             '!   push single character "!"

```

With some better handling of dictionary fetches, this could probably be 2-3 bytes shorter, but that's not getting implemented within the immediate future.

# Answer
> 0 votes
# Octave 33 bytes

```
{"I_Survived!"}(1/(rand(1)>0.16))

```

Approx each 6 time, there is a `warning: division by zero
error: index (inf): subscripts must be either integers 1 to (2^31)-1 or logicals`

# Answer
> 0 votes
# Java, 98 bytes

```
interface m{static void main(String[]a){System.out.print(Math.random()<.16?1/0:"I survived!");}}

```

Try it online
Bonus answer that allocates `2^60` bytes of memory instead of dividing by 0:

```
import sun.misc.Unsafe;import java.lang.reflect.*;interface M{static void main(String[]a)throws Exception{Field f=Unsafe.class.getDeclaredField("theUnsafe");f.setAccessible(1>0);((Unsafe)f.get(null)).allocateMemory(Math.random()<.16?1L<<60:0);System.out.print("I survived!");}}

```

TIO

# Answer
> 0 votes
# Runic Enchantments, 23 bytes

```
>6'RA0)?;"I survived!"@

```

Try it online!

Nothing too special here. Just an IP that picks a random number \[0-6) and prints the required string if the random value isn't 0.

Required string contains two `v`s which also creates an IP each that get terminated after 100k execution steps (otherwise TIO would produce instant results and the `>` wouldn't be needed).

# Answer
> 0 votes
# MATLAB/Octave, 37 bytes

```
a=1:5;a(randi(6));disp("I survived!")

```

Try it online!
It has 1 in 6 chances to crash with indexing error, when `randi` returns `6`.

# Answer
> 0 votes
# PPL, 96 bytes

```
importRandom
declarex=Random.random()*6
ifx>1{
printLine("I survived!")
}
ifx<=1{
printLine(f)
}

```

Very similar code to the Minceraft problem. Runs on PPL v1.0.10.

Soon, I will publish an official PPL website where you can create and run PPL code. I am still working on it.

## Explanation

The first line imports `Random`.

Then, we set `x` to `Random.random()` (random float between 0 and 1) multiplied by `6`.

Since neither `else` nor ternary exists in PPL, we must use two diverging if-statements. One prints the string `I survived!` to STDOUT (if `x` is greater than 1) while the other errors because `f` is undefined.

# Answer
> 0 votes
# 05AB1E, 12 bytes

*Ties hyper-neutrino's Jelly answer for #1.*

```
“IÐ–d!“6LΩiF

```

Try it online!

```
“...“6LΩiF  # trimmed program
“...“       # push "I survived!"
        i   # if...
       Ω    # random element in...
      L     # [1, 2, 3, ...,
     6      # ..., literal...
      L     # ]...
        i   # is 1...
         F  # then do nothing...
“...“       # "I survived!"...
         F  # times
            # implicit output

```

# Answer
> 0 votes
# Rattle, <sup>~~21~~</sup> 19 bytes

```
=?6/`p"I survived!"

```

Try it Online!

There's a 5/6 chance that this just prints `I survived`, and a 1/6 chance that this exits with an error:

```
Error: float division by zero at command index 1 [/`]

```

# Explanation

```
=?6           sets the top of the stack to a random value from 0-5 inclusive
   /`         divides the top of the stack by the top of the stack.
                  This works fine except for when the top of the stack is 0
     b"..."   adds "I survived!" to the output buffer, implicit output (p" " would work here too)

```

# Answer
> 0 votes
# Ly, 19 bytes

```
6?/<"I survived!"&o

```

Try it online!

This is similar to some of the other entries. It generates a random number between `0` and `5`, then crashes with a division by zero error if `0` was the result.

```
6?                   - generate a random number in 0-5
  /                  - divide, fails with division by zero 1/6 of the time
   <                 - switch to a clean stack
    "I survived!"    - push the output string (codepoints)
                 &o  - print the stack a characters

```

# Answer
> 0 votes
# Julia 1.0, 32 bytes

```
0%rand(0:5);print("I survived!")

```

Try it online!

# Answer
> 0 votes
# APOL, 28 bytes

Dead simple, just uses the "divide by 0" method.

`/(1 ∿(0 5));p("I survived!")`

# Answer
> 0 votes
# \<\>^v, 18 bytes

```
5#=V"I survived!";

```

run online

### Explanation

```
5#=V"I survived!";
5                  Push 5 to stack
 #                 Push random number in range [0, <top of stack>]
  =                Skip next instruction if the top two elements (5 and the random number)
                   of the stack are equal
   V               Try reading the value of register 'v'. This should crash because it was
                   never assigned a value, its setter 'v' being a keyword
    "              String start
     I survived!   Contents of the string
                "  String end
                 ; Print with newline

```

# Answer
> 0 votes
# Python 3, 54 bytes

```
import random;1/random.randrange(5);print'I survived!'

```

On 1/0 it will crash:

```
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

```

---
Tags: code-golf, random
---


title: Checkerboard the Matrix

text:
# Question
Title: Checkerboard the Matrix
## Task

Given a matrix, your program/function should output a row-equivalent matrix in checkerboard form ( \\$A\_{ij}=0\\$ if and only if \\$i+j\\$ is odd).

Two matrices are defined to be row-equivalent if and only if one can be obtained from the other by a sequence of elementary row operations (EROs), where each ERO consists of performing one of the following moves:

1. Swapping two rows
2. Multiplying one row by a nonzero rational constant
3. Adding a rational multiple of one row to another row

Since there are multiple possible outputs for each input, please include a way to verify that the output is row-equivalent to the input, or explain enough of your algorithm for it to be clear that the output is valid.

## Example

Input:

```
2 4 6 8
0 2 0 4
1 2 5 4

```

Subtracting row 2 from row 3 yields

```
2 4 6 8
0 2 0 4
1 0 5 0

```

Subtracting double row 2 from row 1 yields

```
2 0 6 0
0 2 0 4
1 0 5 0

```

That is one possible output. Another possible matrix output is

```
1 0 3 0
0 1 0 2
1 0 4 0,

```

which is also row-equivalent to the given matrix and is also in checkerboard form.

## Constraints

* The given matrix will have at least as many columns as rows and contain only integers (your output *may* use rational numbers, but this is not strictly necessary since you can multiply by a constant to obtain only integers in the output).
* You may assume that the rows of the matrix are linearly independent
* You may assume that it is possible to express the given matrix in checkerboard form

Input and output may be in any reasonable format that unambiguously represents an `m×n` matrix.

## Sample Test Cases

Each input is followed by a possible output.

```
1 2 3
4 5 5
6 5 4

1 0 1
0 1 0
1 0 2

1 2 3
4 5 5
2 0 -1

1 0 1
0 1 0
1 0 2

2 4 6 8
0 2 0 4
1 2 5 4

1 0 3 0
0 1 0 2
1 0 4 0

1 2 3 2 5
6 7 6 7 6
1 2 1 2 1

1 0 1 0 1
0 1 0 1 0
1 0 2 0 3

3  2  1  10 4  18
24 31 72 31 60 19
6  8  18 9  15 7
8  4  8  20 13 36

3 0 1 0 4 0
0 1 0 5 0 9
2 0 6 0 5 0
0 8 0 9 0 7

3  2  1  10 4  18
24 31 72 31 60 19
0  4  16 -11 7 -29
8  4  8  20 13 36

3 0 1 0 4 0
0 1 0 5 0 9
2 0 6 0 5 0
0 8 0 9 0 7

1 0 0 0 -2
0 1 0 1 0
0 0 1 0 2

3 0 1 0 -4
0 2 0 2 0
5 0 3 0 -4

```

Related:

# Answer
> 7 votes
# MATLAB - ~~114~~ 129 bytes

```
function n=c(m)
n=rref(m);l=size(n,1);for i=1:l
e=1.5+.5*(-1)^i:2:l;N=n(e,:);n(e,:)=N+repmat(n(i,:),length(e),1).*max(N).^2;end

```

Try it online

For a given nxm matrix, there are three forms of the rref of the matrix.

1. The identity matrix (with optional all-zero columns) (m\>=n)
2. Full rank matrix where columns that do not contain a row-leading 1 can have any value (m\>n)
3. Identity matrix with zero rows on the bottom (m\<n)

1 and 3 are easily made into a checkerboard by looping through each row and adding every odd/even row (which would have the 1s in the appropriate places)

for 2, however, it is impossible to make a checkerboard matrix unless the matrix is already a checkerboard. This is because the columns that have nonzero values can never be reduced because there is no column with a row-leading 1, and any ERO would add a value in another space that would ruin the checkerboard pattern. I'm certain there's a more rigorous explanation but linear algebra is not easy.

# Answer
> 1 votes
# Python3, 941 bytes:

```
from math import*
E=enumerate
Z=zip
T=lambda x:[i>0 for i in x]
lcm=lambda a,b:abs((a*b)//gcd(a,b))
U=lambda i,r,m:m[:i]+[r]+m[i+1:]
G=lambda r:all(r[i+1]for i,a in E(r)if a==0 and i+1<len(r))
v=lambda m:all(not any(r[not i%2::2])and all(r[i%2::2])for i,r in E(m))
S=lambda m:sum(sum(not i for i in b)for b in m)
def f(m):
 q,Q=[m],0
 while q:
  if v(m:=q.pop(0)):return m
  for x,a in E(m):
   for y,b in E(m):
    if x<y:
     if all(j.count(0)==len(j)//2 and G(j)for j in m):q+=[m[:x]+[b]+m[x+1:y]+[a]+m[y+1:]]
     for c in[1,-1]:
      if 0 in(R:=[j+k*c for j,k in Z(a,b)]):
       if T(b)!=T(R):q+=[U(y,R,m)]
       if T(a)!=T(R):q+=[U(x,R,m)]
      for j,k in Z(a,b):
       if j and k:
        L=lcm(j,k);A=[i*(L//j)for i in a];B=[i*(L//k)for i in b]
        if 0 in(R:=[J+K*c for J,K in Z(A,B)])and T(b)!=T(R):
         if(n:=S(u:=U(y,R,m)))>Q:Q=n;q+=[u]
        if 0 in R and T(a)!=T(R):
         if(n:=S(u:=U(x,R,m)))>Q:Q=n;q+=[u]

```

Try it online!

A breadth-first, basic brute force approach.

---
Tags: code-golf, math, matrix
---