title: EASY to memorize numbers

text:
# Question
Title: EASY to memorize numbers
Numbers that are easy to remember yet theoretically not easily made

Your challenge is to make a program/function in any language that generates uniformly random numbers that fit these criteria:

1. **Length** is **5 digits**
2. There are two separate repeated digit pairs
3. One set of repeated digits is at the beginning or end and the digits are next to each other
4. The odd number out is surrounded by the other pair of digits
5. **The two digit pairs and the other number should all be unique**
6. Your program may support numbers with leading zeroes or not, at your discretion. If leading zeroes are supported, they must be included in the output: 06088, not 6088. If leading zeroes are not supported, then numbers like 06088 should not be generated at all.

# Test Cases

## Accepted Outputs:

```
55373
55494
67611
61633
09033
99757
95944
22808
65622
22161

```

## Not accepted outputs:

```
55555
77787
85855
12345
99233
12131
abcde
5033

```

More acceptable test cases can be found at this pastebin link.

These were made with this python program:

```
import random
for i in range(100):

    if random.randint(0,100) >= 50: #Put pair touching at beginning if true
        temp = []                      #working array
        temp.append(random.randint(0,9))  #append random digit
        temp.append(temp[0])              #append the same digit again

        x = random.randint(0,9)
        while x == temp[0]:
            x = random.randint(0,9)
        temp.append(x)                    #append another unique digit

        y = random.randint(0,9)
        while y == temp[0] or y == temp[2]:
            y = random.randint(0,9)
        temp.append(y)                  #append another unique digit, and the previous unique digit
        temp.append(x)

    else:  #Put touching pair at end
        temp = []                      #working array
        temp.append(random.randint(0,9))  #append random digit

        #While not unique, try again
        x = random.randint(0,9)
        while x == temp[0]:
            x = random.randint(0,9)
        temp.append(x)                    #append another unique digit

        temp.append(temp[0])              #append the same 0th digit again

        y = random.randint(0,9)
        while y == temp[0] or y == temp[1]:
            y = random.randint(0,9)
        temp.append(y)                  #append another unique digit twice
        temp.append(y)

    tempstr = ""
    for i in temp:
        tempstr += str(i)
    print tempstr

```

This is , so shortest answer in bytes wins!

# Answer
# 05AB1E, 11 bytes

```
žh.r3£ûÁÂ)Ω

```

Try it online!

**Explanation**

```
žh            # push "0123456789"
  .r          # random shuffle
    3£        # take the first 3
              # EX: 152
      û       # palendromize
              # EX: 15251
       Á      # rotate right
              # EX: 11525
        Â)    # pair with its reverse
              # EX: [11525, 52511]
          Ω   # pick one at random

```
> 21 votes

# Answer
# Perl 5, ~~81~~ ~~63~~ 56 bytes

*Cut 7 bytes with inspiration from @DomHastings*

Constructing the number from the appropriate pattern.

```
@q{0..9}++;say+(keys%q)[.5>rand?(2,2,0,1,0):(0,1,0,2,2)]

```

Try it online!

---

## Perl 5, 89 bytes

Picks random 5 digit numbers until it finds one that meets the criteria.

```
$_=sprintf'%05d',0|rand 1E5until(/(.)\1(.)(.)\2/||/(.)(.)\1(.)\3/)&&$1-$2&$2-$3&$1-$3;say

```

Try it online!
> 9 votes

# Answer
## CJam (16 bytes)

```
YmrG*98+ZbA,mrf=

```

Online demo

Note: I've assumed that by "unique" OP really means "distinct".

Also for 16 bytes:

```
98ZbA,mrf=W2mr#%
98ZbA,mrf=_W%]mR

```

### Dissection

```
Ymr    e# Select a random number from [0 1]
G*98+  e# Multiply by 16 and add 98 to get 98 or 114
Zb     e# Base conversion in base 3 to get [1 0 1 2 2] or [1 1 0 2 0]
A,mr   e# Shuffle the numbers from 0 to 9
f=     e# Map "select the item at this index"

```

The other variants generate using `[1 0 1 2 2]` and then select either the result or its reverse.
> 9 votes

# Answer
# Python 2, 80 bytes

```
from random import*
a,b,c=sample(range(10),3)
print[a,a,b,c,b][::choice((-1,1))]

```

Try it online!

Outputs a list of digits.

# Python 2, 83 bytes

```
from random import*
a,b,c=sample('0123456789',3)
print(a*2+b+c+b)[::choice((-1,1))]

```

Try it online!

Output is a number.
> 8 votes

# Answer
# APL (Dyalog Unicode), ~~22 21 20 18~~ 17 bytes

```
(3∨?2)⌽1↓,∘⌽⍨3?10

```

Try it online!

If it's acceptable to output the numbers always in the same format, this can be shortened to 12 bytes, either `1⌽1↓,∘⌽⍨3?10` or `3⌽1↓,∘⌽⍨3?10`.

Saved a byte by removing the unnecessary .

Saved a byte thanks to H.PWiz, and then 2 more bytes due to their tip.

Saved a byte thanks to ngn.

The function assumes `⎕IO←0` (**I**ndex **O**rigin).

---

### How?

```
(3∨?2)⌽1↓,∘⌽⍨3?10 ⍝ Anonymous function.
              3?10  ⍝ Deal 3 (distinct) random numbers from 0 to 9. (Assume 1 2 3)
             ⍨     ⍝ Use that as both arguments for:
          ,∘⌽      ⍝ Rotate (⌽), then concatenate (,).
                   ⍝ Yields 3 2 1 1 2 3.
        1↓         ⍝ Drop the first element. Our vector is now 2 1 1 2 3
      ⌽            ⍝ Rotate the vector to the left using as argument:
(  ?2)             ⍝ Roll 0 or 1 and...
 3∨                ⍝ Do the GCD between 3 and the result. (3∨0=3; 3∨1=1.)
                   ⍝ This yields either 1 1 2 3 2 or 2 3 2 1 1.

```
> 7 votes

# Answer
# Java 8, ~~145~~ ~~136~~ ~~125~~ 119 bytes

```
v->{String r;for(;!(r=(int)(Math.random()*1e5)+"").matches("((.).?\\2){2}")|r.chars().distinct().count()<3;);return r;}

```

-9 bytes thanks to *@OlivierGrégoire.*
-11 bytes thanks to *@RickHitchcock*.
-6 bytes thanks to *@Nevay*.

**Explanation:**

Try it online.

```
v->{            // Method with empty unused parameter and String return-type
  String r;     //  Result-String
  for(;!(r=(int)(Math.random()*1e5)+"")
                //  Generate a random number in the range [0; 100000) and set it to `r`
        .matches("(.).*\\1(.).*\\2")
                //   And continue doing this as long as it doesn't match the regex above,
       |r.chars().distinct().count()<3;);
                //   or doesn't have three distinct digits
  return r;}    //  Return the result

```
> 6 votes

# Answer
# Jelly, 23 bytes

```
⁵Ḷṗ3⁼Q$ÐfXµḢ;`;ŒBW;U$µX

```

Try it online!
> 5 votes

# Answer
# Jelly, ~~12~~ 11 bytes

```
ØDẊ⁽0yṃ,U$X

```

Try it online!

---

# Explanation

```

ØDẊ⁽0yṃ,U$X    Niladic link, generate a random string.
ØD             List of digits, ['0','1','2',...,'9'].
  Ẋ            Random shuffle.
   ⁽0y         Number 13122.
      ṃ        Base decompression. <sup>(*)</sup>
       ,U$     Pair with its upend (reverse).
          X    Choose one (it or its reversed) randomly.

```

(\*) The right argument of  is the list `['0','1','2',...,'9']`, randomly shuffled, have 10 elements. So the number `13122` will be converted to bijective base 10 (`[1,3,1,2,2]`) and index into the list (so if the list is `l`, the return value of the atom is `[l[1],l[3],l[1],l[2],l[2]]`, where Jelly uses 1-based indexing)
> 5 votes

# Answer
# JavaScript (ES6), 79 bytes

```
f=([,,d,a,b,c]=[...Math.random()+f])=>a-b&&a-c&&b-c?d&1?a+a+b+c+b:b+c+b+a+a:f()

```

Try it online!

### How?

`Math.random()` gives a random float in **\[0..1)**. We use `+f` to force coercion to a string. We ignore the leading zero and the decimal point by doing `[,,` (destructuring assignment of the first two characters to nothing) and collect the first 4 decimal digits into **d**, **a**, **b**, and **c**.

If **a**, **b** and **c** are 3 distinct integers, we build the final output in either **AABCB** or **BCBAA** format (using the parity of **d** to decide). Otherwise, we try again until they are.

In the highly improbable event of `Math.random()` returning a value without enough decimal places, at least **c** will be set to a non-digit character, forcing the test to fail and the recursive call to occur. If **a**, **b** and **c** are valid integers then **d** is guaranteed to be a valid integer as well, so this one doesn't need to be tested.
> 4 votes

# Answer
# Perl 6, 42 bytes

```
[~] (^10).pick(3)[0,|(<0 2 1>,<1 0 2>).pick,2]

```

Try it online!
> 4 votes

# Answer
# Dirty, 33 bytes

Uses the `--numeric-output` flag so it's readable, otherwise it would output a string of control characters with code-points corresponding to the digits.

```
10⭧[1w#%D⅋№3⤱≠1ẅ&]1wẂ⭿⭣1u∅#1∧◌ŪW‼

```

Try it online!

**Explained:**

```
10⭧              put 10 on the right stack
[1w#%D⅋№3⤱≠1ẅ&] loop until there are 3 distinct positive numbers below 10 in the top stack
1wẂ              clean-up the right and top stacks
⭿               copy the top and bottom of the top stack to each-other
⭣                swap the first two elements of the top stack
1u               rotate the top stack by 1
∅#1∧◌ŪW          reverse the top stack half of the time
‼                print the top stack

```
> 2 votes

# Answer
# PHP, ~~73~~ ~~72~~ 66 bytes

```
<?=strtr(rand()%2?AABCB:BCBAA,ABC,join(array_rand(range(0,9),3)));

```

**Edit:** 66 bytes thanks to @David 's suggestion.

Try it online!
> 2 votes

# Answer
# Charcoal, 34 bytes

```
≔‽χθ≔‽Φχ⁻ιθη↑Ｉ⟦θθη‽Φχ×⁻ιθ⁻ιηη⟧¿‽²‖

```

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

```
  χ                                 Predefined variable 10
 ‽                                  Random element from implicit range
≔  θ                                Assign to variable `q`
       χ                            Predefined variable 10
      Φ                             Filter on implicit range
         ι                          Current value
          θ                         Variable `q`
        ⁻                           Subtract
     ‽                              Random element
    ≔      η                        Assign to variable `h`
                    χ               Predefined variable 10
                   Φ                Filter on implicit range
                       ι  ι         Current value
                        θ           Variable `q`
                           η        Variable `h`
                      ⁻  ⁻          Subtract
                     ×              Multiply
                  ‽                 Random element
               θθ                   Variable `q`
                 η          η       Variable `h`
              ⟦              ⟧      Wrap 5 values into array
             Ｉ                      Cast array elements to string
            ↑                       Make array print horizontally
                                ²   Literal 2
                               ‽    Random element from implicit range
                              ¿     If
                                 ‖  Reflect

```
> 2 votes

# Answer
## Retina, 40 bytes

```

10*
Y`w`d
V?`
Lv$7`.(.)
$1$<'$'
O?`...?

```

Try it online!

Can print strings with leading zeros.

### Explanation

```

10*

```

Initialise the string to 10 underscores.

```
Y`w`d

```

Cyclically transliterate word characters to digits. This is a bit weird. The `w` and `d` are short for the following strings, respectively:

```
w: _0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
d: 0123456789

```

Cyclic transliteration means that first, both strings are repeated to the length of the their LCM:

```
_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_012345...
0123456789012345678901234567890123456789012345678901234567890123456789...

```

Since the string lengths 53 and 10 are coprime, each copy of `_` is paired with a different digit. And now cyclic transliteration will replace the **i**th copy of `_` with the **i**th pairing in that expanded list. So we end up with the following string:

```
0369258147

```

All of that to save a single byte over the literal string `0369258147`, so yay I guess? :D

Anyway, we've got a string of all 10 digits now.

```
V?`

```

This shuffles the digits. So the first three digits will be a uniformly random selection of three distinct digits.

```
Lv$7`.(.)
$1$<'$'

```

We match the string `...ABC` and turn it into `BABCC`. The way we do this is kinda crazy though and again saves only one byte compared to a more straightforward approach. We first match all *overlapping* (`v`) pairs of characters, capturing the second one (`.(.)`). Then we retain only the 8th match (`7`, zero-based) which is `AB` in `...ABC`. Then we replace (`$`) it with: `B` (`$1`), `ABC` (`$<'` which is the suffix of the match-*separator* left of the match), `C` (`$'` which is the suffix of the match itself).

```
O?`...?

```

Finally, we match either 3 or 2 characters and shuffle the matches, giving us either `BABCC` or `CCBAB` at random.
> 2 votes

# Answer
# , 78 bytes

```
z=sample(0:9,3)[c(2,1:3,3)];cat(paste(`if`(runif(1)>.5,z,rev(z)),collapse=''))

```

Try it online!

`sample` picks 3 random values from `0:9`, which are placed in a vector like so: `a b a c c`. Now we have a 50/50 chance to reverse this vector, and then concatenate and print.
> 2 votes

# Answer
# Ruby, 60 59 bytes

```
->{a,b,c=[*0..9].sample 3;[[a,a,b,c,b],[b,c,b,a,a]].sample}

```

Try it online!

It returns a list of digits.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 59 bytes

```
{{#,##,#2},{#2,##,#3}}~r~1&@@(r=RandomSample)[0~Range~9,3]&

```

Try it online!
> 1 votes

# Answer
# Red, 147, 146 125 bytes

```
func[][b: copy[]d:[1 1 2 3 2]if 1 = random 2[d: reverse d]while[4 > length? b][alter b(random 10)- 1]foreach a d[prin b/(a)]]

```

Try it online!

## Ungolfed:

```
f: func[] [                       function with no arguments
    b: copy []                    an empty list
    d: [1 1 2 3 2]                preset digits at positons
    if 1 = random 2 [             generate 1 or 2
        d: reverse d]             based on this choose to reverse the positions list
    while [4 > length? b] [       while we haven't chosen 3 different digits
        alter b (random 10) - 1   pick a random digit, if it's not in the list already
                                  append it to the list, otherwise remove it
    ]
    foreach a d [                 for each position
       prin b/(a)]                print the corresponding digit
]

```
> 1 votes

# Answer
# C (gcc), 126 119 bytes

-6 bytes from @ceilingcat

```
#define R time(0)%10
b,n,m,k;f(){b=R^8;for(n=R;m==n|k==m|k==n;m=R,k=R);printf("%d%d%d%d%d",b?n:m,b?n:k,m,b?k:n,b?m:n);}

```

Try it online!
> 1 votes

# Answer
# Python 3 +numpy, 69 bytes

```
from pylab import*
r=choice
i=r(2)
print(r(10,3,0)[[1-i,0,1,2,-1-i]])

```

Explanation

```
from pylab import*
r=choice               # `choice` takes a range, number of samples, and wether repetition is allowed
i=r(2)                 # Single value in [0,1] to specify if repeated digits come on right or left
print(r(10,3,0)[[1-i,0,1,2,-1-i]])    # Construct output using index list and 3 random integers

```
> 1 votes

# Answer
# , 35 bytes

```
[:u:48+[:|.^:(?&2:)2 2 1 0 1{3?10"_

```

Try it online!

I'm sure it can be golfed much further.

## Explanation:

```
  3?10             - generates 3 different digits
7 0 3

  2 2 1 0 1{       - constructs a list using digits positions 0, 1 and 2

  2 2 1 0 1{3?10
3 3 0 7 0

  |.^:(?&2:)       - generates 0 or 1 and if 1, reverses the list

  |.^:(?&2:)2 2 1 0 1{3?10
0 7 0 3 3

   u:48+              - converts to char by adding 48 to each digit
   u:48+|.^:(?&2:)2 2 1 0 1{3?10
07033

```
> 0 votes

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


title: There, I fixed it (with rope)

text:
# Question
Title: There, I fixed it (with rope)
*Related: Rather similar (but much easier) challenge horizontally: There I fixed it (with tape)*

## Challenge:

Given a string only containing upper- and/or lowercase letters (whichever you prefer) and new-lines, put `rope` vertically to fix it. We do this by checking the difference of two adjacent letters in the alphabet (ignoring wrap-around and only going downward), and filling the space with as much `ROPE`/`rope` as we would need.
NOTE: One other key difference between this challenge and the There I fixed it (with tape) challenge is that we're not wasting `rope` this time like we did with the `tape` (suggested by *@JonathanAllan* in part one of the challenge).

### Example:

Input:

```
abc
bcd
ddd
eex
gfz
hka
imh

```

Output:

```
abc
bcd
Rdd
deE
efR
OPO
gEP
hRE
iOR
 kO
 PP
 mE
  R
  O
  P
  E
  R
  O
  P
  E
  R
  O
  x
  P
  z
  a
  E
  R
  O
  P
  E
  R
  h

```

***Why?***

* Between `b` and `d` in column 1 should be `c` (length 1), so we fill this with `R`;
* Between `e` and `g` in column 1 should be `f` (length 1), so we fill this with `O`;
* Between `f` and `k` in column 2 should be `ghij` (length 4), so we fill this with `PERO`;
* Between `k` and `m` in column 2 should be `l` (length 1), so we fill this with `P`;
* Between `d` and `c` in column 3 should be `efghijklmnopqrstuvw` (length 19), so we fill this with `EROPEROPEROPEROPERO`;
* Between `x` and `z` in column 3 should be `y` (length 1), so we fill this with `P`;
* Between `a` and `h` in column 3 should be `bcdefg` (length 6), so we fill this with `EROPER`.

## Challenge rules:

* The difference only applies downwards, so no rope between `za` (column 3 in the example above).
* It is possible to have multiple of the same adjacent letters like `dd` (column 3 in the example above).
* You will continue using the `ROPE` one column at a time to not waste parts (suggested by *@JonathanAllan* in part 1 of the challenge).
* You are allowed to take the input in any reasonable format. Can be a single string, string-array/list, character-matrix, etc. Output has the same flexibility.
* You are allowed to use lowercase and/or uppercase any way you'd like. This applies both to the input, output, and `ROPE`.
* Trailing spaces are optional (note that the correct amount of leading spaces are mandatory so the columns are correct).
Any amount of trailing and/or leading new-lines are also optional.
* You can assume that all test cases will have the same length across all rows, so `a\naa`/`[[a][a,a]]` wouldn't be a valid input.
* It is possible no `ROPE` is necessary, in which case the input remains unchanged.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

## Test cases:

```
As string:
 Input:  "abc\nbcd\nddd\neex\ngfz\nhka\nimh"
 Output: "abc\nbcd\nRdd\ndeE\nefR\nOPO\ngEP\nhRE\niOR\n kO\n PP\n mE\n  R\n  O\n  P\n  E\n  R\n  O\n  P\n  E\n  R\n  O\n  x\n  P\n  z\n  a\n  E\n  R\n  O\n  P\n  E\n  R\n  h"
As array-matrix:
 Input:  [[a,b,c],[b,c,d],[d,d,d],[e,e,x],[g,f,z],[h,k,a],[i,m,h]]
 Output: [[a,b,c],[b,c,d],[R,d,d],[d,e,E],[e,f,R],[O,P,O],[g,E,P],[h,R,E],[i,O,R],[ ,k,O],[ ,P,P],[ ,m,E],[ , ,R],[ , ,O],[ , ,P],[ , ,E],[ , ,R],[ , ,O],[ , ,P],[ , ,E],[ , ,R],[ , ,O],[ , ,x],[ , ,P],[ , ,z],[ , ,a],[ , ,E],[ , ,R],[ , ,O],[ , ,P],[ , ,E],[ , ,R],[ , ,h]]

As string:
 Input:  "a\nz\na"
 Output: "a\nR\nO\nP\nE\nR\nO\nP\nE\nR\nO\nP\nE\nR\nO\nP\nE\nR\nO\nP\nE\nR\nO\nP\nE\nz\na"
As array-matrix:
 Input:  [[a],[z],[a]]
 Output: [[a],[R],[O],[P],[E],[R],[O],[P],[E],[R],[O],[P],[E],[R],[O],[P],[E],[R],[O],[P],[E],[R],[O],[P],[E],[z],[a]]

As string:
 Input:  "zz\nyy\nxx\nxx\ncc\ncc\nbb\nad"
 Output: "zz\nyy\nxx\nxx\ncc\ncc\nbb\naR\n d"
As array-matrix:
 Input:  [[z,z],[y,y],[x,x],[x,x],[c,c],[c,c],[b,b],[a,d]]
 Output: [[z,z],[y,y],[x,x],[x,x],[c,c],[c,c],[b,b],[a,R],[ ,d]]

As string:
 Input:  "a\nb\nc\nc\nx\nx\ny\nz"
 Output: "a\nb\nc\nc\nR\nO\nP\nE\nR\nO\nP\nE\nR\nO\nP\nE\nR\nO\nP\nE\nR\nO\nP\nE\nx\nx\ny\nz"
 As array-matrix:
  Input:  [[a],[b],[c],[c],[x],[x],[y],[z]]
  Output: [[a],[b],[c],[c],[R],[O],[P],[E],[R],[O],[P],[E],[R],[O],[P],[E],[R],[O],[P],[E],[R],[O],[P],[E],[x],[x],[y],[z]]

As string:
 Input:  "zai\nybj\nxcq\nxcu\ncxw\ncxw\nbyr\nazw"
 Output: "zai\nybj\nxcR\nxcO\ncRP\ncOE\nbPR\naEO\n Rq\n OP\n PE\n ER\n Ru\n OO\n Pw\n Ew\n Rr\n OP\n PE\n ER\n RO\n Ow\n P \n E \n x \n x \n y \n z "
As array-matrix:
  Input:  [[z,a,i],[y,b,j],[x,c,q],[x,c,u],[c,x,w],[c,x,w],[b,y,r],[a,z,w]]
  Output: [[z,a,i],[y,b,j],[x,c,R],[x,c,O],[c,R,P],[c,O,E],[b,P,R],[a,E,O],[ ,R,q],[ ,O,P],[ ,P,E],[ ,E,R],[ ,R,u],[ ,O,O],[ ,P,w],[ ,E,w],[ ,R,r],[ ,O,P],[ ,P,E],[ ,E,R],[ ,R,O],[ ,O,w],[ ,P, ],[ ,E, ],[ ,x, ],[ ,x, ],[ ,y, ],[ ,z, ]]

As string:
 Input:  "asdljasdjk"
 Output: "asdljasdjk"
As array-matrix:
 Input:  [[a,s,d,l,j,a,s,d,j,k]]
 Output: [[a,s,d,l,j,a,s,d,j,k]]

As string:
 Input:  "asdljasdjk\nlkawdasuhq\nasjdhajksd"
 Output: "asdljasdjk\nRkaOdasPhR\nOPOPEajEPO\nPEPER  REP\nERERO  ORE\nROROh  POR\nOPOP   EPq\nPEPE   ROd\nERER   OR \nRsRO   PO \nO jP   EP \nl  w   RE \na  d   Os \n       P  \n       E  \n       R  \n       O  \n       u  \n       k  "
As array-matrix:
 Input:  [[a,s,d,l,j,a,s,d,j,k],[l,k,a,w,d,a,s,u,h,q],[a,s,j,d,h,a,j,k,s,d]]
 Output: [[a,s,d,l,j,a,s,d,j,k],[R,k,a,O,d,a,s,P,h,R],[O,P,O,P,E,a,j,E,P,O],[P,E,P,E,R, , ,R,E,P],[E,R,E,R,O, , ,O,R,E],[R,O,R,O,h, , ,P,O,R],[O,P,O,P, , , ,E,P,q],[P,E,P,E, , , ,R,O,d],[E,R,E,R, , , ,O,R, ],[R,s,R,O, , , ,P,O, ],[O, ,j,P, , , ,E,P, ],[l, , ,w, , , ,R,E, ],[a, , ,d, , , ,O,s, ],[ , , , , , , ,P, , ],[ , , , , , , ,E, , ],[ , , , , , , ,R, , ],[ , , , , , , ,O, , ],[ , , , , , , ,u, , ],[ , , , , , , ,k, , ]]

As string:
 Input:  "re\nop\npo\ner"
 Output: "re\noR\npO\neP\n E\n R\n O\n P\n E\n R\n O\n p\n o\n P\n E\n r"
As array-matrix:
 Input:  [[r,e],[o,p],[p,o],[e,r]]
 Output: [[r,e],[o,R],[p,O],[e,P],[ ,E],[ ,R],[ ,O],[ ,P],[ ,E],[ ,R],[ ,O],[ ,p],[ ,o],[ ,P],[ ,E],[ ,r]]

```

# Answer
# Jelly, 21 bytes

```
ZµOI’R“¡nⱮ»ṁż@"µF€z⁶Y

```

Try it online!

# Explanation

```
ZµOI’R“¡nⱮ»ṁż@"µF€z⁶Y  Main Link
Z                      Transpose the input so the columns are now rows
 µ                     New monadic chain
  O                    [Vectorizing] Convert each letter to its character code
   I                   [Vectorizing] Get the differences (gap size)
    ’                  [Vectorizing] Add one
     R                 [Vectorizing] Range from 1 .. x
           ṁ           Mold the string        into the ranges
      “¡nⱮ»                            "rope"
            ż@"        Vectorizing zip the rope strings with the original string (place ropes in gaps)
               µ       New monadic chain
                F€     Flatten Each
                  z⁶   Zip and fill with spaces
                    Y  Join on newlines for output

```

-1 byte thanks to Mr. Xcoder
-2 bytes thanks to Erik the Outgolfer
> 3 votes

# Answer
# 05AB1E, ~~38~~ ~~37~~ 25 bytes

Saved 10 bytes with suggestions from *Magic Octopus Urn* and another byte changing output format.

Outputs a list of strings.
Footer pretty prints.

```
'ÙºUζεDÇ¥<)ζε`FX¬sÀU}J]Jζ

```

Try it online!

**Explanation**

```
'ÙºU                       # store the string "rope" in variable X
    ζ                      # transpose input
     ε                ]    # for each transposed row
      D   )ζ               # zip the row with
       Ç¥<                 # the decremented deltas of its character codes
            ε              # for each pair of [letter, delta-1]
             `F     }      # delta-1 times do:
               X¬          # get the first letter of X (originally "rope")
                 sÀU       # rotate the letters left by 1 and store in X
                     J     # join the rope-letter to the current row-letter
                       J   # join to list of strings (the new columns)
                        ζ  # transpose

```
> 4 votes

# Answer
# Python 2, ~~197~~ 194 bytes

```
def f(s):
 r='ROPE'*len(`s`)*9;x=[]
 for i in zip(*s):
	x+='',
	for c,C in zip(i,i[1:]+(' ',)):l=(C>c)*(ord(C)+~ord(c));x[-1]+=c+r[:l];r=r[l:]
 print zip(*['%*s'%(-max(map(len,x)),s)for s in x])

```

Try it online!

---

* -3 bytes thanks to ovs
> 3 votes

# Answer
# Ruby, 119 bytes

```
->a{l=0;a.map!{|r|r.reduce{|x,y|x+("ROPE"*7)[l%4,-l+l+=[0,y.ord+~x[-1].ord].max]+y}}.map{|s|s.ljust a.map(&:size).max}}

```

Try it online!

Yes, this is much more difficult than the "TAPE" challenge. I tried to build up on my solution to that task, but this has a few extra twists.

Takes input as a columnwise array of characters, returns an array of strings, also in columnwise format. The code in the footer of the TIO link performs pre- and post-processing of I/O data so that we could supply a more manageable string and then print the result nicely.

## Explanation

The code makes two passes through the input array.

In the first pass we apply the `reduce` operation that fills up the space between the characters with the required amount of ROPE (`y.ord-x[-1].ord-1` characters, if positive). We also need to keep track of the used ROPE length (`l`).

Unlike in the TAPE case we cannot simply use `rjust` for filling, as it would always start from the R character. Instead, taking a proper slice of a long "ROPEROPE..." string seems lighter on byte count, especially since we also need to update `l` on the fly.

In the second pass we left-justify the resulting strings with spaces to match the length of the longest of them. Since we need the full results of the previous iteration here, the first pass modifies the array in place (hence `map!`, not `map`).
> 2 votes

# Answer
*-1 bytes thanks to Kevin Cruijssen*

*-70 bytes thanks to Jonathan Frech, wow.......*

# Python 3, 203 bytes

```
def f(s,c=0,x=()):
	for i in range(len(s[0])):
		p,o=" ",""
		for j in s:t=j[i];y=p>' 'and~ord(p)+ord(t);o+=('ROPE'*y)[c:y+c]+t;c,p=c%4+y*(y>=0)%4,t
		x+=o,
	for i in x:yield i.ljust(len(max(x,key=len)))

```

Try it online!
> 1 votes

# Answer
# Python 3, 182 bytes

```
from itertools import*
def f(l):r=cycle('ROPE');return zip_longest(*(''.join(c+''.join(islice(r,max(ord(n)+~ord(c),0)))for c,n in zip(z,z[1:]+(' ',)))for z in zip(*l)),fillvalue=' ')

```

Try it online!

The function takes its input as a list (or an iterable) of strings and also returns a generator for a sequences of strings, which is almost as good as a list.

## Ungolfed

…for better readability of the nested generators.

```
def f(l):
    r = cycle('ROPE')
    return zip_longest(
        *(
            ''.join(
                c + ''.join(islice(r, max(ord(n) - ord(c) - 1, 0)))
                for c, n in zip(z, z[1:] + (' ',)))
            for z in zip(*l)),
        fillvalue=' ')

```

## Explanation

1. The function uses `zip` to transpose the incoming list of lines into a generator of columns.
2. The innermost generator looks at pairs of adjacent characters and…
3. …slices the required amount of *continuous* ROPE out of an (infinite) `cycle` generator.
4. After copious amounts of string joining from generators the function re-transposes the list of columns back to a generator or lines and fills missing entries with `zip_longest`.
> 1 votes

# Answer
# Stax, 25 bytes

```
ÅiV╘ε╢+gA┘♦W[≈{`Co?-φvM«'

```

Run and debug online!

Input and output are given as space separated lists. Input is the list of rows as required, output is the list of columns as permitted.

## Explanation

Uses the unpacked version to explain.

```
M"ROPE"s{2B{Ev|r%b:m~|(,m_s\mJ
M                                 Transpose
 "ROPE"                           The string "ROPE"
       s{                   mJ    Map each column (in the original input) with block, and output with space as the separator
         2B                       All contiguous pairs of current column
           {            m         Map each pair with block
            Ev|r%                     Pair [j,k] to length of range [j..k-2]
                 b:m                  Repeat current repeating string to given length
                    ~                 Last line gives the result the pair should map to, now store it on the input stack
                     |(               Rotate current repeating string `p` times, where `p` is the length of the range [j..k-1]
                       ,              Fetch back the result
                         _s\      Zip with current column, filling missing element with empty string

```
> 0 votes

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


title: Some Lonely Primes

text:
# Question
Title: Some Lonely Primes
*I know, I know, yet **another** primes challenge...*

Related

A lonely (or isolated) prime is a prime number `p` such that `p-2`, `p+2`, `p-4`, `p+4` ... `p-2k`, `p+2k` for some `k` are all composite. We call such a prime a **`k`th-times-isolated prime.**

For example, a 5th-times-isolated prime is `211`, since all of `201, 203, 205, 207, 209, 213, 215, 217, 219, 221` are composite. (`p-2*5=201`, `p-2*4=203`, etc.)

### Challenge

Given two input integers, `n > 3` and `k > 0`, output the smallest `k`th-times-isolated prime that is strictly larger than `n`.

For example, for `k = 5` and any `n` in range `4 ... 210`, the output should be `211`, since that's the smallest 5th-times-isolated prime strictly larger than the input `n`.

### Examples

```
n=55 k=1
67

n=500 k=1
503

n=2100 k=3
2153

n=2153 k=3
2161

n=14000 k=7
14107

n=14000 k=8
14107

```

## Rules

* If applicable, you can assume that the input/output will fit in your language's native Integer type.
* The input and output can be given by any convenient method.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 4 votes
# Jelly, ~~17~~ 13 bytes

```
_æR+⁼ḟ
‘ç1#Ḥ}

```

Try it online!

### How it works

```
‘ç1#Ḥ}  Main link. Left argument: n. Right argument: k

‘       Increment; yield n+1.
    Ḥ}  Unhalve right; yield 2k.
 ç1#    Call the helper link with arguments m = n+1, n+2, ... and k until 1 one
        them returns a truthy value. Return the matching [m].

_æR+⁼ḟ  Helper link. Left argument: m. Right argument: k

_       Subtract; yield m-2k.
   +    Add; yield m+2k.
 æR     Prime range; yield the array of primes in [m-2k, ..., m+2k].
     ḟ  Filterfalse; yield the elements of [m] that do not occur in [k], i.e., [m]
        if m ≠ 2k and [] otherwise.
        The result to the left will be non-empty when m = 2k, as there always is
        a prime in [0, ..., 2m], since m > n > 3.
    ⁼   Test the results to both sides for equality.
        This yields 1 iff m is the only prime in [m-2k, ..., m+2k].

```

# Answer
> 3 votes
# Husk, 13 bytes

```
ḟ§=;ofṗM+ṡD⁰→

```

Try it online!

## Explanation

Pretty straightforward.

```
ḟ§=;ofṗM+ṡD⁰→  Inputs are k and n.
            →  Increment n
ḟ              and find the first number m >= n+1 such that:
         ṡD⁰    Take symmetric range [-2k,..,2k].
       M+       Add m to each.
    ofṗ         Keep those that are prime.
 §=             Check equality with
   ;            the singleton [m].

```

# Answer
> 2 votes
# Java 8, ~~144~~ 143 bytes

```
(n,k)->{for(k*=2;;)if(p(++n)>1){int i=-k;for(;i<=k&p(n+i)<2|i==0;i+=2);if(i>k)return n;}}int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}

```

**Explanation:**

Try it online.

```
(n,k)->{                      // Method with two integer parameters and integer return-type
  for(k*=2;                   //  Multiply `k` by 2
      ;)                      //  Loop indefinitely
    if(p(++n)>1){             //   Increase `n` by 1 before every iteration with `++n`
                              //   And if it's a prime:
      int i=-k;for(;i<=k      //    Loop `i` from `-k` to `k` (inclusive)
        &p(n+i)<2|i==0;       //    As long as `n+i` is not a prime (skipping `n` itself)
        i+=2);                //    And iterate in steps of 2 instead of 1
      if(i>k)                 //    If we've reached the end of the loop:
        return n;}}           //     We've found our result, so return it

// Separated method to check if `n` is a prime
// `n` is a prime if it remained unchanged, and not when it became 0 or 1
int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}

```

# Answer
> 2 votes
# JavaScript (Node.js), ~~94~~ ~~92~~ 89 bytes

```
f=(n,k)=>(Q=y=>y<-k||(P=(a,b=2)=>a>b?a%b&&P(a,b+1):1)(n+2*y)^!!y&&Q(--y))(k,++n)?n:f(n,k)

```

Try it online!

~~Mysteriously, further golfs end up stack overflow. Only this works at the size of 14000.~~

Finally one golf that won't end up stack overflow at 14000.

**Explanation**

```
f=(n,k)=>            // Two inputs
 (Q=y=>              // Function checking whether all numbers in
                     // [n-2*k, n+2*k] except n are all composite
  y<-k               // The counter runs from k to -k
                     // If none breaks the rule, return true
  ||(P=(a,b=2)=>     // Function checking primality
   a>b?              // Check if a>b
   a%b&&P(a,b+1)     // If a>b and a%b==0 return false, else proceed
   :1                // If a<=b return 1 (prime)
  )(n+2*y)^!!y       // If n+2*y is prime, then y must be 0
                     // If n+2*y is not prime, then y must be non-zero
                     // If none of the conditions are met, return false
  &&Q(--y)           // Else proceed to the next counter
 )
 (k,++n)?            // Add 1 to n first, then start the check
 n                   // If conditions are met, return n
 :f(n,k)             // Else proceed to the next n.

```

# Answer
> 2 votes
# Python 2, ~~105~~ 104 bytes

<sup>-1 byte thanks to ovs</sup>

```
n,k=input()
n+=1
while sum(all(x%i for i in range(2,x))^(x==n)for x in range(n-k*2,2*k-~n)):n+=1
print n

```

Try it online!

# Answer
> 2 votes
# Stax, 14 bytes

```
åΣ▀ë F▬&■º↔╔^∞

```

Run and debug it

This is the corresponding ascii representation.

```
w^x:r{Hn+|p_!=m0#

w                   while; run the rest of the program until a falsy value remains
 ^                  increment candidate value.
  x:r               [-x, ..., -1, 0, 1, ... x] where x is the first input
     {        m     map using block, using k from -x to x
      Hn+           double and add to candidate value - this is "p+2k"
         |p         is it prime? produces 0 or 1
           _!       k is zero?
             =      two values are equal; always true for a passing candidate
               0#   any falses left after mapping? if so, continue running

```

# Answer
> 1 votes
# Ruby \+ `-rprime`, ~~73~~ ~~71~~ ~~61~~ 57 bytes

```
->n,k{n+=1;(-k..k).all?{|i|(i*2+n).prime?^(i!=0)}?n:redo}

```

Try it online!

It feels good to be learning! I'm ~~using the `Integer#[]` and `redo` techniques that I learned here on PPCG.~~ getting lost in the weeds of fun techniques...

-1 byte: Use `n%2` instead of `n[0]` to get the least significant bit. Thanks, Asone Tuhid!

-1 byte: Use a ternary operator instead of a boolean expression. Thanks, Asone Tuhid!

-10 bytes: Use the XOR operator to avoid typing out `.prime?` twice... This is just as much Asone Tuhid's answer as mine now :)

-4 bytes: There's no harm in checking even values of `n`. Asone Tuhid is non-stop.

Ungolfed:

```
->n,k{
  n += 1;                   # Increment n
  (-k..k).all?{|i|          # In the set [n-2*k, n+2*k], is every number
    (i*2+n).prime? ^ (i!=0) #    EITHER prime XOR different from n itself?
  } ? n                     # If yes, return the current value of n
  : redo                    # Otherwise, restart the block
}

```

# Answer
> 1 votes
# C (gcc), 113 bytes

```
P(n,d,b){for(b=d=n>1;++d<n;)b=b&&n%d;n=b;}f(n,k,i,f){for(f=n;f;)for(f=i=!P(++n);i++<k;f|=P(n+i+i)|P(n-i-i));f=n;}

```

Try it online!

# Answer
> 0 votes
# Pari/GP, 55 bytes

```
f(n,k)=until(isprime(n++)&&#primes([n-2*k,n+2*k])<2,);n

```

Try it online!

# Answer
> 0 votes
# Perl 6, 63 bytes

```
{$^k;first {[grep *.is-prime,$_-2*$k..$_+2*$k]eqv[$_]},$^a^..*}

```

Try it online!

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


# Question
Title:   F̲o̲r̲m̲a̲t̲t̲e̲r̲ (*Unicode* **Markdown** __Formatter__)
If you cannot see this post, you can use this image

Your task is to create a markdown parser that outputs Unicode. It should support , , , and ̲̲̲̲̲̲̲̲̲.

Every alphabetical character should be converted into Math Sans. This includes the characters before an underline character.

Underlines: Add a `̲` character (code point 818) after each character. Underlines can be combined with anything else.

There should be no way to escape a control character.

### The following combinations should be supported:

(code point 120224 to 120275 Math Sans)

```  ``` (120432 to 120483 Math Monospace)

`*`  `*` (120328 to 120379 Math Sans Italic)

`**`  `**` (120276 to 120327 Math Sans Bold)

`***`  `***` (120380 to 120431 Math Sans Bold Italic)

`__` `̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲` `__` (818 Math Sans with Combining Low Line after each character)

`__``  `̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲̲`  ``__` (Math Sans Monospace with Combining Low Line)

Underline should also support Math Sans Italic, Math Sans Bold, and Math Sans Bold Italic

The final output should not contain the characters used to format the text.

### Nesting

Some things can be nested. Underlines can nest with any character and can be put in the inside or outside of another control character. Both of these will have an underline.

```
**Underlines __inside the bold__**
__Bold **inside the underline**__

```

Other things such as bold, monospace, bold italic, and italic can't nest because there are no characters for it.

```
**This is `not valid` input and will***never be given*

```

### Ambiguous Formatting Characters

Formatting characters that can be ambiguous will never be given. `**` is valid because it is bold, but `****` will never be given because it is undefined.

At the end of formatting characters, there will always be another character between the next formatting delimiter of the same character. `*format***ing**` will not be given because there should be a character before the next `*format* **ing**` delimiter using `*`s, however `*format*__ing__` could be given because they are different characters used in the delimiter.

```
**Which is bold ***and which is italic?* <-- Invalid, will never be given
**Oh I see** *now.* <-- Valid

```

### Escaping

Nothing can escape. There is no way to use any of the control characters except for a singular underscore

```
*There is no way to put a * in the text, not even \* backslashes* <-- All of the asterisks will be italic

Even __newlines
don't interrupt__ formatting <-- newlines don't interrupt will all be underlined

Because the singular _underscore is not a formatting character, it_is allowed_ and will not be removed

```

### Example I/O

Example I

```
*This* is_a **test** of __the ***markdown*** `parser`__ Multi-line `__should
be__ supported`. Nothing `can\` escape.

```

Example O

```
 _   ̲̲̲ ̲̲̲̲̲̲̲̲̲ ̲̲̲̲̲̲̲ - ̲̲̲̲̲̲
̲̲̲ .  \ .

```

This input is not valid and it doesn't matter what your program outputs:

```
*This **is not valid** input* because it nests italic and bold

*Neither `is this`* because it nests italic and monospace

*This***Is not valid** Either because it can be interpreted different ways

```

As this is , the shortest solution in bytes wins.

# Answer
> 5 votes
# Stax, 75 73 74 70 bytes

```
Ç╜ÿPÜV►♀b7╛i┴?τ\⌂:Té√╖■♠(µ`ómƒÜKx▬∙═τ½εxÅr∩!E#î⌡╕B┴zäÅéë┘S²↔óh₧≡6ÿ╖iô├

```

Run and debug it online

The basic approach is store the 4 types of formatting in a bit field, and then get the correct character offset from a lookup using the integer value. Only 8 values are in the lookup. The high bit denoting underline is handled separately.

Here's a commented ungolfed version.

```
m                       Map mode: for each line of input,
                            run the rest of the program, then output
"\*\*|__|."|F           Find all regex matches using pattern. This splits the string into
                            individual characters except for ** and __, which stay together.
                            These will be called "atoms" of the input.
{                       begin a block
  VAVa+                 Construct "ABC..XYZabc..xyz"
  "_*``_****__"_I       Get the index of the current atom in "_*`_****__"
  0|MY                  Take the maximum with zero, then store in register y.
                            This gives {*: 1, `: 2, **: 4, __: 8} and 0 for all else.
  x|^X                  Xor with the x register and write back. It stores bitflags for 4 modes.
  "&6mU*9*9 0E*9 !"!@   Index into codepoint lookup table using x.
  c52+|r                Build range of 52 consecutive values starting at codepoint.
  \$                    Build translation string by combination with the alphabetic string.
  |t                    Perform translation on the current atom.
  818+                  Add codepoint 818 to the current atom.
  x8<T                  Remove it again if x<8.  This is iff underline mode is off.
  y!*                   Multiply by the logical not of y.  If the atom is for formatting,
                        this eliminates output for this atom
m                       map over atoms using the enclosed block

```

Run this one

# Answer
> 2 votes
# Python 3, ~~267~~ ~~253~~ ~~243~~ ~~239~~ ~~235~~ ~~229~~ ~~226~~ 224 bytes

```
import re
def f(s):
 m=u=0;a='__','**','*','***','`'
 for c in re.findall(r'__|\*+|`|.|\n',s):
  if c in a:m,u=[a.index(c)-m,m,u,1-u][c=='__'::2]
  else:print([c,chr(120159+52*m+ord(c)-6*(c>'`'))][c.isalpha()]+'̲'*u,end='')

```

Try it online!

# Answer
> 2 votes
# Jelly, 87 bytes

```
JḤ
ØṖḟØAḟØa⁷;e€@Ọ¬
=Œua6+“¡ẓƬ’a@Ç+©O3ḷr1”*ẋ“`”ṭðO®œṣ+Ça¥¥€Ñ¦Ẏ©µ"“ƈ4hẊ‘ṪỌµœṣ⁾__p€Ñ¦818Ọ¤

```

Try it online!

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


title: Help John watch movies!

text:
# Question
Title: Help John watch movies!
# Introduction

So John finally has his holidays! And what better could he do than watching some movies. He indeed has a lot of movies to watch, but he is unable to decide which one to watch first. He has a list of movies, each in the format: `<Movie name> (<Year>)`. So he makes a simple set of rules to decide his order of watching movies.

1) The first preference is given to the release year. If a movie released a year or earlier than others, then he would watch them first.

2) If two or more movies released in the same year, and one of them begins with a number, then he would prefer to watch that movie first.

3) If two or more movies released in the same year begin with a number as well, then the movie which comes first on the original list would be watched first.

4) If two or more movies released in the same year begin with a letter, then the movie beginning with a letter which comes earlier in the English alphabet will be chosen first. If two movies begin with the same letter, then the one containing a lesser number of characters in the movie name(including spaces) will be chosen first.

5) If the number of characters is also same, then the movie which comes later in the original list would be watched first.

Well, what a great set of rules indeed. Now the challenge.

# Challenge

The input will be a list of movies, i.e, strings - all following the specified format, and you need to output the sorted list, following the above stated rules. Be case insensitive , i.e, treat both uppercase and lower case characters equally and assume all inputs to be valid, and the list will contain no duplicate elements. Also, every character in the movie name is either a letter, or a number and there are blank spaces only in between. You can assume the release year is 4 digits long.

# Examples

```
Input
Output

['The Town (2010)', 'The Prestige (2006)', 'The Departed (2006)']
['The Departed (2006)', 'The Prestige (2006)', 'The Town (2010)']

['Hello (2001)', '15 minutes (2001)', '25 Minutes (2002)']
['15 minutes (2001)', 'Hello (2001)', '25 Minutes (2002)']

['15 (1960)', '25 days (1960)']
['15 (1960)', '25 days (1960)']

['Jjjj (2004)', 'Hello (2004)']
['Hello (2004)', 'Jjjj (2004)']

['all gone (2018)', 'Be careful (2018)']
['all gone (2018)', 'Be careful (2018)']

['Be careful (2018)', 'all gone (2018)']
['all gone (2018)', 'Be careful (2018)']

```

# Scoring

This is , so the shortest code wins!

# Answer
# Python 3, 115 bytes

```
lambda a:sorted(a[::-1],key=lambda s:(s.split()[-1],-("/"<s[0]<":"),a.index(s)*("/"<s[0]<":"),s[0].lower(),len(s)))

```

Try it online!

-11 bytes thanks to spec change (thanks Jonathan Allan for pointing it out)
-6 bytes thanks to Lynn
> 3 votes

# Answer
# Red, 108 bytes

```
func[b][s: copy[]foreach m b[append/only s reverse split m"("]foreach m sort/all s[print rejoin[m/2"("m/1]]]

```

Try it online!

## Explanation:

```
f: func[b] [                                 the argument is a block of strings
    s: copy []                               prepare an empty block
    foreach m b [                            for each string in the input block
       append/only s reverse split m "("     split it on "(" and append in reversed order
    ]
    foreach m sort/all s [                   sort the new block
       print rejoin[m/2 "(" m/1]             and print it in the right order
    ]
]

```

Red's `sort/all` (sort function with refinement all) performs a stable sort, comparing all the fields of a compound argument:

```
sort/all [[1 2 3 1] [1 1 6] [2 1 3] [1 2 3 4]]
== [[1 1 6] [1 2 3 1] [1 2 3 4] [2 1 3]]

```
> 2 votes

# Answer
# PHP, ~~231 115~~ 113 bytes

PHP sort stabilized by using keys including the position

```
while($s=$argv[++$i])$a[substr($s,-6).($s<A?:$s&_).str_pad($s<A?$i:$argc-$i,$argc,0,0)]=$s;ksort($a);print_r($a);

```

Run with `php -nr '<code>' 'movie1 (year1)' 'movie2 (year2)' ...` or try it online.
> 2 votes

# Answer
# , ~~95~~ ~~87~~ 85 bytes

-2 thanks to Wheat Wizard

```
function(v)v[order(unlist(regmatches(v,gregexpr("[0-9]{4}",v))),tolower(v),nchar(v))]

```

Try it online!
> 2 votes

# Answer
# Perl 6, 58 bytes

```
*.sort({~m/\(\d+/,/^\d/??(0,$++)!!(1,.uc.ord,.chars,$--)})

```

Try it online!
> 2 votes

# Answer
# Jelly, 35 bytes

```
³i
ḲṪ$ḊṖV;1ịeØDƲ×Çṭ1Ɗ;Œlḷ/$;L;ÇN$µÞ

```

Try it online!

-4 bytes thanks to Mr. Xcoder
> 1 votes

# Answer
# Jelly,  ~~28 26 25~~  24 bytes

-1 thanks to Erik the Outgolfer (use a zip to replace pair then transpose)

```
µḲṚż>”<aŒlƲḢO;L;⁹iNƊȧ\ðÞ

```

A monadic link taking and returning lists of lists of characters.

**Try it online!** \- footer reformats the result like the input (which is interpreted as a list of lists of characters)

...or see a test-suite

### How?

```
µḲṚż>”<aŒlƲḢO;L;⁹iNƊȧ\ðÞ - Link: list of lists of characters, X
                                                     e.g. ["RV (2006)", "iChannel (2006)", "300 (2006)"]
                      ðÞ - sort by the following ðyadic key function (right is now X)
µ                        - ...start a monadic chain (left is now an item in X):
 Ḳ                       -   split at spaces              ["RV","(2006)"] / ["iChannel","(2006)"] / ["300","(2006)"]
  Ṛ                      -   reverse                      ["(2006)","RV"] / ["(2006)","iChannel"] / ["(2006)","300"]
          Ʋ              -   last four links as a monad:
     ”<                  -     literal '<' character (resides between digits*  and alphas ...* also the spaces and parentheses)
    >                    -     greater than? (vectorises) [1,1,0,0,0,0,0,0,0] / [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0] / [0,0,0,0,0,0,0,0,0,0]
        Œl               -     lower-case                 ["rv (2006)"] / ["ichannel (2006)"] / ["300 (2006)"]
       a                 -     AND (vectorises)           ['r','v',0,0,0,0,0,0,0] / ['i','c','h','a','n','n','e','l',0,0,0,0,0,0,0] / [0,0,0,0,0,0,0,0,0,0]
   ż                     -   zip together                 [["(2006)",'r'],["RV",'v'],[0],[0],[0],[0],[0],[0],[0]] / [["(2006)",'i'],["iChannel",'c'],['h'],['a'],['n'],['n'],['e'],['l'],[0],[0],[0],[0],[0],[0],[0]] / [["(2006)",0],["300",0],[0],[0],[0],[0],[0],[0],[0],[0]]
           Ḣ             -   head                         ["(2006)",'r'] / ["(2006)",'i'] / ["(2006)",0]
            O            -   cast to ordinal (vectorises) [[40,50,48,48,54,41],114] / [[40,50,48,48,54,41],105] / [[40,50,48,48,54,41],0]
                         -   (Jelly cannot compare characters with integers)
              L          -   length                       9 / 15 / 10
             ;           -   concatenate                  [[40,50,48,48,54,41],114,9] / [[40,50,48,48,54,41],105,15] / [[40,50,48,48,54,41],0,10]
                   Ɗ     -   last three links as a monad:
                 i       -     1st index of item in...
                ⁹        -     chain's right argument, X    1 /  2 /  3
                  N      -     negated                     -1 / -2 / -3
               ;         -   concatenate                  [[40,50,48,48,54,41],114,9,-1] / [[40,50,48,48,54,41],105,15,-2] / [[40,50,48,48,54,41],0,10,-3]
                     \   -   cumulative reduce with:
                    ȧ    -     AND (does not vectorise)   [[40,50,48,48,54,41],114,9,-1] / [[40,50,48,48,54,41],105,15,-2] / [[40,50,48,48,54,41],0,0,0]
                         -                           i.e. max / middle / min
                         -                                so the sort, Þ, reverses this input:
                         -                                ["300 (2006)", "iChannel (2006)", "RV (2006)"]

```
> 1 votes

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


# Question
Title: All non-empty finite sets of positive integers
The challenge is to create an iterator(/generator) which iterates (in any order so as to reach all of them... ie no set should occur at infinity) over all possible non-empty finite sets(/tuples/lists) of positive integers (hence demonstrating their countability).

Since the problem of verifying the correctness of a solution is undecidable in some cases, an accompanying explanation of how your program works and what order the sets are returned in would be helpful

Each finite set should occur exactly once. So if left running long enough, the iterator should eventually hit each of {1}, {3,5}, {17,29,306} etc. exactly once

# Answer
> 3 votes
### GolfScript, 21 characters

```
;]]0{)\{.2$+.p}%\1}do

```

A GolfScript version which prints all generated sets. It basically does the same as my Python version although not by recursion but instead collecting all possible sets in an array.

```
;        // clear the stack
]]       // put [[]] on the stack - the array of generated sets
            (initially an array with only the empty set)
0        // counter starts with zero
{        // start of infinite loop
  )      // increase counter
  \{     // map for each item of the array
    .    // duplicate item (i.e. this is a set)
    2$+  // append counter
    .p   // print the newly generated set
  }%\    // end of map => now the array contains all sets with max. up to counter
1} do    // end of infinite loop

```

# Answer
> 3 votes
Why mess with iterators and suchlike if we can just return an infinite (lazy) list?

## Haskell, 40

```
s(α:η)=[α]:(s η>>=(\κ->[κ,α:κ]))
c=s[1..]

```

Works thusly:

```
s(α:η)                    --the nonempty subsets of the list beginning with α, followed by η
   =[α]                   --  are: the singleton set [α]
      :(s η               --       and all nonempty subsets of η,
          >>=(\κ->[ κ     --         once on their own
                  , α:κ ] --         and once with α prepended to each of them.
                         ))
c=s[1..]       --c is the list of all nonempty subsets of the naturals.

```

Demonstration:

```
Prelude> take 16 c
[[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3],[4],[1,4],[2,4],[1,2,4],[3,4],[1,3,4],[2,3,4],[1,2,3,4],[5]]

```

# Answer
> 2 votes
### Python

*Note:* I wrote this version before the challenge became . I'll leave it here until I have a new one.

```
def allsets():

  def setswithmax(n):
    yield [n]

    for m in range(1,n):
      for s in setswithmax(m):
        yield s+[n]

  n = 1
  while n:
    for s in setswithmax(n):
      yield s
    n = n+1

```

It enumerates the sets with increasing maximum element, i.e. first of all it will generate all sets where max element is `1`, then `2`, ...

It does so by calling the generator `setswithmax` for increasing argument, which recursively builds these sets, i.e. a set with maximum `n` is obtained by iterating all sets with arbitrary max `<n` and then appending `n` to these sets.

You can see it in action on ideone.

# Answer
> 1 votes
### Scala 265:

```
object C extends Iterator[Set[Int]]{
var c=1
var M=1
var s=(1 to M)
var i:Iterator[Seq[Int]]=_
def n{i=s.combinations(c)}
def hasNext=true
n
def next:Set[Int]={
if(!i.hasNext)
if(c<M){
c+=1
n}else{c=1
M+=1
s=(1 to M)
n}
val r=i.next
if(r.max<M)next else r.toSet
}
}

```

Iterator is a well defined type in Scala, which means you have to declare what it returns (Set\[Int\]) in our case) and implement a method next and hasNext. For infinite Sets, hasNext trivially just returns true.

Here is code for testing:

```
object Cg6394IteratorTest extends App {
  val ci = C
  println (ci.take (1000).mkString ("\n"))
}

```

output:

```
Set(1)
Set(2)
Set(1, 2)
Set(3)
Set(1, 3)
Set(2, 3)
Set(1, 2, 3)
Set(4)
Set(1, 4)
Set(2, 4)
Set(3, 4)
Set(1, 2, 4)
Set(1, 3, 4)
Set(2, 3, 4)
Set(1, 2, 3, 4)

```

ungolfed:

```
object Cg6394Iterator extends Iterator [Set[Int]] {

  var curLength = 1
  var MAX = 1
  var source = (1 to MAX)
  var iter: Iterator [Seq[Int]] = _

  def init { iter = source.combinations (curLength)}
  def hasNext: Boolean = true

  init

  def next : Set[Int] = {
    if (! iter.hasNext)
      if (curLength < MAX) {
        curLength += 1
        init
       } else {
         curLength = 1
         MAX = MAX + 1
         source = (1 to MAX)
         init
       }
     val coll = iter.next ()
     if (coll.max < MAX) next else coll.toSet
  }
}

```

# Answer
> 0 votes
### Python, 88

Simple implementation, like mentioned, counter and checking for bits in binary representation.

```
def P():
 i=1
 while 1:yield [n+1 for n,x in enumerate(bin(i)[2:][::-1])if x=='1'];i+=1

```

# Answer
> 0 votes
# Stax, 7 bytes

```
âe¢-ï♂~

```

The link below adds a footer to output the generated sets

Run and debug online!

## Explanation

Uses ASCII representation to explain:

```
zWiRSca-
z           Empty set
 W          Loop forever
  iR        Range [1..current loop index]
    S       Powerset (*)
     ca-    Remove the powerset of [1..(current loop index-1)] from (*)

```

The footer is `mJ`, which outputs every generated set on a line, with the element separated by spaces.

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


# Question
Title: This challenge is about recursion (Cops' thread)
# Cops' thread

In this thread, your task is to make a recursion-based program/function to generate any integer series. Robbers will try and find a shorter non-recursive solution over in the **Robbers' thread**.

# Challenge synopsis

In many languages, recursive functions can significantly simplify a programming task. However, the syntax overhead for a proper recursion may limits its usability in code-golf.

The **cops** will create a program or function taking a single integer `n`, which will generate the first `n` entries of an integer series, **using only recursion**1. They should also make sure there is a shorter nonrecursive way to generate the sequence in order to mark their entry as safe.

The **robbers** will try to find a **shorter** program or function in the same language, generating the same integer series, **using no recursion**2.

If the cops' submission is not cracked within ten days (240 hours), the cop will prove it was in fact possible to have a shorter non-recursive approach by revealing their own solution. They may then mark their submission as **safe**.

**The winner of the cops challenge will be the shortest (according to ) recursion-based submission marked safe.**

The winner of the robbers challenge will be the robber who cracked the most solutions.

1: It only needs to be recursive in syntax; you don't need to worry about for example tail call optimization.

2: Again, non-recursive in syntax; so you can't post a recursive solution and claim its compiled to a loop thanks to tail call optimization.

# Submission requirements

Each submission will take a single integer `n` (zero- or one-based). The submission will then output or return the first `n` entries of an integer series of choice. (note that this integer series must not depend on `n`). The input and output method may differ between the recursive and non-recursive approach. The integer series may be any deterministic series with a length of at least 5. The series should be explained properly.

Your submission does not have to work for arbitrary large `n`, but should work for at least `n=5`. The non-recursive approach must be able to work up to at least the same `n` as the recursive approach, or up to `n=2^15-1`, whichever is smaller.

# Recursion

For the sake of this challenge, recursion is defined as creating the desired sequence using a **function** (or function-like construct) that **calls itself** (or calls a sequence of functions that ends up calling itself; this includes constructs like the Y combinator). The recursion depth should go to infinity as `n` goes to infinity. The non-recursive approach is anything that is **not** recursive.

# Answer
> 4 votes
# Python 3, 65 bytes (Safe)

```
f=lambda n,a=3,b=0,c=6,d=6:n*[1]and[a+b]+f(n-1,c,d,2*c+d,2*a+3*b)

```

Try it online!

Another try in Python.

The sequence is "the number of ways to fill a 2-by-n board with dominoes in three colors, so that no two same-colored dominoes touch each other". Not on OEIS.

---

Let's say `n=6`. The board looks like:

```
######
######
```

and these are valid domino tilings in three colors (`1-3` represent a color each):

```
123123 122331 212332 212121 113311
123123 133221 212112 212121 331133
```

but these are not (two same-colored dominoes are touching each other):

```
112323 332333 211113
112323 112311 233223
```

The sequence counts all possible domino tilings that satisfy the rules for each `n`.

---

# Intended solution, 58 bytes

```
n=int(input());a=3;b=12
for _ in[0]*n:print(a);a,b=b,a*4+b

```

Try it online!

Unfortunately it looks like no one bothered to simplify the recurrence relation, which was clearly shown in the recursive code. Making a program with the given double recurrence as-is doesn't work since it's Python 3.

# Answer
> 2 votes
# Octave, 47 bytes, cracked by l4m2

```
@(n)(f=@(r,m){@()[r(r,m-1),m],[]}{~m+1}())(f,n)

```

Try it online!

As an example, here is an Octave entry which generates the first `n` positive integers, https://oeis.org/A000027.

# Answer
> 2 votes
# Forth (gforth), 39 bytes, cracked by NieDzejkob

```
: | dup 1 > if dup 1 - recurse then . ;

```

Try it online!

# Answer
> 2 votes
# Python 3, 75 bytes, cracked by xnor

```
f=lambda n,a=[1]:a*n and[a[0]]+f(n-1,sorted({*a[1:],a[0]*2,a[0]*3,a[0]*5}))

```

Try it online!

The famous Hamming numbers, a.k.a. 5-smooth numbers (A051037).

### Cracked solution, 51 bytes

```
lambda n:[k for k in range(1,2**n)if 60**k%k<1][:n]

```

Try it online!

### Intended solution, 74 bytes

```
lambda n:sorted(2**(i%n)*3**(i//n%n)*5**(i//n**2)for i in range(n**3))[:n]

```

Try it online!

# Answer
> 2 votes
# Röda, 40 bytes

```
f x,a=1,b=2{[a];f x-1,a=b,b=a+b if[x>1]}

```

Try it online!

This function gives the following finite sequence (the 90 first Fibonacci numbers):

```
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269
2178309
3524578
5702887
9227465
14930352
24157817
39088169
63245986
102334155
165580141
267914296
433494437
701408733
1134903170
1836311903
2971215073
4807526976
7778742049
12586269025
20365011074
32951280099
53316291173
86267571272
139583862445
225851433717
365435296162
591286729879
956722026041
1548008755920
2504730781961
4052739537881
6557470319842
10610209857723
17167680177565
27777890035288
44945570212853
72723460248141
117669030460994
190392490709135
308061521170129
498454011879264
806515533049393
1304969544928657
2111485077978050
3416454622906707
5527939700884757
8944394323791464
14472334024676221
23416728348467685
37889062373143906
61305790721611591
99194853094755497
160500643816367088
259695496911122585
420196140727489673
679891637638612258
1100087778366101931
1779979416004714189
2880067194370816120
4660046610375530309

```

I know it can generate more Fibonacci numbers, but for purposes of this challenge it is enough to produce these numbers.

# Answer
> 1 votes
# JavaScript (Node.js), 91 bytes, Cracked by l4m2

```
f=x=>[w=~-x&&(g=(n,y=2)=>~-n&&(n<y?1:n%y?g(n,y+1):1+g(n/y,y)))(x)+f(x-1),console.log(w)][0]

```

Try it online!

Prints the first n terms of the OEIS sequence A022559 (starting from i=1).

**l4m2 fit 3 for loops into ~~74~~ 72 bytes and cracked my cop post:**

```
n=>{for(i=s=0;j=i++<n;console.log(s))for(x=i;j++<i;)for(;x%j<1;x/=j)s++}

```

**However, my intended answer actually has only 2 for loops:**

```
n=>{for(i=c=0;i++<n;console.log(c))for(p=2,z=i;p<=z;z%p?p++:(z/=p,c++));}

```

Try it online!

# Answer
> 1 votes
# x86 .COM function, 12 bytes, Cracked by NieDzejkob

```
0000 52                     push dx
0001 4A                     dec dx
0002 7403                   je 0007
0004 E8F9FF                 call 0000
0007 58                     pop ax
0008 F7E0                   mul ax
000A AB                     stosw

000B C3                     ret

```

Input DX, Output \[DI\] ~ \[DI+2\*DX-1\]

Cracker's solution:

```
0: 31 C0    xor ax, ax
2: BF 01 00 mov di, 1
5: 01 F8    add ax, di
7: AB       stosw
8: E2 FB    loop 5
A: C3       ret

```

Intended solution:

```
  xor bx,bx
c:inc bx
  mov ax,bx
  mul ax
  stosw
  loop c
  ret

```

# Answer
> 1 votes
# Gol\>\<\>, 15 bytes, cracked by mbomb007

```
I1AZZ;
M:K:?ZNB

```

Try it online!

The series is `0,1,2,3,4,5` but each element is followed by that many 0s.

For example, the first few values are:

```
 1: 0  First element, followed by 0 zeroes
 2: 1  Followed by 1 zero
 3: 0
 4: 2  Followed by 2 zeroes
 5: 0
 6: 0
 7: 3  Followed by 3 zeroes
 8: 0
 9: 0
10: 0
    etc.

```

# Answer
> 1 votes
# Python 3, 62 bytes, Cracked by mwchase

```
def f(x):
 if(x<1):return[1]
 return f(x-1)+[sum(f(x-1)[-2:])]

```

Try it online!

I feel like this one is going to be too easy...

The sequence is the Fibonacci sequence `f(n) = f(n-1) + f(n-2)` with `f(0) = f(1) = 1`

# Answer
> 0 votes
# JavaScript, 63 bytes, Cracked

```
f=x=>(x?[f(x-1)[0]&&1?3*f(x-1)[0]+1:f(x-1)[0]/2,...f(x-1)]:[7])

```

Try it online!

Returns the first n elements in a reversed array

# Answer
> 0 votes
# Windows .BAT, 80 Bytes

```
@set /a n=%1-1
@echo 8%3
@if 0 neq %n% @call %0 %n% 2%3 6%2%3

```

Usage:

```
CD <PATH>
<FILENAME> <N_1>
<FILENAME> <N_2>
<FILENAME> <N_3>

```

The loop version can assume in the current dictionary, but have to init or reset

# Answer
> 0 votes
# Python, 82 bytes; cracked

This is a recursive Python implementation of OEIS sequence A004001 in 82 bytes. More background on this series can be found on Wolfram's Mathworld.

```
def A(n):
 if n in[1,2]:return[1]*n
 S=A(n-1);return S+[S[S[n-2]-1]+S[n-S[n-2]-1]]

```

The first 30 numbers in this sequence are:

```
1, 1, 2, 2, 3, 4, 4, 4, 5, 6, 7, 7, 8, 8, 8, 8, 9, 10, 11, 12, 12, 13, 14, 14, 15, 15, 15, 16, 16, 16

```

---
Tags: code-golf, sequence, cops-and-robbers
---


# Question
Title: This challenge is about recursion (Robbers' thread)
# Robbers thread

In this thread, your task is to find a non-recursive solution which produces the same integer series of a submission not marked as 'safe' in the **Cops' thread**.

# Challenge synopsis

In many languages, recursive functions can significantly simplify a programming task. However, the syntax overhead for a proper recursion may limits its usability in code-golf.

The **cops** will create a program or function taking a single integer `n`, which will generate the first `n` entries of an integer series, **using only recursion.**1.

The **robbers** will try to find a **shorter** program or function in the same language, generating the same integer series, **using no recursion**2.

If the cops' submission is not cracked within ten days (240 hours), the cop will prove it was in fact possible to have a shorter non-recursive approach by revealing their own solution. They may then mark their submission as **safe**.

The winner of the cops challenge will be the shortest (according to ) recursion-based submission marked safe.

**The winner of the robbers challenge will be the robber who cracked the most solutions.**

1: It only needs to be recursive in syntax; you don't need to worry about for example tail call optimization.

2: Again, non-recursive in syntax; so you can't post a recursive solution and claim its compiled to a loop thanks to tail call optimization.

# Requirements

Each submission will take a single integer `n` (zero- or one-based). The submission will then output or return the first `n` entries of the same integer series as the cops' entry. The input and output method may differ between the recursive and non-recursive approach.

Your robbers' entry must be **strictly shorter** in byte-count than the recursive solution. It must work for at least the same `n`, or up to `n=2^15-1`, whichever is smaller.

# Recursion

For the sake of this challenge, recursion is defined as creating the desired sequence using a **function** (or function-like construct) that **calls itself** (or calls a sequence of functions that ends up calling itself). The recursion depth should go to infinity as `n` goes to infinity. The non-recursive approach is anything that is **not** recursive.

# Answer
> 3 votes
# Octave, by Sanchises 27 bytes

There are so many, many ways to do this in a loopy-way. For instance this one, if an explicit loop is needed:

```
for i=1:input('')disp(i)end

```

Try it online!

Or, if you want to create a vector (I haven't golfed this terribly well, since using a loop like this is kinda pointless):

```
x=0;for i=1:input(''),x(i)=i;end,x

```

Or 7 bytes if it's OK to not use a loop at all:

```
@(n)1:n

```

# Answer
> 3 votes
## Python 3, 75 bytes by Bubbler

**Python 3, 51 bytes**

```
lambda n:[k for k in range(1,2**n)if 60**k%k<1][:n]

```

Try it online!

Tests for 5-smoothness of `k` with `60**k%k<1`.

# Answer
> 1 votes
# JavaScript (Node.js), by user71546, ~~74~~ 72 Bytes

```
n=>{for(i=s=0;j=i++<n;console.log(s))for(x=i;j++<i;)for(;x%j<1;x/=j)s++}

```

# Answer
> 1 votes
# Gol\>\<\> by Jo King, 12 bytes iterative

```
I:FL:R0|rRN;

```

**Try it online**

Makes good use of `R`, the repeat command. Once I thought of this method, I knew it would be shorter than trying to use a for loop within a while loop.

**Explanation:**

```
I:              Input and duplicate (will be used at the end to print).
  F             For loop input times.
   L:           Push and duplicate loop counter (leaving one on the stack).
     R0         Pop counter and push that many zeros.
       |        End of loop.
        r       Reverse the stack.
         RN;    Print input times and halt.

```

List of language commands (`D` debug is useful for understanding what is going on)

Golfish

# Answer
> 1 votes
https://codegolf.stackexchange.com/a/158075/76323, 78 Bytes

```
def A(n):
 x=[1]*n
 for i in range(2,n):x[i]=x[x[i-1]-1]+x[i-x[i-1]]
 return x

```

# Answer
> 0 votes
# https://codegolf.stackexchange.com/a/157397/76323, 7 bytes assuming it's not recursive

```
@(n)1:n

```

or if use for,

```
function o=f(n);for i=1:n;disp(i);end;end;

```

# Answer
> 0 votes
# COM function, by l4m2, 11 bytes iterative

```
0: 31 C0    xor ax, ax
2: BF 01 00 mov di, 1
5: 01 F8    add ax, di
7: AB       stosw
8: E2 FB    loop 5
A: C3       ret

```

Input CX, output \[ES:1\] ~ \[ES:2\*CX\] (inclusive)

# Answer
> 0 votes
# Forth (gforth), by jmarkmurphy, 22 bytes iterative

```
: | 0 do i 1+ . loop ;

```

Try it online!

# Answer
> 0 votes
## Python 3 by PunPun1000, 59 bytes iterative

```
def f(x):
 l=[1]
 while x>0:l+=[sum(l[-2:])];x-=1
 return l

```

I tried my hardest to do a closed-form one-liner, but I only got as low as the original submission.

# Answer
> 0 votes
# JavaScript (Node.js), 45 bytes

```
x=>[...Array(x)].map(_=>h=h&1?3*h+1:h/2,h=14)

```

Try it online!

---
Tags: code-golf, sequence, cops-and-robbers
---


title: Cross platform... You wish

text:
# Question
Title: Cross platform... You wish
Write a program that will produce differing behaviors on as many different platforms as you can. Each differing platform awards one point (including an initial platform, meaning you can't score less than 1\*). Mechanisms intended for determining the target/executing platform (e.g. through platform compilation statements or APIs like .NET's Environment.OSVersion.Platform) must not be used. The answer with the highest score wins (where upvotes are the tiebreakers).

For example, consider the following program in the Blub language: `print (1+2)`. If this program were to print `3` on every platform it is compiled and run on, its score would be 1. However, if, for any reason, it were to print `4` on PDP-11s, its score would be 2. Etc. But the following C snippet, for example, is an invalid entry: `#ifdef WIN32 ... #endif`.

---

Definitions/details:

* *Distinct platform:* the combination of a) the hardware architecture b) the OS and its MAJOR version number (e.g. 1.0.0 and 1.1.0 are considered the same OS)
* *Differing behavior:* two behaviors are the same iff they produce similar side-effects (e.g. creating the same file with the same contents), or if the side-effect are errors of the same kind. For example, if a program segfaults on two distinct platforms, but the segfault message is different on these platforms, this is still considered the same behavior; while a program producing a zero-division error on one platform and a stack overflow (see what I did there? ;) error on another is producing different behavior.
* All undefined behaviors are considered equivalent.
* Program must be invoked in an equivalent manner on all platforms (however; this does mean you can pass command-line parameters if you so desire)

---

* Well, I guess you'd score zero if your program ran on zero platforms. But um... Yeah nevermind.

# Answer
# C

I will take a stab at it with a textbook-like example:

```
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char a[] = {1,2,3,4,5,6,7,8};
    if (sizeof(&a) > sizeof(int)) {
        printf("foo %d %d\n", *(int *)a, *(long *)a);
    } else {
        printf("bar %d %d\n", *(int *)a, *(long *)a);
    }
}

```

64-bit Platform prints: foo

32-bit Platform prints: bar

Little Endian Platforms: 67305985

Big Endian Platforms: 16909060

So there is at least 4 combinations.

On top of that, some very old platforms has `int` defined as 16-bits. And some platform has `long` defined as 64-bits. So the result will be different as well.

C has been quite platform specific, if you dig deep enough. It is not hard to come up with thousands of combinations (2^10+).
> 7 votes

# Answer
## 16/32/64-bit x86/x64 assembly, 16 bytes, 4 combinations

Byte-code:

```
31 C9 41 E2 0A 66 49 41 74 05 0F 00 C0 03 C1 C3
```

Disassembly (16-bit):

```
    xor  cx, cx ;cx=0
    inc  cx     ;cx=1
    loop l1     ;fall through
    dec  cx     ;cx=FFFF
    inc  ecx    ;cx=0000
    je   l1     ;branch taken
    ;...
l1: ret
```

Disassembly (32-bit):

```
    xor  ecx, ecx ;ecx=0
    inc  ecx      ;ecx=1
    loop l1       ;fall through
    dec  cx       ;ecx=0000FFFF
    inc  ecx      ;ecx=00010000
    je   l1       ;branch not taken
    sldt ax       ;detect VMware, VirtualPC, Parallels, etc.
    add  ecx, eax ;conditionally modify ecx
l1: ret
```

Disassembly (64-bit):

```
    xor   ecx, ecx ;rcx=0 (implicit 64-bit zero-extension)
    loopq l1       ;rcx becomes FFFFFFFFFFFFFFFF, branch taken
    ...
l1: ret
```

It returns:
\- CX=0000 in 16-bit mode;
\- ECX=10000 in 32-bit non-virtual mode;
\- ECX=(random) in 32-bit virtual mode;
\- RCX=FFFFFFFFFFFFFFFF in 64-bit mode.
> 3 votes

---
Tags: code-challenge
---


# Question
Title: Print the largest String with the shortest Code
As the title says, your task is to print the largest string using the shortest code without taking any input value.

## Rules

* The program must take no input and print the largest string to STDOUT
* The string must contain only ASCII Characters. If you don't know the ASCII Characters, take a look at the table
* No Loops are allowed
* No multiplication, exponentiation or any kind of elevation is permitted.
* The score is measured by subtracting the amount of bytes of your code to the amount of bytes of your string. Example. My code is `60` Bytes and it generates an string of `300` Bytes. My score will be `300-60=240`
* The highest score wins.

## Example

```
try{a.b}catch(e){alert(e)}
```

The output of my program is `ReferenceError: a is not defined` = 32 bytes

My Score will be `32-26` = 6

---

## Update

By Loops i mean any repetitive structure. For example `for`, `while`, `do while`, `recursive functions` etc..

# Answer
# R, 541-9 = 532

When passing a built-in function name to R, the console describes it parameters. I'm sure there are longer ones, but I went for the low-hanging fruit

Code:

```
.packages

```

Output:

```
function (all.available = FALSE, lib.loc = NULL)
{
if (is.null(lib.loc))
    lib.loc <- .libPaths()
if (all.available) {
    ans <- character()
    for (lib in lib.loc[file.exists(lib.loc)]) {
        a <- list.files(lib, all.files = FALSE, full.names = FALSE)
        pfile <- file.path(lib, a, "Meta", "package.rds")
        ans <- c(ans, a[file.exists(pfile)])
    }
    return(unique(ans))
}
s <- search()
invisible(.rmpkg(s[substr(s, 1L, 8L) == "package:"]))
}
<bytecode: 0x103fdf200>
<environment: namespace:base>

```

Edit: Thanks Giuseppe for the link
> 3 votes

# Answer
# Python 3, 937

```
help()

```

Try it online!
> 1 votes

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


title: Solve the busy beaver

text:
# Question
Title: Solve the busy beaver
Given a number `n`, calculates `BB(n)` (the maximum number of `1`s finally on the tape, among all halting 2-symbol n-state Turing machines with tape of zeros).

To solve the problem, you are given an extra (black-box) function **H** as input, which takes a function in your language (**f**) and returns a truthy/falsy value indicates whether this function will halt. However, the function **f** must not have any side-effects (I/O operations, timing, etc.) or call the halting function **H**.

Note that, there is no restriction on how you use the function **H**. A possible way is to use the function **H** to check if each Turing machine halts, and then simulate those to calculate the maximum, but there are other ways to compute `BB(n)`.

You need to prove that it solves such a problem. Shortest code in bytes wins.

Definition of Turing Machine:

```
Turing machines, each member of which is required to meet the following design specifications:

    The machine has n "operational" states plus a Halt state, where n is a positive integer, and one of the n states is distinguished as the starting state. (Typically, the states are labelled by 1, 2, ..., n, with state 1 as the starting state, or by A, B, C, ..., with state A as the starting state.)
    The machine uses a single two-way infinite (or unbounded) tape.
    The tape alphabet is {0, 1}, with 0 serving as the blank symbol.
    The machine's transition function takes two inputs:

        the current non-Halt state,
        the symbol in the current tape cell,

    and produces three outputs:

        a symbol to write over the symbol in the current tape cell (it may be the same symbol as the symbol overwritten),
        a direction to move (left or right; that is, shift to the tape cell one place to the left or right of the current cell), and
        a state to transition into (which may be the Halt state).

    There are thus (4n + 4)2n n-state Turing machines meeting this definition.
    The transition function may be seen as a finite table of 5-tuples, each of the form
    (current state, current symbol, symbol to write, direction of shift, next state).
```

# Answer
# Perl 5, ~~149~~ 147 bytes (+15 bytes if you want to be really strict)

Generates all Turing machines, use H as oracle to see if they halt and if so runs them, count the number of `1`s and take the maximum

```
#!/usr/bin/perl -p
$"=",",@t=1..$_;map{H($f=sub{my%v;$v{$n}=$1while/(A?)(\d+)(\W)$2$v{$n+=$3.1}/;map/A/,%v})&&\$G[&$f]}glob join"V{,A}{@t,0}{+,-}",0,<{@t}{,A}>;$_=$#G

```

Slightly breaks the conditions on `f` though not in an very bad way.

* `$n` is the starting position on the tape and is a global. So on each new run it starts where the previous Turing machine left off. But since the tape state ***is*** local and starts empty it doesn't matter where you start, so it's not actually used to communicate anything (adding `$n` to the `my` solves that at a cost of 5 bytes)
* I pass the actual Turing machine in global `$_`. That's also easily solved by e.g. a `for` loop over `my` variable `$g` and use it in `$f` via closure with `while$g=~/.../` at the cost of 10 bytes. However the current way has the advantage that I can also see `$_` inside `H` and return true for a few halting Turing machines so that I can really compute BB(1) and BB(2) and BB(3) (BB(3) takes 90 minutes on my computer)

Try it online!

The TIO link implements an actual (sort of) halting function in the header.

* The default version has the actual size 1 to 3 busy beaver hard-coded and returns true only for that particular Turing machine. All others return false
* If you add a `1` on the next input line after the size then `H` will be a real halting function but only for a tape that runs from `-10` to `10`. It will return false for any Turing machine that repeats its complete state or reaches the edge of the tape (so 19 tape positions can actually be used). It returns true for any Turing machine that halts on this restricted tape. This is enough to ***really*** calculate BB(1), BB(2) and BB(3) (you'll need lots of patience and memory for BB(3) but it does work). It also prints out some info about long running machines it finds along the way.
* If instead you add `-1` on the next input line after the size then `H` will behave like what is described for extra argument `1` but will also show the full execution trace of every Turing machine it tries.

Each Turing machines is represented by a strings that describe all input tuples with their corresponding output state. A tape value is either `A` (for `1`) or empty (for `0`). The states are numbered from `1` to `n`, `0` is the halting state. A tuple is the concatenation of:

```
value to write to tape (A or empty)
new state (1 to n or 0)
direction to move the head (+ or -)
input state (1 to n)
input tape value (A or empty)

```

The full string consists of a dummy `0` and then `2n` tuples in increasing order all separated by `V`. So for example a 2 state busy beaver Turing machine in this notation is:

```
0VA2+1VA2-1AVA1-2VA0+2A

```

which represents these 4 tuples:

```
A2+1     in state 1 seeing 0, write 1 move right go to state 2
A2-1A    in state 1 seeing 1, write 1 move left  go to state 2
A1-2     in state 2 seeing 0, write 1 move left  go to state 1
A0+2A    in state 2 seeing 1, write 1 move right go to state 0 (halt)

```
> 4 votes

---
Tags: code-golf, busy-beaver
---


# Question
Title: Print the positive non-zero integer n-tuple(s) that solve an inequality within a bound
Suppose I have a linear inequality like

> x0A0 \+ x1A1 \+ ... + xnAn \<= C

with xi a non-zero positive integer and Ai and C a positive non-zero multiple of `0.01`. Find all the positive integer n-tuples {x1,...,xn} such that:

> D \<= x0A0 \+ x1A1 \+ ... + xnAn \<= C

where D is also a positive non-zero multiple of `0.01`.

---

**Challenge:** Find the shortest code to produce the n-tuple solution(s) for any Ai, C, D.

---

Example: Let A0,A1=1, C = 2.5, and D=1.5. This gives

> 1.5 \<= x01+x11 \<= 2.5

Here, the (only) 2-tuple solution is {1,1}:

# Answer
# Haskell, 64 bytes

```
(d#c)a=[x|x<-mapM(\_->[1..c])a,y<-[sum$zipWith(*)x a],y>=d,y<=c]

```

Try it online! Defines a funktion `(#)` which takes D as first argument, C as second argument and A as a list as last argument and returns a list of possible X as lists. E.g. `(#) 1.5 3.5 [1,1]` yields the three solutions `[[1.0,1.0],[1.0,2.0],[2.0,1.0]]`.

---

### 61 bytes with D and C integers:

```
(d#c)a=[x|x<-mapM(\_->[1..c])a,elem(sum$zipWith(*)x a)[d..c]]

```

Try it online! E.g. `(#) 2 5 [1,1,2]` yields `[[1,1,1],[1,2,1],[2,1,1]]`.
> 1 votes

---
Tags: code-golf, math, linear-algebra
---


title: Mixed up output

text:
# Question
Title: Mixed up output
Write a function or program that outputs the following lines `<input>` time:

```
Hello World. Dlrow Olleh. Hwlrod Eoll.
Big Brown Fox. Xof Nworb Gib. Bbfgox Iro.

```

**EDIT**: It's "*B* rown *F* ox" not "brown fox".

This is so the program with the shortest bytecount wins!

# Answer
> 1 votes
# Ruby - 84 chars

```
"Hello World. Dlrow Olleh. Hwlrod Eoll.
Big brown fox. Xof Nworb Gib. Bbfgox Iro."*n

```

# Answer
> 5 votes
## vim - 82 strokes

```
oHello World. Dlrow Olleh. Hwlrod Eoll.
Big brown fox. Xof Nworb Gib. Bbfgox Iro.<ESC>

```

Type the number of repeats you want before entering this.

# Answer
> 2 votes
**Python ~~110~~ 105 Characters**

```
exec"print'Hello World. Dlrow Olleh. Hwlrod Eoll.\\nBig brown fox. Xof Nworb Gib. Bbfgox Iro.';"*input()

```

# Answer
> 1 votes
## JavaScript - 100 characters

```
while(n--)print('Hello World. Dlrow Olleh. Hwlrod Eoll.\nBig brown fox. Xof Nworb Gib. Bbfgox Iro.')

```

# Answer
> 1 votes
# D: 127 Characters

```
auto f(int n){return join(repeat("Hello World. Dlrow Olleh. Hwlrod Eoll.\nBig brown fox. Xof Nworb Gib. Bbfgox Iro.",n),"\n");}

```

More Legibly:

```
auto f(int n)
{
    return join(repeat("Hello World. Dlrow Olleh. Hwlrod Eoll.\nBig brown fox. Xof Nworb Gib. Bbfgox Iro.", n), "\n");
}

```

# Answer
> 1 votes
# PowerShell: 95

```
"Hello World. Dlrow Olleh. Hwlrod Eoll.`nBig Brown Fox. Xof Nworb Gib. Bbfgox Iro.`n"*(read-host)

```

Read-Host prompts the user for input, then the string is multiplied by that value and printed. This will have an extra newline at the end, but I don't see that as a constraint in the challenge.

# Answer
> 1 votes
# Whitespace, ~~761~~ 724 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_input_as_integer][T   T   T   _Retrieve_heap_at_0][S N
S _Duplicate][N
S S N
_Create_Label_LOOP][S N
N
_Discard_top][S S S T   N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate_input][N
T   T   T   N
_Jump_to_Label_EXIT_if_negative][S S S N
_Push_0][S S T  T   S T T   S S T   N
_Push_-89_\n][S S T T   T   S T S T N
_Push_-53_.][S S S T    T   S S N
_Push_12_o][S S S T T   T   T   N
_Push_15_r][S S T   T   T   S T S N
_Push_-26_I][S S T  T   S S S S T   T   N
_Push_-67_space][S S S T    S T S T N
_Push_21_x][S S S T T   S S N
_Push_12_o][S S S T S S N
_Push_4_g][S S S T  T   N
_Push_3_f][S S T    T   N
_Push_1_b][S S T    T   S S S S T   N
_Push_-33_B][S T    S S T   T   S N
_Copy_6th_space][S S T  T   T   S T S T N
_Push_-53_.][S S T  T   N
_Push_1_b][S S S T  T   S N
_Push_6_i][S S T    T   T   T   S S N
_Push_-28_G][S T    S S T   S S N
_Copy_4th_space][S S T  T   N
_Push_-1_b][S S S T T   T   T   N
_Push_15_r][S S S T T   S S N
_Push_12_o][S S S T S T S S N
_Push_20_w][S S T   T   S T S T N
_Push_-21_N][S T    S S T   S T N
_Copy_5th_space][S S S T    T   N
_Push_3_f][S S S T  T   S S N
_Push_12_o][S S T   T   S T T   N
_Push_-11_X][S T    S S T   T   N
_Copy_3rd_space][S S T  T   T   S T S T N
_Push_-53_.][S S S T    S T S T N
_Push_21_x][S S S T T   S S N
_Push_12_o][S S T   T   T   T   S T N
_Push_-29_F][S T    S S T   S S N
_Copy_4th_space][S S S T    S T T   N
_Push_11_n][S S S T S T S S N
_Push_20_w][S S S T T   S S N
_Push_12_o][S S S T T   T   T   N
_Push_15_r][S S T   T   S S S S T   N
_Push_-33_B][S T    S S T   S T N
_Copy_5th_space][S S S T    S S N
_Push_4_g][S S S T  T   S N
_Push_6_i][S T  S S T   T   N
_Copy_3rd_B][S S T  T   S T T   S S T   N
_Push_-89_\n][S S T T   T   S T S T N
_Push_-53_.][S S S T    S S T   N
_Push_9_l][S N
S _Duplicate_9_l][S S S T   T   S S N
_Push_12_o][S S T   T   T   T   T   S N
_Push_-30_E][S T    S S T   S S T   N
_Copy_9th_space][S S S T    N
_Push_1_d][S T  S S T   T   N
_Copy_3rd_o][S S S T    T   T   T   N
_Push_15_r][S S S T S S T   N
_Push_9_l][S S S T  S T S S N
_Push_20_w][S S T   T   T   S T T   N
_Push_-27_H][S T    S S T   T   S N
_Copy_6th_space][S S T  T   T   S T S T N
_Push_-53_.][S S S T    S T N
_Push_5_h][S S S T  S N
_Push_2_e][S S S T  S S T   N
_Push_9_l][S N
S _Duplicate_9_l][S S T T   S T S S N
_Push_-20_O][S T    S S T   T   S N
_Copy_6th_space][S S S T    S T S S N
_Push_20_w][S S S T T   S S N
_Push_12_o][S S S T T   T   T   N
_Push_15_r][S S S T S S T   N
_Push_9_l][S S T    T   T   T   T   T   N
_Push_-31_D][S T    S S T   S T N
_Copy_5th_space][S S T  T   T   S T S T N
_Push_-53_.][S S S T    N
_Push_1_d][S S S T  S S T   N
_Push_9_l][S S S T  T   T   T   N
_Push_15_r][S S S T T   S S N
_Push_12_o][S S T   T   T   S S N
_Push_-12_W][S T    S S T   T   S N
_Copy_6th_space][S S S T    T   S S N
_Push_12_o][S S S T S S T   N
_Push_9_l][S N
S _Duplicate_9_l][S S S T   S N
_Push_2_e][S S T    T   T   S T T   N
_Push_-27_H][N
S S S N_Create_Label_PRINTER
][S N
S _Duplicate][N
T   S N_Jump_to_Label_LOOP_if_0
][S S S T   T   S S S T T   N_Push_99
][T S S S _Add][T   N
S S _Print_as_character][N
S N
S N
_Jump_to_Label_PRINTER]

```

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

Try it online (containing the raw spaces, tabs and new-lines).

**Explanation in pseudo-code:**

```
integer i = input_as_integer
Start LOOP
  i = i-1
  if i is negative:
    EXIT
  Call function PRINT

function PRINT
  Print "Hello World. Dlrow Olleh. Hwlrod Eoll.\n
         Big Brown Fox. Xof Nworb Gib. Bbfgox Iro.\n
         "
  Go to the next iteration of LOOP

```

**Some things I did to golf it:**

* `SNS` (Duplicate) is used for repeated characters (`ll`)
* 99 is subtracted from every ASCII-value, which we'll add in the PRINT function to reduce loads of bytes. In Whitespace an integer/character is formed by using `SS` (Stack Manipulation: Push Number) + `S` or `T` (Positive or Negative) + some `T` / `S` (Binary representation of the number where `T=1` and `S=0`) + `N`. So having lower binary values and adding the 99 in the `PRINT` function is shorter than using the large binary values directly.
* Since creating the number for a space is 11 bytes (`SSTTSSSSTTN`), I copied the spaces from the last occurrences to the top of the stack instead. For example, after the first space is created in `\n.orI xogfbB`, I then use `STSSTTSN` (copy 6th to top) instead to copy the previous space. The largest distant between two spaces is 9, and since `STSSTSSTN` (copy 9th to top) is still 2 bytes shorter than `SSTTSSSSTTN` (create space) I've done this for all spaces to save bytes.
* I did something similar as with the copying of spaces above for every character that has a distance of 3 or less. This applies to the `B` in `Big B` and the `o` in `od Eo` (Note: The distance between both `b` in `b. Bb` is also three, but creating the number for `b` (`SSTTN`) is actually shorter than copying the 3rd value to the top of the stack (`STSSTTN`).)

# Answer
> 0 votes
## Game Maker Language, 107

```
repeat argument0{return "Hello World. Dlrow Olleh. Hwlrod Eoll.#Big Brown Fox. Xof Nworb Gib. Bbfgox Iro."}

```

# Answer
> 0 votes
# Java 8, 121 bytes

```
n->{for(;n-->0;System.out.println("Hello World. Dlrow Olleh. Hwlrod Eoll.\nBig Brown Fox. Xof Nworb Gib. Bbfgox Iro."));}

```

**Explanation:**

Try it online.

```
n->{           // Method with integer parameter and no return-type
  for(;n-->0;  //  Loop `n` times
    System.out.println("Hello World. Dlrow Olleh. Hwlrod Eoll.\n
                        Big Brown Fox. Xof Nworb Gib. Bbfgox Iro."));}
               //   And print this text + a trailing new-line that many times

```

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


title: Tips for golfing in Whitespace

text:
# Question
Title: Tips for golfing in Whitespace
What general tips do you have for golfing in Whitespace? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Whitespace (e.g. "remove comments" is not an answer).

Please post one tip per answer.

# Answer
I'm not entirely sure whether this is a joke question or not, so I hope I don't get mocked for taking it seriously, but...

# Tip 1: Don't End Your Program

The spec says that a program should be ended by three line-feeds, `[LF][LF][LF]`, where the first is the flow control IMP, and the next two are the quit command, but many interpreters will just run your code without the proper ending. Saves you 3 characters in any program.
> 12 votes

# Answer
# Tip 2: Use The Heap As Little As Possible

I used to use the Heap a lot for counting my loops and such, but realised it was actually extremely inefficient; first pushing an address, getting the current count, taking/adding one, re-pushing address, etc.

Now I just push a value on the stack to act as loop counter, then use the `[Space][LF][Tab]` swap command to get back to it when I need it. It takes a lot of working in/around, but when you get it it can really reduce your char count.
> 6 votes

# Answer
# Lower all characters by a fixed amount and add that right before printing in a loop

Credit to *@LukStorms*, who uses a similar approach in his answer for the Hello World challenge.

*(`STN` used for Space, Tab, and New-line respectively.)*

Pushing the values for letters is always 11 bytes (i.e. pushing the value 65 for the character 'A' is `SSSTSSSSSTN`; pushing the value 122 for the character 'z' is `SSSTTTTSTSN`). When you want to output large amount of text this can be expensive. Instead, you can lower the values of all the characters you want to print by a fixed amount, and then in the loop to print them add this fixed amount.

This can be done with the following code (let's assume the fixed value is 100 in this case):

1. Push all values for the characters (minus the fixed amount 100) in reverse order
2. `NSSN` (Create a Label\_0; basically starting the loop)
    1. `SSSTTSSTSSN` (Push the fixed amount 100)
    2. `TSSS` (Add the top two values of the stack together)
    3. `TNSS` (Pop and print the now correct value as character)
    4. `NSNN` (Jump to Label\_0; go to the next iteration of the loop)

This will stop the program with an error (which is allowed according to the meta) as soon as it tries to do the Add (`TSSS`) with nothing more on the stack. I've used this to golf this answer of mine (see items 5 and 6 of *Things I did to lower the byte-count*).

Whether a fixed amount of 100 is the shortest approach depends on what you are printing. *@LukStorm* for example used 107 in his Hello World answer.

Note that copying the top value (`SNS`) for two of the same adjacent characters (like the `l` in `Hello`), or copying values from another position can still be used in addition to this to golf more bytes.
> 6 votes

# Answer
# Use arbitrary heap addresses

Many interpreters allow you to read/write to arbitrary heap addresses instead of starting at 0 or 1 and counting up. You can duplicate an existing stack value (3 bytes) to use as an address instead of pushing a new value (minimum 4 bytes)
> 5 votes

# Answer
# The empty sequence is a valid label

`[LF][Space][Space][LF]` (Flow Control - Mark with the label '') creates an empty label that is a valid target for jumps or subroutine calls. This saves a byte when declaring the label and a byte every time it is called.

(Observed in the whitespace answer for implement a truth machine)
> 5 votes

# Answer
# Jumping to undefined labels ends the program (in some interpreters)

This starts to get into implementation specific behaviour, but I believe this is allowed.

TIO (and possibly other interpreters? doesn't work on ideone at least) will stop execution when an attempt is made to jump to a label that doesn't exist. If you need to do a comparison to break out of a loop this allows you to save bytes by not declaring the break label. (See my comment on Print Invisible Text for an example.)
> 5 votes

# Answer
# The value 0 can be declared as a number with no binary digits

The whitespace tutorial mentions that numbers can be any number of bits/binary digits wide. This means a number with no bits (beyond the required sign bit) is a valid representation of the value 0. `[Space][Space][Space][LF]` and `[Space][Space][Space][Space][LF]` both push the value 0 to the stack but the former is one byte shorter.
> 4 votes

# Answer
# Copying previous integers can be shorter than creating new ones

*(`STN` used for Space, Tab, and New-line respectively.)*

`STS` \+ Number argument can be used to *Copy the* n*th item on the stack (given by the argument) onto the top of the stack*. This can in some cases be used to save bytes.

For example, in this answer of mine I explained in the 4th item of *Things I did to lower the byte-count* how copying the 1st (0-indexed) value (`STSSTN`) is shorter than pushing 12 to create the character 'p' (`SSSTTSSN`) in the part `"pop"` of the output. (NOTE: I use the value 12 instead of 112 for the character 'p', because I've applied this other tip of lowering all values by a fixed amount, which we add before printing the characters in the loop.)
> 1 votes

---
Tags: code-golf, tips, whitespace-language
---