# Question
Title: Find All Digitroot Cyclic Sequences With Length Greater Than One
Digital sum, DR, Digit root is the iterative process of summing digits of a number until you end up with a single digit root number: e.g. digit root of 12345 is 6 since 1 + 2 + 3 + 4 + 5 = 15 = 1+5. Also look at Digit root challenge.

### Input:

Given integers `m` and `n` which are the modular and multiplier for sequence.

### Output:

Return all cyclic sequences of length greater than one for Digit roots of `n` * `i` in base `m` \+ 1.

* \\$1\\$\\$i\\$\\$m\\$
* \\$1\\$\\$DR(n\*i) \\$\\$m\\$
* \\$DR(i) = i \\$
* \\$DR(-m) = 0 \\$
* \\$|DR(-x)| \equiv DR(x) \equiv -DR(x)\\$ (mod \\$ m) \\$
* \\$DR(a+b) = DR(DR(a)+DR(b))\\$
* \\$DR(a-b) \cong (DR(a)-DR(b))\\$ (mod \\$ m) \\$

### Example Input:

```
9 4

```

### Example Output:

```
1 4 7
2 5 8

```

## More details:

```
m=9, n=4
DR(4*1) -> 4
DR(4*4) -> 7
DR(4*7) -> 1 = first i

```

A cycle happens when going through numbers 1 trough `m` taking digit root of `n` * `i` and then digit root of `n` * result of previous call and so on until returns to the first `i`.

Note that if there is no cycle taking digit root of `n` * `i` would simply result to `i`.

So we store this sequence in something like a hash set for all the `i`'s and then return all the sequences.

## Challenge

All the normal rules are applied excepts the answer with smaller sum of digit roots of each individual byte wins.

Example program of how to calculate the Σ digit sums of your code:

```
from sys import stdin
score=lambda s:sum((ord(c)-1)%9+1for c in s if ord(c)>0)
bytes=lambda s:"".join(str([ord(c)for c in s]).replace(',','').replace(']','').replace('[',''))
dr_bytes=lambda s:"".join(str([(ord(c)-1)%9+1for c in s]).replace(',',' +').replace(']',' =').replace('[',''))
code="\n".join(stdin.readlines())
print(bytes(code))
print(dr_bytes(code), end=' ')
print(score(code))

```

# Answer
> 2 votes
# Jelly, score = 104

```
x⁹Sḃ³Ṛḷ/)ƬR1¦z7MṖ’ƊPḄƊoEƊÐḟQ€

```

A dyadic Link accepting `m` on the left and `n` on the right that yields a list of lists of integers (each integer being a "digit").

**Try it online!**

The byte code is (see Jelly's code-page here):

```
120 137 83 231 131 182 218 47 41 152 82 49 5 122 55 77 203 253 145 80 172 145 111 69 145 15 235 81 12

```

So the score is:

```
3+2+2+6+5+2+2+2+5+8+1+4+5+5+1+5+5+1+1+8+1+1+3+6+1+6+1+9+3 = 104

```

### How?

```
x⁹Sḃ³Ṛḷ/)ƬR1¦z7MṖ’ƊPḄƊoEƊÐḟQ€ - Link: m; n
         Ƭ                    - collect inputs while unique, starting with m, applying:
        )                     -   for each d (where m is implicitly treated as [1..m]):
 ⁹                            -     n
x                             -     d repeated n times                    |
  S                           -     sum -> n×d            (cheaper than ×)|
    ³                         -     m
   ḃ                          -     n×d to bijective base m
     Ṛ                        -     reverse                               |
       /                      -     reduce by:                            |
      ḷ                       -       left argument       (cheaper than Ṫ)|
          R1¦                 - change the leading m to [1..m]
             z7               - transpose with filler 7   (cheaper than Z)|
                         Ðḟ   - discard those for which:
                        Ɗ     -   last three links as a monad:
                     Ɗ        -     last three links as a monad:
                  Ɗ           -       last three links as a monad:
               M              -         maximal (1-indexed) indices
                Ṗ             -         remove the last one
                 ’            -         decrement
                   P          -        product
                    Ḅ         -        from binary [cheap no-op to help use Ɗ]
                       E      -      all equal?
                      o       -      logical OR
                           Q€ - deduplicate each

```

# Answer
> 1 votes
# 05AB1E, score: ~~139~~ 125 (33 bytes)

```
Lε¸ΔR¬I*¹L¤иæ{ÙésèRнšRÙ].¡W]€нʒg≠

```

Inputs in the order \\$m,n\\$. Outputs as a list of lists.

Try it online (with `¹L¹иæ{Ùé` replaced with `¯¹ƒ¹LNã«}` so it won't timeout).

The codegolfed program would be **~~31~~ 28 bytes**:

```
Lε¸Δ¤I*¹L¹иæêésèθªÙ].¡ß}€нʒg≠

```

Try it online (with `¹L¹иæê` replaced with `¯¹ƒ¹LNã«}` so it won't timeout).

The bytes for this codegolfed program (in the 05AB1E codepage) would result in a score of ~~`154`~~ `145`:

```
[76, 6, 184, 17, 164, 73, 42, 185, 76, 185, 12, 230, 234, 233, 115, 232, 9, 170, 217, 93, 46, 161, 223, 125, 128, 14, 1, 103, 22]
4+6+4+8+2+1+6+5+4+5+3+5+9+8+7+7+9+8+1+3+1+8+7+8+2+5+1+4+4=145

```

Try it online.

To improve this score, the following modifications have been made:

* -3 score: `θ` \[pop and push last item\] (\[9\] → 9) to  \[reverse; pop and push first item\] (\[82,14\] → 1+5=6)
* -1 score: `ß` \[pop and push minimum\] (\[223\] → 7) to `W` \[push minimum without popping\] (\[87\] → 6)
* -6 score: `¤ ... ª` \[push last item without popping & append to list\] (\[164,170\] → 2+8=10) to `R¬ ... šR` \[reverse; push first item without popping & prepend to list; reverse\] (\[82,172,154,82\] → 1+1+1+1=4)
* -5 score: `}` \[close loop\] (\[125\] → 8) to `]` \[close all loops\] (\[93\] → 3)
* -2 score: `ê` \[sorted uniquify\] (\[234\] → 9) to  \[sort; uniquify\] (\[123,217\] → 6+1=7)
* -3 score: second `¹` \[push first input\] (\[185\] → 5) to `¤` \[push last item without popping\] (\[164\] → 2)

**Explanation (of the codegolfed program):**

For a language that's (almost) literally called `Base` (`05AB1E` converted from hexadecimal to a base-10 integer, and then to the default base-64 string), the lack of bijective base builtins is pretty annoying.. This is now done manually (with portion `¹L¹иæêésè` \- which will timeout for \\$m\geq4\\$).

```
L                 # Push a list in the range [1, (implicit) input `m`]
 ε                # Map each integer to:
  ¸               #  Wrap it in a list
   Δ              #  Continue looping until the list no longer changes:
    ¤             #   Push the last item of the list (without popping)
     I*           #   Multiply it by the second input `n`
       ¹L¹иæêésè  #   Convert it to bijective base-`m`:
       ¹L         #    Push a list in the range [1, input `m`]
         ¹и       #    Repeat it `m` amount of times
           æ      #    Get the powerset of this list
            ê     #    Uniquify and sort this list of lists
             é    #    (Stable) sort again by length
              s   #    Swap so the `i*n` is at the top
               è  #    Index it into this list
        θ         #   Pop and only leave the last value
         ª        #   Append this to the list
          Ù       #   Uniquify this list
 ]                # Close both the inner fixed-point loop and map
  .¡ }            # Group the resulting lists by:
    ß             #  Their minimum
      €           # For each group:
       н          #  Only leave the first list
        ʒ         # Filter the remaining lists by:
         g        #  Where the length of the list
          ≠       #  Is NOT 1
                  # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Python 3, score = 937 (228 bytes)

```
I=int(input())
R=int(input())
D=lambda v:v and~-v%I+1
J=lambda v:[D(R*m)for m in v]
d=list(range(1,I+1))
m=J(d)
v=[]
while m not in v:v+=[m];m=J(m)
exit([frozenset(m)for m in zip(*([d]+v))if max(m)in m[1:]!=m[0]==max(m)>min(m)])

```

Try it online!

Bytes:

```
73 61 105 110 116 40 105 110 112 117 116 40 41 41 10 10 82 61 105 110 116 40 105 110 112 117 116 40 41 41 10 10 68 61 108 97 109 98 100 97 32 118 58 118 32 97 110 100 126 45 118 37 73 43 49 10 10 74 61 108 97 109 98 100 97 32 118 58 91 68 40 82 42 109 41 102 111 114 32 109 32 105 110 32 118 93 10 10 100 61 108 105 115 116 40 114 97 110 103 101 40 49 44 73 43 49 41 41 10 10 109 61 74 40 100 41 10 10 118 61 91 93 10 10 119 104 105 108 101 32 109 32 110 111 116 32 105 110 32 118 58 118 43 61 91 109 93 59 109 61 74 40 109 41 10 10 101 120 105 116 40 91 102 114 111 122 101 110 115 101 116 40 109 41 102 111 114 32 109 32 105 110 32 122 105 112 40 42 40 91 100 93 43 118 41 41 105 102 32 109 97 120 40 109 41 105 110 32 109 91 49 58 93 33 61 109 91 48 93 61 61 109 97 120 40 109 41 62 109 105 110 40 109 41 93 41

```

Digit root of those bytes:

```
1 + 7 + 6 + 2 + 8 + 4 + 6 + 2 + 4 + 9 + 8 + 4 + 5 + 5 + 1 + 1 + 1 + 7 + 6 + 2 + 8 + 4 + 6 + 2 + 4 + 9 + 8 + 4 + 5 + 5 + 1 + 1 + 5 + 7 + 9 + 7 + 1 + 8 + 1 + 7 + 5 + 1 + 4 + 1 + 5 + 7 + 2 + 1 + 9 + 9 + 1 + 1 + 1 + 7 + 4 + 1 + 1 + 2 + 7 + 9 + 7 + 1 + 8 + 1 + 7 + 5 + 1 + 4 + 1 + 5 + 4 + 1 + 6 + 1 + 5 + 3 + 3 + 6 + 5 + 1 + 5 + 6 + 2 + 5 + 1 + 3 + 1 + 1 + 1 + 7 + 9 + 6 + 7 + 8 + 4 + 6 + 7 + 2 + 4 + 2 + 4 + 4 + 8 + 1 + 7 + 4 + 5 + 5 + 1 + 1 + 1 + 7 + 2 + 4 + 1 + 5 + 1 + 1 + 1 + 7 + 1 + 3 + 1 + 1 + 2 + 5 + 6 + 9 + 2 + 5 + 1 + 5 + 2 + 3 + 8 + 5 + 6 + 2 + 5 + 1 + 4 + 1 + 7 + 7 + 1 + 1 + 3 + 5 + 1 + 7 + 2 + 4 + 1 + 5 + 1 + 1 + 2 + 3 + 6 + 8 + 4 + 1 + 3 + 6 + 3 + 5 + 2 + 2 + 7 + 2 + 8 + 4 + 1 + 5 + 3 + 3 + 6 + 5 + 1 + 5 + 6 + 2 + 5 + 5 + 6 + 4 + 4 + 6 + 4 + 1 + 1 + 3 + 7 + 1 + 5 + 5 + 6 + 3 + 5 + 1 + 7 + 3 + 4 + 1 + 5 + 6 + 2 + 5 + 1 + 1 + 4 + 4 + 3 + 6 + 7 + 1 + 1 + 3 + 3 + 7 + 7 + 1 + 7 + 3 + 4 + 1 + 5 + 8 + 1 + 6 + 2 + 4 + 1 + 5 + 3 + 5 = 937

```

---
Tags: math, code-challenge, integer
---


# Question
Title: Build an optimizing Brainfuck compiler/interpreter
### the goal

Build an optimizing Brainfuck implementation. Whether it is a compiler, an interpreter, a JIT compiler, or whatever else is up to you.

### scoring

A reference implementation (`bfi`) will be given. Each implementation will run the same program (`mb.b`) also given at the end.

Your score is

```
time spent to run `mb.b` translated by `bfi`
/ time spent to run `mb.b` translated by your implementation

```

rounded to 3 decimal digits.

If `mb.b` through `bfi` runs in 20 seconds and through yours in 7 seconds, the score is `20 / 7 = 2.8571..` rounded to `2.857`.

If your implementation compiles `mb.b` to an intermediate or final form, such compilation time is not measured.

The time measurement will be done on your machine.(1)

### requirements

Your implementation should work on at least one platform, which may be an obscure one or even a virtual environment, but it should be able to also run the reference implementation for comparison.

You can rely on an existing backend such as `llvm`, or even a source-to-source compiler is possible. You can use any external program during the translation of the Brainfuck program.

### possible strategies

* Compile to native code rather than interpret it.
* Most machines can add or subtract arbitrary numbers very fast. You can replace a series of `+`, `-`, `>`, `<` to a single operation.
* Postpone pointer movements. `>+>->` can be translated to `p[1] += 1; p[2] -= 1; p += 3;`.
* Remove loops. A common way to zero a cell is `[-]`. This is the same as `p[0] = 0`. `[->+<]` is `p[1] += p[0]; p[0] = 0`.

### reference implementation

Compile the program with `gcc` version 9.3 or higher with the given flags. `gcc` 9.3 was released on March 12, 2020 and is ported to a variety of platforms. If you think this requirement is unreasonable for your target platform, let me know on the comments.

```
gcc -obfi -s -O3 -march=native bfi.c

```

**bfi.c**

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

typedef unsigned char byte;

static void interpret(byte *cp, byte *ip, int j) {
    byte *s[0x100];
    size_t i = -1;
    for (; *ip; ++ip) {
        if (!j) {
            switch (*ip) {
            case '>':
                ++cp;
                break;
            case '<':
                --cp;
                break;
            case '+':
                ++*cp;
                break;
            case '-':
                --*cp;
                break;
            case '.':
                putchar(*cp);
                break;
            case ',':
                *cp = getchar();
                break;
            case '[':
                if (*cp) {
                    s[++i] = ip;
                } else {
                    ++j;
                }
                break;
            case ']':
                if (*cp) {
                    ip = s[i];
                } else {
                    --i;
                }
            }
        } else if (*ip == '[') {
            ++j;
        } else if (*ip == ']') {
            --j;
        }
    }
}

int main() {
    static byte b[0x8000];
    FILE *f = fopen("mb.b", "r");
    fread(b + sizeof(b) / 2, 1, sizeof(b) / 2, f);
    fclose(f);
    interpret(b, b + sizeof(b) / 2, 0);
    return 0;
}

```

---

**mb.b** (pastebin, online interpreter)

---

(1) One may think that the scoring method is not fair because, I know, each machine has its own qualities and the score will be different across different machines. But, this is not a serious competition. I'm just providing a *puzzle*, some subject to think about, that might be interesting enough for some people to spend their time on. If someone comes up with an interesting algorithm, that is an interesting algorithm, nothing changes whether a *fair* score is there or not. The score is there just as a hint showing how effective the optimization was.

* While there are no rules to prevent you from optimizing *too specifically* for the test program, such as hard-coding the output directly, for example. I believe that won't be interesting to anyone including yourself, so please try to apply *general* optimizations if you'd like to participate.

# Answer
> 4 votes
# C++, 17.497/0.720=24.301

```
#include <stdio.h>
#include <stdlib.h>
int main() {
    freopen("mb.b", "r", stdin);
    freopen("2g.c", "wb", stdout);
    puts("char b[100000]; int main(){ char*p = b+50000;");
    while (1) {
        switch (getchar()) {
        case '+': puts("++*p;"); break;
        case '-': puts("--*p;"); break;
        case '>': puts("++p;"); break;
        case '<': puts("--p;"); break;
        case '[': puts("while(*p){"); break;
        case ']': puts("}"); break;
        case ',': puts("*p=getchar();"); break;
        case '.': puts("putchar(*p);"); break;
        case -1: goto done;
        }
    } done:;
    puts("}");
    fclose(stdout);
    system("gcc -s -O3 -march=native 2g.c -o 2g");
}

```

Just use the optimization of gcc

# Answer
> 3 votes
# Java with ObjectWeb ASM, \\${98.055\over19.52}\\$ = 5.023

Compiles BF to JVM bytecode. Applies optimizations such as collapsing `[-]` and collapsing multiple `<>+-` into one operation.

**One thing to note:** On my computer, the reference program crashes after printing 2/3 of the set. It takes 65.37 seconds before crashing, so I have manually adjusted my score using \\${2\over3} x = 65.37\\$

import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.ListIterator;

public class Main implements Opcodes {

    public static void main(String[] args) throws IOException {
        String program = Files.readString(Paths.get("mb.b"));
        Files.write(Path.of("Main.class"), compile(program));
    }

    private static byte[] compile(String program) {
        ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        writer.visit(V16, ACC_PUBLIC + ACC_SUPER, "Main", null, "java/lang/Object", null);
        writer.visitSource("Main.bf", null);

        // filter out unnecessary characters
        StringBuilder programBuilder = new StringBuilder();
        for (char c : program.toCharArray()) {
            if ("[]<>+-.,".indexOf(c) != -1) {
                programBuilder.append(c);
            }
        }
        program = programBuilder.toString();

        program = program.replace("[-]", "z");

        Deque<JumpPair> recurStack = new ArrayDeque<>();

        MethodVisitor mv = writer.visitMethod(ACC_PUBLIC + ACC_STATIC,
            "main",
            "([Ljava/lang/String;)V", null, null);
        mv.visitCode();

        // pointer, in var 0
        mv.visitInsn(ICONST_0);
        mv.visitVarInsn(ISTORE, 0);

        // memory, in var 1
        mv.visitLdcInsn(1000);
        mv.visitIntInsn(NEWARRAY, T_INT);
        mv.visitVarInsn(ASTORE, 1);

        ListIterator<Character> programIterator = program.chars().mapToObj(c -> (char) c).toList().listIterator();
        while (programIterator.hasNext()) {
            char c = programIterator.next();
            switch (c) {
                case '>' -> mv.visitIincInsn(0, count(c, programIterator));
                case '<' -> mv.visitIincInsn(0, -count(c, programIterator));
                case '+' -> {
                    mv.visitVarInsn(ALOAD, 1);
                    mv.visitInsn(DUP);
                    mv.visitVarInsn(ILOAD, 0);
                    mv.visitInsn(IALOAD);
                    chooseNumberInsn(count(c, programIterator), mv);
                    mv.visitInsn(IADD);
                    mv.visitVarInsn(ILOAD, 0);
                    mv.visitInsn(SWAP);
                    mv.visitInsn(IASTORE);
                }
                case '-' -> {
                    mv.visitVarInsn(ALOAD, 1);
                    mv.visitInsn(DUP);
                    mv.visitVarInsn(ILOAD, 0);
                    mv.visitInsn(IALOAD);
                    chooseNumberInsn(count(c, programIterator), mv);
                    mv.visitInsn(ISUB);
                    mv.visitVarInsn(ILOAD, 0);
                    mv.visitInsn(SWAP);
                    mv.visitInsn(IASTORE);
                }
                case '.' -> {
                    mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
                    load(mv);
                    mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "print", "(C)V", false);
                }
                case ',' -> {
                    mv.visitVarInsn(ALOAD, 1);
                    mv.visitVarInsn(ILOAD, 0);
                    mv.visitFieldInsn(GETSTATIC, "java/lang/System", "in", "Ljava/io/InputStream;");
                    mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/InputStream", "read", "()I", false);
                    mv.visitInsn(IASTORE);
                }
                case '[' -> {
                    JumpPair jumpPair = new JumpPair(new Label(), new Label());
                    recurStack.push(jumpPair);
                    load(mv);
                    mv.visitJumpInsn(IFEQ, jumpPair.nextLabel());
                    mv.visitLabel(jumpPair.thisLabel());
                }
                case ']' -> {
                    JumpPair jumpPair = recurStack.pop();
                    load(mv);
                    mv.visitJumpInsn(IFNE, jumpPair.thisLabel());
                    mv.visitLabel(jumpPair.nextLabel());
                }
                case 'z' -> {
                    mv.visitVarInsn(ALOAD, 1);
                    mv.visitVarInsn(ILOAD, 0);
                    mv.visitInsn(ICONST_0);
                    mv.visitInsn(IASTORE);
                }
            }
        }

        mv.visitInsn(RETURN);
        mv.visitMaxs(0, 0);
        mv.visitEnd();

        writer.visitEnd();

        return writer.toByteArray();
    }

    private static record JumpPair(Label thisLabel, Label nextLabel) {
    }

    private static int count(char c, ListIterator<Character> programIterator) {
        int count = 1;
        while (programIterator.hasNext() && programIterator.next() == c) {
            count++;
        }
        programIterator.previous();
        return count;
    }

    private static void chooseNumberInsn(int number, MethodVisitor mv) {
        switch (number) {
            case -1 -> mv.visitInsn(ICONST_M1);
            case 0 -> mv.visitInsn(ICONST_0);
            case 1 -> mv.visitInsn(ICONST_1);
            case 2 -> mv.visitInsn(ICONST_2);
            case 3 -> mv.visitInsn(ICONST_3);
            case 4 -> mv.visitInsn(ICONST_4);
            case 5 -> mv.visitInsn(ICONST_5);
            default -> {
                if (number > Byte.MIN_VALUE && number < Byte.MAX_VALUE) {
                    mv.visitIntInsn(BIPUSH, number);
                } else if (number > Short.MIN_VALUE && number < Short.MAX_VALUE) {
                    mv.visitIntInsn(SIPUSH, number);
                } else {
                    mv.visitLdcInsn(number);
                }
            }
        }
    }

    private static void load(MethodVisitor mv) {
        mv.visitVarInsn(ALOAD, 1);
        mv.visitVarInsn(ILOAD, 0);
        mv.visitInsn(IALOAD);
    }
}
```
</code></pre>

# Answer
> 2 votes
# Python 3 / gcc, 17.737/0.527 = 33.657

This simple solution is based on @l4m2's, compiling to C which is then compiled by gcc. It collapses blocks composed only of `<`, `>`, `+` and `-` as much as possible and also squashes the simplest possible loops, those which contain one block between `[` and `]`, have no overall data pointer movement, and change the loop counter by \\$\pm 1\\$.

A few years ago I wrote a much more complicated optimizing BF compiler (see comments above for the link) but the result is no faster than this on the Mandelbrot program.

```
#
# Python 3
#

import os
import sys

src = open('/tmp/bf.c', 'w')

print("""#include <stdio.h>

unsigned char b[100000];

int main(void)
{
  unsigned char *p = b + 50000;
  int c;
""", file=src)

def output_bb():
    global bb, ptr
    if start == '[':
        print("  while (*p != '\\0') {", file=src)
    elif start == ']':
        print("  }", file=src)
    elif start == '.':
        print("  putchar(*p);", file=src)
    elif start == ',':
        print("  *p = ((c = getchar()) == EOF ? '\\0' : (unsigned char)c);", file=src)
    else:
        assert start == '*'
    for ofs, diff in bb.items():
        if diff != 0:
            print(f"  p[{ofs}] += {diff};", file=src)
    if ptr != 0:
        print(f"  p += {ptr};", file=src)
    bb = {}
    ptr = 0

def optimize_bb():
    global bb, ptr
    for ofs, diff in bb.items():
        if diff != 0 and ofs != 0:
            print(f"  p[{ofs}] += {-diff * bb.get(0, 0)} * p[0];", file=src)
    print("  *p = '\\0';", file=src)
    bb = {}
    ptr = 0

bb = {}
ptr = 0
start = '*'

for ch in sys.stdin.read():
    if ch not in {'[', ']', '+', '-', '<', '>', ',', '.'}:
        continue

    if ch == ']' and start == '[' and ptr == 0 and bb.get(0, 0) in {1, -1}:
        optimize_bb()
        start = '*'
    elif ch == '+':
        bb[ptr] = bb.get(ptr, 0) + 1
    elif ch == '-':
        bb[ptr] = bb.get(ptr, 0) - 1
    elif ch == '<':
        ptr -= 1
    elif ch == '>':
        ptr += 1
    else:
        output_bb()
        start = ch

output_bb()

print("""  return 0;
}""", file=src)
src.close()

os.system("gcc -s -Wpedantic -W -Wall -Wextra -O3 -march=native -o /tmp/bf /tmp/bf.c")

```

---
Tags: code-challenge, interpreter, brainfuck, compiler
---


title: Give the inverse permutation

text:
# Question
Title: Give the inverse permutation
## Task

Given a finite permutation output its inverse.

You may take input and output in any reasonable format equivalent to a list of natural numbers. You may choose to use 0 indexing or 1 indexing. Your input and output format should be the same. You may assume a permutation has at least 1 element.

This is so the goal is to minimize the size of your source as measured in bytes.

## Permutations

A finite permutation is a function which takes an \\$n\\$-tuple and produces an \\$n\\$-tuple such that every element of the input is present in the output, and the ordering does not rely on the values of the inputs.

We can unambiguously represent these permutations with an \\$n\\$-tuple where each element is the index of where it will end up. For example:

$$ (3 \\,\\, 2 \\,\\, 1 \\,\\, 0) $$

This permutation reverses a \\$4\\$ element tuple. The first element goes to the 3rd (last) position, the second goes to the 2nd (penultimate) position etc.

With this representation a valid permutation is just any list of size \\$n\\$ which contains the numbers \\$0\\$ through \\$n-1\\$.

For a permutation \\$A\\$ the inverse permutation of \\$A\\$ is a permutation such that when applied after \\$A\\$ it restores the list to it's initial state.

For example \\$(3\\,\\,2\\,\\,1\\,\\,0)\\$ is the permutation that reverse the order of 4 elements. It is its own inverse since reversing twice gets you back to where you started. \\$(1\\,\\,2\\,\\,3\\,\\,4\\,\\,0)\\$ takes the first of 5 elements and moves it to the end, it has an inverse of \\$(4\\,\\,0\\,\\,1\\,\\,2\\,\\,3)\\$ since that takes the last of 5 elements and moves it to the front:

$$ (A,B,C,D,E) \\ \underset{\\,(1\\,\\,2\\,\\,3\\,\\,4\\,\\,0)\\,}{\xrightarrow{}}\\ (B,C,D,E,A) \\ \underset{\\,(4\\,\\,0\\,\\,1\\,\\,2\\,\\,3)\\,}{\xrightarrow{}}\\ (A,B,C,D,E) $$

Every permutation has an inverse.

## Test cases

```
[0] -> [0]
[0,1,2] -> [0,1,2]
[2,1,0] -> [2,1,0]
[1,2,0] -> [2,0,1]
[0,2,1] -> [0,2,1]
[1,2,0,5,4,3] -> [2,0,1,5,4,3]

```

# Answer
> 5 votes
# , 5 bytes

```
order

```

Try it online!

# , 26 bytes

```
function(x)match(seq(x),x)

```

Try it online!

Both 1-indexed.

# Answer
> 4 votes
# JavaScript (ES6), 28 bytes

Modifies the input list in-place.

```
a=>[...a].map((v,i)=>a[v]=i)

```

Try it online!

# Answer
> 4 votes
# MATL, 2 bytes

```
&S

```

Try it online!

Built-in, 1-indexed.

Get the second output of `sort`. Implicit input, implicit output.

### MATL, 4 bytes

```
fG&m

```

Try it online!

Just to make use of the "restricted to permutations" aspect of this question (mentioned in the question comments). Construct an array of 1:length(input), and find the position of each element of that in the input array.

Another option at 6 bytes: `t"X@@(`

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

```
Ordering

```

Try it online! 1-indexed (while the input can be either 0- or 1-indexed, the output is always 1-indexed). Plot twist: this generic builtin beats the specific builtin `InversePermutation` (not to mention that that builtin operates on Mathematica's custom permutation type, which would be hard to justify as being "equivalent to a list of natural numbers").

# Answer
> 2 votes
# Python 3, 35 31 bytes

```
lambda l:map(l.index,sorted(l))

```

Try it online!

Thanks to Jonathan Allan for the -4 bytes!

# Answer
> 2 votes
# K (ngn/k), ~~7~~ 1 bytes

```
<

```

built in.
old answer `{x?!#x}`

Try it online!

### Explanation

```
{x?!#x}   a function that takes a list x
 x?       indices of the elements in x
   !#x    in the range to length x

```

# Answer
> 2 votes
# Python 3 NumPy (not using builtin), 23 bytes

```
lambda L:L.put(L[L],+L)

```

Try it online!

Expects a numpy array and modifies it in-place.

# Python 3 NumPy (not using builtin), 29 bytes

```
lambda L:sorted(L,key=L.item)

```

Try it online!

This doesn't really use numpy except for the shorter `item` member which replaces the cumbersome `__getitem__`

# Python 3 NumPy (builtin), 20 bytes

```
lambda L:L.argsort()

```

Try it online!

This one requires the input to be a numpy array.

# Python 3 NumPy (builtin), 26 bytes

```
from numpy import*
argsort

```

Try it online!

# Answer
> 1 votes
# Builtin solutions

### APL / BQN, 1 byte

Try it on APLgolf! / Run with BQN!

### , 2 bytes

```
/:

```

Try it online!

### Jelly, 1 byte

Try it online! (1-indexed)

# Answer
> 1 votes
# Factor, 8 bytes

```
arg-sort

```

Try it online!

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

```
p->vecsort(p,,1)

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 56 bytes

```
\d+
$*
(?<=(?=(1*,)*(?<-2>1)*(?(2)^)(?!1))^(1*,)*)1*
$#1

```

Try it online! Link includes test cases. Explanation:

```
\d+
$*

```

Convert to unary.

```
1*

```

For each element...

```
(?<=^(1*,)*)

```

... find its index, ...

```
(?=(1*,)*(?<-2>1)*(?(2)^)(?!1))

```

... then find the index of the element with that as its value.

```
$#1

```

Replace the element with that index (in decimal).

# Answer
> 1 votes
# Julia 1.0, 8 bytes

```
sortperm

```

Try it online!

1-indexed

# Answer
> 1 votes
# flax, 1 byte

Builtin \o/

Unlike Jelly, flax is 0-indexed.

# Answer
> 1 votes
# Desmos, 20 bytes

```
f(l)=sort(sort(l),l)

```

Try It Desmos!

Try It Desmos! - Prettified

# Answer
> 1 votes
# x86-64 machine code, 11 bytes

```
8B 04 96 89 14 87 FF CA 79 F6 C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as an array of 32-bit integers; the address of the given permutation, as an array of 32-bit integers, in RSI; and the length of that array in EDX. The starting point is after the first 6 bytes.

In assembly:

```
r:  mov eax, [rsi+4*rdx]    # Load the entry at index EDX into EAX.
    mov [rdi+4*rax], edx    # Store the value of EDX into the result array at index EAX.
f:  dec edx     # (Start here.) Count down from the length in EDX.
    jns r       # Jump back if it isn't negative. (This will iterate from n-1 to 0.)
    ret         # Return.

```

# Answer
> 1 votes
# 05AB1E, 2 bytes

```
{k

```

0-based.

Try it online or verify all test cases.

**Explanation:**

```
{   # Sort the (implicit) input-list
 k  # Get the 0-based indices of each value in the (implicit) input-list
    # (after which the list is output implicitly as result)

```

# Answer
> 1 votes
# Haskell, 43 bytes

```
import Data.List
f p=snd<$>sort(zip p[0..])

```

Try it online!

Alternative 47 bytes using association list.

* saved 7 Bytes thanks to @Unrelated String
* added a maybe() to convert *maybe int* to just *int*, if a *just int* is acceptable it can be 37 Bytes.

```
f p|i<-zip p[0..]=maybe 0id.(`lookup`i).snd<$>i

```

Try it online!

# Answer
> 1 votes
# Python3, 27 bytes

```
def f(l):return l.argsort()

```

Try it online!

# Answer
> 0 votes
# Vyxal, 1 byte

Try it Online!

I suppose grading the list up also works.

## Vyxal, 9 bytes

```
Ṗ'2(?~İ)⁼

```

Try it Online!

## Explained

```
Ṗ'2(?~İ)⁼
Ṗ         # From all permutations of the input
 '        # Keep those where
  2(      #   Getting the result of
   ?~İ    #   [input[x] for x on tos]
      )   #   twice
       ⁼  #   equals the original item.

```

# Answer
> 0 votes
# Charcoal, 6 bytes

```
ＩＥθ⌕θκ

```

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

```
  θ     Input array
 Ｅ      Map over elements
   ⌕    Find index of
     κ  Current index
    θ   In input array
Ｉ       Cast to string
        Implicitly print

```

---
Tags: code-golf, permutations, abstract-algebra
---


title: root of root of root of root

text:
# Question
Title: root of root of root of root
This idea came to me when I saw my little brother playing with my calculator :D

# The task

Taking a integer as an input, print that many graphical square roots under each other, like this:

```
n = 1

  ___
\/ 1

n = 3
    _______
   / _____
  / / ___
\/\/\/ 3

n = 5

      ___________
     / _________
    / / _______
   / / / _____
  / / / / ___
\/\/\/\/\/ 5

n = 10

           ______________________
          / ____________________
         / / __________________
        / / / ________________
       / / / / ______________
      / / / / / ____________
     / / / / / / __________
    / / / / / / / ________
   / / / / / / / / ______
  / / / / / / / / / ____
\/\/\/\/\/\/\/\/\/\/ 10

```

Each root consists of 4 parts, which I'm going to very scientifically name:

(s is the root size on the stack of roots, n is the input number, x is the number of digits)

1. The "tail", which is a single `\`
2. The "wall", which consists of `/` * s
3. The "roof", which consists of `_` * 2 * s + x
4. And the number n under the smallest root, placed in the centre (leaving one empty space under the last `_` in the smallest root)

# Input

You must take input of the number `n`, no hardcoding the `n`

# Output

The ascii roots your program made

This is a code-golf challenge, so lowest byte count for each language wins!

# Answer
> 5 votes
# 05AB1E, 30 bytes

-4 bytes thanks to Kevin Cruijssen.

```
Lε-„/ ×'_y·¹g+×«y>ú}R„\/¹×¹‚ª»

```

Try it online!

# Answer
> 12 votes
# Python 2, ~~104~~ ~~94~~ ~~89~~ ~~81~~ 79 bytes

```
s=n=input()
while s:print' '*s,'/ '*(n-s)+'_'*(2*s+len(`n`));s-=1
print'\/'*n,n

```

Try it online!

Edit 1: Forgot I switched to python 2 lol

Edit 2: Thanks @ElPedro for the idea of switching to while loop!

Edit 3: Thanks @SurculoseSputum for saving 8 bytes!

Edit 4: Thanks @xnor for saving 2 bytes!

# Answer
> 11 votes
# JavaScript (ES6),  ~~104 102~~  99 bytes

A recursive function starting with the last line and using regular expressions to update each line above.

```
f=(n,s='\\/'.repeat(n)+(e=' ')+n)=>~n?f(n-1,e+s.replace(/\\/g,e).replace(/.(?!.*\/)/g,'_'))+`
`+s:e

```

Try it online!

## How?

### Initialization

We generate the bottom line with:

```
s = '\\/'.repeat(n) + (e = ' ') + n

```

For instance, this gives `"\/\/\/\/ 4"` for \\$n=4\\$.

### Recursion

We get rid of the backslashes with:

```
s.replace(/\\/g, e)

```

We create the 'roof' or increase its size with:

```
.replace(/.(?!.*\/)/g, '_')

```

which means: replace with an underscore each character that doesn't have any slash on its right.

This leads to:

```
 _________
 / _______
 / / _____
 / / / ___
\/\/\/\/ 4

```

And with a leading space inserted at each iteration:

```
     _________
    / _______
   / / _____
  / / / ___
\/\/\/\/ 4

```

# Answer
> 7 votes
# Erlang (escript), 188 bytes

```
f(0,N)->string:copies("\\/",N)++" "++integer_to_list(N);f(X,N)->string:copies(" ",X+1)++string:copies("/ ",N-X)++string:copies("_",2*X+floor(math:log10(N)+1))++"
"++f(X-1,N).
f(N)->f(N,N).

```

Try it online!

# Explanation

f(N)->f(N,N).   % Assign the counter to the input.
f(X,N)->        % While the counter isn't 0:
string:copies(" ",X+1)
                %     Repeat the space counter + 1 times

++string:copies("/ ",N-X)
                %     Repeat "/ " input - counter times

++string:copies("_",
                %     Repeat the "_" that many times:

2*X             %     The counter doubled
+floor(math:log10(N)+1)
                %     Plus the length of the digit(s) of the input
++"
"               %     Join the above, and append a newline
++f(X-1,N).     %     Decrement the counter by 1

f(0,N)->        % If the counter turns into 0:
string:copies("\\/",N)
                %     Repeat "\/" input times

++" "           %     Append a space
++integer_to_list(N);
                %     Append the number converted into a string
```
</code></pre>

# Answer
> 6 votes
# Mathematica (Notebook) 30 bytes

Only in Spirit ;-)

```
Nest[Defer@√#&,#,#]&@Input[]

```

produces the nested radicals

in the spirit but not the letter of the problem.

# Explanation

```
Input[]              //take input

Nest[f,expr,n]       //apply f to expr n times i.e. f[f[f[f[f....[expr]]..]] with n fs
Nest[f,#,#]&         //define a lambda that applies f to arg #, # times
Nest[f,#,#]&@Input[] //apply the lambda Nest[f,#,#]& to the value of Input[]

√#&                  //define a lambda that puts arg # inside √
Defer@√#&            //define a lambda that puts arg # inside √ buts keeps the mathematical square root unevaluated

Nest[Defer@√#&,#,#]&@Input[]
                     //apply the lambda Defer@√#& to Input, Input no of times

```

# Answer
> 4 votes
# Pyth, 34 bytes

```
VQj*N"/ ",*hJ-QNd*+l`QyJ\_;jd,*"\/

```

Try it online!

```
VQ

```

Loop the variable `N` over `0` to `Q` (the input) minus 1

```
j*N"/ "

```

Join the following using `N` instances of `"/ "`:

```
,

```

The two element list of...

```
*hJ-QNd

```

... {`Q` \- `N` \+ `1`} space characters (`d` is the space character in Pyth). Store the value of `Q` minus `N` in the variable `J` so we can use it later.

```
*+l`QyJ\_

```

... {`J` times 2, plus the number of digits of `Q`} instances of the string `"_"`

```
;

```

End of loop

```
jd,*"\/

```

Join the following using a space:

* `Q` instances of the string `"\/"`
* `Q` casted to a string

Conveniently, the string literal is implicitly closed, and the two `Q`s are implicitly appended to the end of the program.

# Answer
> 3 votes
# PowerShell, ~~88~~ 84 bytes

```
param($n)1..$n|%{' '*($m=$n- --$_)+' /'*$_+' '+'_'*(2*$m+"$n".length)}
'\/'*$n+" $n"

```

Try it online!

# Answer
> 2 votes
# Charcoal, 30 bytes

```
ＮηＧ↙η←⁺²Ｌθ↖η_Ｍη↘Ｐθ←←Ｆη«Ｐ↗⊕ι←/\

```

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

```
Ｎη

```

Input `n` as a number.

```
Ｇ↙η←⁺²Ｌθ↖η_

```

Print the "roof", ensuring that it is long enough to overhang `n`.

```
Ｍη↘Ｐθ←←

```

Print `n` as a string in the appropriate place.

```
Ｆη«

```

Loop `n` times.

```
Ｐ↗⊕ι

```

Print the next diagonal line of the "wall".

```
←/\

```

Print the next part of the "tail".

# Answer
> 2 votes
# MATL, 43 bytes

```
:P"@QZ"47Oh1X@qX"95GVn@E+Y"hh]'\/'1GX"0GVhh

```

Try it online!

First time I have used `X"`, `Y"`, `Z"` in the same answer!

# Answer
> 2 votes
# Jelly, 36 bytes

```
DLṭ1j+1,-,2×Ɱ$“ “/ “_”ẋ"ⱮṚṄ€ȧ⁾\/ẋ,⁸K

```

A full program which prints the result.

**Try it online!**

### How?

```
DLṭ1j+1,-,2×Ɱ$“ “/ “_”ẋ"ⱮṚṄ€ȧ⁾\/ẋ,⁸K - Main Link: integer, n
D                                    - digits (n)
 L                                   - length
  ṭ1                                 - tack to one
    j                                - join with (n)
             $                       - last two links as a monad - f(n):
      1,-,2                          -   [1,-1,2]
            Ɱ                        -   map across [1..n] with:
           ×                         -     multiplication
     +                               - add (left to each of right, vectorised)
              “ “/ “_”               - [' ', '/ ', '_']
                        Ɱ            - map across (the list of list of numbers) with:
                       "             -   zipped:
                      ẋ              -     repetition
                         Ṛ           - reverse
                          Ṅ€         - print each with trailing newlines
                            ȧ        - logical AND (with n) -> n
                             ⁾\/     - ['\', '/']
                                ẋ    - repeat (n times)
                                 ,⁸  - pair with n
                                   K - join with a space
                                     - implicit print

```

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), ~~217~~ 154 bytes

```
n=>Join("",Range(0,n).Select(i=>new S(' ',n-i+1)+new S('/',i*2)+new S('_',(n-i)*2-~(n+"").Length)+'\n').Concat(Repeat("\\/",n))).Replace("//", "/ ")+" "+n

```

Try it online!

Edit: Removed 19 bytes thanks to @KevinCruijssen, and used the header better(?)

# Answer
> 2 votes
# MathGolf, 32 bytes

```
{kî-⌠ *_£(∞k£+'_*û/ ï*\n}û\/k* k

```

Try it online.

**Explanation:**

```
{             # Loop the (implicit) input amount of times:
 k            #  Push the input-integer
  î-          #  Subtract the 1-based loop-index
    ⌠         #  + 2
      *       #  And repeat that many spaces
 _            #  Duplicate this string
  £           #  Pop and push its length
   (          #  + 1
    ∞         #  * 2
     k        #  Push the input-integer again
      £       #  Pop and push its length
       +      #  Add those two integers together
        '_*  '#  And repeat that many "_"
 û/           #  Push the 2-char string "/ "
    ï*        #  And repeat it the 0-based loop-index amount of times
 \            #  Then swap the top two strings on the stack
 n            #  And push a newline character
}û\/k*        # After the loop: repeat 2-char string "\/" the input amount of times
              # Push a space
 k            # And push the input-integer
              # (after which the stack is joined together and output implicitly)

```

# Answer
> 2 votes
# Wolfram Mathematica 120 bytes

```
a=StringRepeat;b=Print;Input[];
b[a[" ",#+1],a["/ ",%-#],a["_",2#+IntegerLength[%]]]&/@Range[%,1,-1];b[a["\/",%]," ",%];

```

# Explanation

```
StringRepeat[str,n]
                      //creates a string with str repeated n times

a=StringRepeat
                      //alias for StringRepeat

Print[expr1,expr2,...]
                      //prints expr1, expr2,... on a newline without separation

b=Print
                      //alias for Print

Input[]
                      //gets user input,

;
                      //Hide implicit output

%
                      //last output

IntegerLength[n]
                      //no of digits in n in base 10

a[" ",#+1]
                     //Make a lamba StringRepeat with arg #, that prints " ",#+1 times

b[a[" ",#+1],a["/ ",%-#],a["_",2#+IntegerLength[%]]]&

                     //Make a lambda with arg # that
                     //prints the appropriate "     /_________"
                     //depending on #

b[....]&/@Range[%,1,-1];
                     //map the lambda b[....] over {%,%-1,%-2,...,1}

b[a["\/",%]," ",%];
                     //print the last row "\/\/\/...\/ "

```

Link to notebook

# Answer
> 2 votes
# Haskell, 129 bytes

```
x%s=[1..x]>>s
0#b=b%"\\/"++' ':show b
x#b=(x+1)%" "++(b-x)%"/ "++(show b>>"_")++x%"__"++'\n':(x-1)#b
f x=x#x
main=interact$f.read

```

Try it online!

Ties the existing 129 byte answer but is compliant with the challenge by performing full IO.

# Answer
> 1 votes
# Retina 0.8.2, 77 bytes

```
^
$.'$*_=$'$*/¶$'$*V
/
=$.%'$*=¶  $.%'$* $`
=
__
(_+)(/+)
$2$1
/
/
V
\/
1A`

```

Try it online! Explanation:

```
^
$.'$*_=$'$*/¶$'$*V

```

Insert some working elements: enough `_`s to cover the input, a `/` for each input, then on the next line, a `V` for each input (representing `\/`) and a space.

```
/
=$.%'$*=¶  $.%'$* $`

```

Now expand the `/`s into a bottom right triangle, and also add extra `_`s to overhang on both sides on each line.

```
=
__

```

Expand the `=`s which were placeholders for two `_`s.

```
(_+)(/+)
$2$1

```

Move the input cover next to the rest of the overhang.

```
/
/

```

Space the `/`s apart.

```
V
\/

```

Expand the `V`s on the last line.

```
1A`

```

Delete some left-overs.

# Answer
> 1 votes
# Haskell, 129 bytes

```
r=replicate
c=(concat.).r
f n|s<-show n=unlines$map(\o->r(n-o+1)' '++c o"/ "++r(2*(n-o)+length s)'_')[0..n-1]++[c n"\\/"++" "++s]

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~100~~, 99 bytes

```
n=int(input())
for i in range(n):print(" "*(n+~i)," /"*i,"_"*(2*n-2*i+len(str(n))))
print("\/"*n,n)

```

Try it online!

thnx to @KevinCruijssen for -1

# Answer
> 1 votes
# Java 11, ~~137~~ 124 bytes

```
n->{String l="\\/".repeat(n)+" "+n,r=l;for(;n-->0;r=l+"\n"+r)l=" "+l.replace('\\',' ').replaceAll(".(?!.*/)","_");return r;}

```

-13 bytes by porting *@Arnauld*'s JavaScript answer, so make sure to upvote him!

Try it online.

**Explanation:**

```
n->{                       // Method with integer parameter and String return-type
  String l=                //  Temp-String `l` for the current line, starting at:
           "\\/".repeat(n) //   The input amount of "\/"
           +" "+n,         //   appended with a space and the input
         r=l;              //  Result-String, starting at this (last) line
  for(;n-->0               //  Loop `n` amount of times:
      ;                    //    After every iteration:
       r=l+"\n"+r)         //     Prepend the new `l` with newline to the result-String
    l=                     //   Change `l` to the new line:
      " "                  //    A space
      +l                   //    appended with the current line, with the replacements:
        .replace('\\',' ') //     All '\' replaced with spaces
        .replaceAll(".(?!.*/)","_");
                           //     And all characters NOT followed by a '/' with a "_"
  return r;}               //  And return the result-String after the loop

```

# Answer
> 1 votes
# Julia, 107 bytes

```
n=parse(Int,readline())
println.([[" "^(s+1)*"/ "^(n-s)*"_"^(2s+length("$n")) for s=n:-1:1];"\\/"^n*" $n"])

```

Try it online!

## Breakdown

```
n = parse(Int, readline())
println.([ # broadcasting with `.` applies `println` to each element of vector
    [
        " "^(s + 1)*"/ "^(n - s)*"_"^(2s + length("$n"))
        for s ∈ n:-1:1 # array comprehension
    ];   # semicolon enables blockmatrix-style array syntax...
         # ...which unpacks elements in array above into elements of vector
    "\\/"^n*" $n" # last element of vector
])

```

# Answer
> 1 votes
# Perl 5 `-ap`, 86 bytes

```
$\=$/.'\\/'x$_." $_";$_=$"x($_+1).'_'x(2*$_+y///c);for$a(1.."@F"-1){say;s, /| __,/ ,g}

```

Try it online!

# Answer
> 1 votes
# CJam, 46 bytes

```
li:A:B;{A)S*"/ "BA-*'_2A*Bs,+*NA(:A}g"\\/"B*SB

```

Try it online!

Port of my Python answer

Explanation:

```
li            take input as integer
:A:B;         assign that to the variables A and B
{             start of while A loop
A)S*          push A-1 spaces
"/ "BA-*      push B-A strings of "/ "
'_2A*Bs,+*    push 2A + the number of digits _
N             push a newline
A(:A          decrement A
}g            end of while loop
"\\/"B*       push B \/
SB            push B after a space

```

# Answer
> 1 votes
# Haskell, 122 bytes

```
x%y=[1..x]>>y
f x|n<-read x=unlines[(n+1-i)%" "++i%"/ "++(n-i)%"__"++(x>>"_")|i<-[0..n-1]]++n%"\\/"++' ':x
main=interact f

```

Try it online!

I've deliberately constrained myself to standard I/O. See my comments on the question.

# Answer
> 1 votes
# Vyxal `So`, 30 bytes

```
ɾṘ›?ʀṪ‛/ *꘍?ɾd?L+\_*Ṙ+⁋,‛\/*$"

```

Try it Online!

This code's sorta backwards to reduce stack operations.

```
           ?ɾd                 # (1...input) * 2
              ?L+              # + log_10(input)
                 \_*           # That many underscores for each
                    Ṙ+         # Reverse that, and append to...
ɾṘ›                            # (2...input+1) reversed
          ꘍                    # For each, that many spaces appended to each of...
   ?ʀṪ                         # 0...input-2
      ‛/ *                     # For each, that many copies of "/ "

                      ⁋,       # Print that, joined on newlines
                        ‛\/*   # Input * "\/"
                            $" # Paired with input
                               # (So flags) print that joined by a space

```

# Answer
> 0 votes
# Perl 5, 96 bytes

```
sub f{$n=pop;join"\n",(map' 'x($x=1+$n-$_).'/ 'x$_.'_'x($x*2-2+length$n),0..$n-1),'\/'x$n." $n"}

```

Try it online!

# Answer
> 0 votes
# PHP, 121 bytes

```
for($x=($i=$j=$argn)/10+1,$f=str_repeat;$i;$c.="/ ")printf("%{$i}s $c%s\n"," ",$f("_",2*$i--+$x));echo$f("\\/",$j)." $j";

```

Try it online!

This is not that great maybe, but I came with this.

# Answer
> 0 votes
# Pyth, ~~54~~ 44 bytes

```
VQ+d++*-QNd*"/ "N*+*2-QNl+""Q"_";++*"\/"hNdQ

```

Try it online!

edit 1: Thanks @mathjunkie for saving 10 bytes!

# Answer
> 0 votes
# Pip, 38 bytes

```
Fi,aP[sYsXa-i"/ "Xi'_Ma.y.y]"\/"Xa.s.a

```

Try it online!

### Explanation

This is one of those very rare occasions in Pip when a for loop seems to be the shortest solution.

```
Fi,aP[sYsXa-i"/ "Xi'_Ma.y.y]"\/"Xa.s.a
                                        s is space; a is 1st command-line arg (implicit)
Fi,a                                    For i in range(a):
    P                                    Print, with a newline
     [                     ]             the contents of this list, implicitly concatenated:
      s                                   A space
        sXa-i                             Space, repeated (a-i) times
       Y                                   also, yank that string into the y variable
             "/ "Xi                       "/ ", repeated (i) times
                      a.y.y               Concatenate a with y twice
                   '_M                     and replace each character with an underscore,
                                           giving a string of len(a) + 2 * (a-i) underscores
                            "\/"Xa      "\/", repeated (a) times
                                  .s    concatenated to space
                                    .a  concatenated to a
                                        Autoprint (implicit)

```

# Answer
> 0 votes
# Scala, 91 bytes

```
n=>print(n.to(1,-1).map{i=>" "*(i+1)+"/ "*(n-i)+"_"*(2*i+1)}:+("\\/"*n+" "+n)mkString "\n")

```

Try it online!

# Answer
> 0 votes
# MAWP, 138 bytes

```
%@![1A~!~]%![!!!1M[84W;1A]%\A[95W2M;84W;1A]%2W1M3A{3M[29W1M5W;1A]25W;%1A}]~!!0/[25WP~1M~]%\1A3M[29W1M5W;1A]25W;%[99W25WM1M;95W2M;1A]%84W;:

```

Works as expected for single digit numbers, but beyond that, the last root will be longer than the others.

Try it!

# Answer
> 0 votes
# Husk, 46 bytes

```
`:§+*"¦/"o:' s¹z+mR' ṫ¹m§+*" /"(:' R'_+L¹D≠¹)ŀ

```

Try it online!

# Answer
> 0 votes
# Java (JDK), ~~139~~ 171 bytes

```
String g(int k){return g(0,k);}String g(int i,int n){return i<n?" ".repeat(n-i+1)+"/ ".repeat(i)+"_".repeat((n-i)*2+(""+n).length())+"\n"+g(++i,n):"\\/".repeat(n)+" "+n;}

```

Try it online!

No for loop, recursion is used. Therefor I had to define the function as a method because I couldn't find a way to define it as a BiFunction lambda expression and call it recursively. The method has 2 inputs: zero as first argument, the integer input parameter as second. And thus added an overloaded method with only one parameter.

## Explained

```
String g(int i,int n) {                          // i is current index (start with 0), n is the input parameter value
  return i<n?                                    // are we not yet at the end?
         " ".repeat(n-i+1)                       // add spaces
          +"/ ".repeat(i)                        // add i times '/ '
          +"_".repeat((n-i)*2+(""+n).length())   // add underscores, including extra for the length of the input value
          +"\n"                                  // add CRLF
          +g(++i,n)                              // recursive call with i+1
         :
         "\\/".repeat(n)+" "+n                   // at last i=n, add \/ + input parameter value
;}                                               // what goes open, must be closed

```

Called as

```
System.out.println(g(10));

```

139 -\> 171 : to make it acceptable with only 1 input parameter (@Razetime)

---
Tags: code-golf, ascii-art
---


title: Generate Fmbalbuena Numbers

text:
# Question
Title: Generate Fmbalbuena Numbers
My user id is `106959`

How to check if the number is Fmbalbuena number?

First Step: Check if the number of digits is a multiple of 3: `6` = `3` * `2`

Second step: Split the digits into even thirds: `106959 -> 10 69 59`

Third step: Subtract the first set of digits from the second modulo 10: `6` \- `1` = `5`, `9` \- `0` = `9`

Last step: Check that the result is the same as the third set of digits: `59 = 59`

## Sequence

Here is the sequence until `106959`

```
109, 110, 121, 132, 143, 154, 165, 176, 187, 198, 208, 219, 220, 231, 242, 253, 264, 275, 286, 297, 307, 318, 329, 330, 341, 352, 363, 374, 385, 396, 406, 417, 428, 439, 440, 451, 462, 473, 484, 495, 505, 516, 527, 538, 549, 550, 561, 572, 583, 594, 604, 615, 626, 637, 648, 659, 660, 671, 682, 693, 703, 714, 725, 736, 747, 758, 769, 770, 781, 792, 802, 813, 824, 835, 846, 857, 868, 879, 880, 891, 901, 912, 923, 934, 945, 956, 967, 978, 989, 990, 100090, 100191, 100292, 100393, 100494, 100595, 100696, 100797, 100898, 100999, 101000, 101101, 101202, 101303, 101404, 101505, 101606, 101707, 101808, 101909, 102010, 102111, 102212, 102313, 102414, 102515, 102616, 102717, 102818, 102919, 103020, 103121, 103222, 103323, 103424, 103525, 103626, 103727, 103828, 103929, 104030, 104131, 104232, 104333, 104434, 104535, 104636, 104737, 104838, 104939, 105040, 105141, 105242, 105343, 105444, 105545, 105646, 105747, 105848, 105949, 106050, 106151, 106252, 106353, 106454, 106555, 106656, 106757, 106858, 106959

```

You can generate the first N numbers, infinite numbers, Check if the number is Fmbalbuena number or get Nth number of the sequence

## Test cases

Truthy

```
106959
109
219
103222
666666000
777666999

```

Falsy

```
100
230
320
666666666
125466
1069592

```

# Answer
> 3 votes
# Brachylog, ~~13~~ ~~9~~ 8 bytes

```
ḍ₃\-ᵐtᵛ0

```

Try it online! (infinite sequence version)

Not sure how I missed that by making it about congruence to 0, I dodged any thorny sign issues in taking the last digit versus performing a proper mod 10.

```
ḍ₃          Split the input into three digit lists of similar lengths.
  \         Check that the lengths are strictly equal, and transpose.
    ᵐ       For each triple,
   -        subtract the second digit from the sum of the first and third.
     tᵛ0    Is the last digit of every difference 0?

```

# Answer
> 5 votes
# 05AB1E, ~~14~~ 13 bytes

Checks if a given number is a Fmbalbuena:

```
S3äR`-T%Q*g3Ö

```

Could be 12 bytes by taking the input as a list of digits, removing the leading `S`.

Try it online or verify all test cases.

We can add a leading `∞ʒD` to output the infinite sequence:
Try it online.

**Explanation:**

```
S          # Split the (implicit) input-integer to a list of digits
 3ä        # (Try to) split it into three equal-sized parts
   R       # Reverse these parts from [A,B,C] to [C,B,A]
    `      # Pop and push all three lists separated to the stack
     -     # Subtract the digits of the top two lists: B-A
      T%   # Modulo-10
        Q  # Check if it's equal to C: B-A=C (1 if truthy; 0 if falsey)
*          # Multiply this by the (implicit) input-integer
           # (remains unchanged if the check was truthy or becomes 0 otherwise)
 g         # Pop and push its length
  3Ö       # Check if this is divisible by 3
           # (after which it is output implicitly as result)

```

```
∞          # Push an infinite positive list: [1,2,3,...]
 ʒ         # Filter it by:
  D        #  Duplicate the current integer
   S3äR`-T%Q*g3Ö
           #  Same as above
           # (after which the filtered infinite list is output implicitly as result)

```

# Answer
> 4 votes
# JavaScript (ES6), 66 bytes

Expects the input number as a string. Returns a Boolean value.

```
n=>![...n].some((d,i)=>i<(l=n.length/3)&(n[i+=l]-d+10)%10!=n[i+l])

```

Try it online!

### How?

We don't explicitly test whether the length of the input number is a multiple of 3. When it's not, `l` is a non-integer value, both `n[i+l]` and `n[i+2*l]` are *undefined*, `n[i+l]-d+10` is *NaN*, and we end up testing `NaN != undefined`, which is true and makes the test fail as expected.

# Answer
> 3 votes
# Vyxal, ~~19~~ 14 bytes

```
L3/₌ẎȯI÷‟-ȧ₀%⁼

```

Try it Online!

Checks whether an input number is a Fmbalbuena number. Takes input as a list of digits.

*can't believe I forgot to handle the case where the length isn't divisible by 3...*

*-5 thanks to Fmbalbuena*

## Explained

```
L3/₌ẎȯI÷‟-ȧ₀%⁼
L                   # Push the length of the input
 3/                 # divide that by 3
   ₌Ẏȯ              # and push input[0:that], input[that:-1]
      I             # split input[that:-1] into two lists
       ÷            # and dump that onto the stack - the stack is now [first N/3, remaining first half, remaining second half]
        ‟           # rotate the stack right - this sets it up for the subtraction
         -ȧ         # subtract the first N/3 digits from the second half and take the absolute value
           ₀%       # and modulo by 10
             ⁼      # does that exactly equal the first half?

```

# Answer
> 3 votes
# Charcoal, 27 bytes

```
¬∨﹪Ｌθ³⊙∕θ³﹪⍘⭆³§§⪪θ÷Ｌθ³λκ±¹χ

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if the input is an Fmbalbuena number, nothing if not. Explanation:

```
    θ                       Input as a string
   Ｌ                        Length
  ﹪  ³                      Is not divisible by `3`
 ∨                          Logical Or
        θ                   Input as a string
       ∕ ³                  Reduced to a third in length
      ⊙                     Any index satisfies
             ³              Literal integer `3`
            ⭆               Map over implicit range and join
                 θ          Input string
                ⪪ ÷Ｌθ³      Split into three parts
               §            Indexed by
                      λ     Inner value
              §             Indexed by
                       κ    Outer index
           ⍘            ±¹  Interpreted as base `-1`
          ﹪               χ Is not divisible by `10`
¬                           Logical Not
                            Implicitly print

```

# Answer
> 3 votes
# Factor \+ `grouping.extras`, ~~75~~ 45 bytes

```
[ 3 n-group first3 spin v- [ 10 rem ] map = ]

```

Returns whether or not the input is a Fmbalbuena number.

## Explanation

```
                   ! { 1 0 6 9 5 9 }
3 n-group          ! { { 1 0 } { 6 9 } { 5 9 } }
first3             ! { 1 0 } { 6 9 } { 5 9 }
spin               ! { 5 9 } { 6 9 } { 1 0 }
v-                 ! { 5 9 } { 5 9 }
[ 10 rem ] map     ! { 5 9 } { 5 9 }
=                  ! t

```

# Answer
> 3 votes
# Jelly, 14 bytes

```
Dœs3µZI%⁵z-Ḣ⁼Ṫ

```

A monadic Link accepting a positive integer that yields `1` if it is Fmbalbuena, or `0` if not.

**Try it online!**
Or test every positive integer up to and including \\$106959\\$ here.

### How?

```
Dœs3µZI%⁵z-Ḣ⁼Ṫ - Link: positive integer, I
D              - digits of I
   3           - literal three
 œs            - split the digits into three equal(ish) parts
                  (if not equally splittable leftmost get longer first)
    µ          - start a new monadic chain with X=that as the argument
             Ṫ - tail X (gets the digits in the last part and modifies X)
     Z         - transpose the remaining parts
      I        - deltas
        ⁵      - literal ten
       %       - modulo (the deltas)
          -    - literal minus one
         z     - transpose with filler -1 (avoiding false positives like 1009)
           Ḣ   - head
            ⁼  - does that equal the tail we removed?

```

# Answer
> 3 votes
# , 65 bytes

```
function(x,y=matrix(x,,3))!any((y[,2]-y[,1])%%10-y[,3],sum(x,-y))

```

Try it online!

Input as list of digits; checks whether this is a 'Fmalbuena' number.
+24 bytes for input as integer.

Pretty straightforward, except that we can check whether length of `x` is divisible by 3 using `sum(x,-y)` instead of `length(x)%%3` (or its usual  golf `sum(x|1)%%3`), since we know that all elements of `x` must be non-negative, and the first one must be positive.

# Answer
> 1 votes
# Python3, 246 bytes

This can probably be cut down a bit, but I didn't see a Python answer, so I thought I'd try it out. Just counting the actual code in the byte count, not the characters assigning the `n` variable.

```
n=106959
c=lambda:int(len(str(n))/3);f=lambda z,x,y:int(list(z[x])[y])
j=str(n);a=[j,list(j),len(list(j))];
if(len(a[0])%3==0):z=[a[0][x:x+c()]for x in range(0,a[2],c())];p="%s%s"%(f(z,1,0)-f(z,0,0),f(z,1,1)-f(z,0,1));print(p==z[-1:][0])
else:print(False)

```

# Answer
> 0 votes
# J, 64 bytes

Check whether a number is Fmbalbuena. The input is a number as a string, for example `'219'`. Yield `1` if the number is Fmbalbuena, `0` otherwise.

```
([:>(2{])((9|~[)=9|~])&.>(1{])-&.>0{])(]$~3,3%~#)".&.>(#$1<;.1])

                                                      (#$1<;.1]) split into digits (characters)
                                                 ".&.> convert digits into real digits
                                      (]$~3,3%~#) reshape into thirds
([:>(2{])((9|~[)=9|~])&.>(1{])-&.>0{]) substract modulo 9 and check for equality

```

It can probably golfed a lot more but I am helpless when it comes to performing operations on cells.

---
Tags: code-golf, math, sequence, decision-problem
---


title: Calculate the relativistic velocity

text:
# Question
Title: Calculate the relativistic velocity
In special relativity, the velocity of a moving object relative to another object that is moving in the opposite direction is given by the formula:

\begin{align}s = \frac{v+u}{1+vu/c^2}.\end{align}

```
s = ( v + u ) / ( 1 + v * u / c ^ 2)

```

In this formula, \\$v\\$ and \\$u\\$ are the magnitudes of the velocities of the objects, and \\$c\\$ is the speed of light (which is approximately \\$3.0 \times 10^8 \\,\mathrm m/\mathrm s\\$, a close enough approximation for this challenge).

For example, if one object was moving at `v = 50,000 m/s`, and another object was moving at `u = 60,000 m/s`, the velocity of each object relative to the other would be approximately `s = 110,000 m/s`. This is what you would expect under Galilean relativity (where velocities simply add). However, if `v = 50,000,000 m/s` and `u = 60,000,000 m/s`, the relative velocity would be approximately `106,451,613 m/s`, which is significantly different than the `110,000,000 m/s` predicted by Galilean relativity.

## The Challenge

Given two integers `v` and `u` such that `0 <= v,u < c`, calculate the relativistic additive velocity, using the above formula, with `c = 300000000`. Output must be either a decimal value or a reduced fraction. The output must be within `0.001` of the actual value for a decimal value, or exact for a fraction.

## Test Cases

Format: `v, u -> exact fraction (float approximation)`

```
50000, 60000 -> 3300000000000/30000001 (109999.99633333346)
50000000, 60000000 -> 3300000000/31 (106451612.90322581)
20, 30 -> 7500000000000000/150000000000001 (49.999999999999666)
0, 20051 -> 20051 (20051.0)
299999999, 299999999 -> 53999999820000000000000000/179999999400000001 (300000000.0)
20000, 2000000 -> 4545000000000/2250001 (2019999.1022226212)
2000000, 2000000 -> 90000000000/22501 (3999822.2301231055)
1, 500000 -> 90000180000000000/180000000001 (500000.9999972222)
1, 50000000 -> 90000001800000000/1800000001 (50000000.972222224)
200000000, 100000000 -> 2700000000/11 (245454545.45454547)

```

# Answer
> 6 votes
# MATL, 9 bytes

```
sG3e8/pQ/

```

**Try it online!**

```
s      % Take array [u, v] implicitly. Compute its sum: u+v
G      % Push [u, v] again
3e8    % Push 3e8
/      % Divide. Gives [u/c, v/c]
p      % Product of array. Gives u*v/c^2
Q      % Add 1
/      % Divide. Display implicitly

```

# Answer
> 12 votes
## Mathematica, 17 bytes

```
+##/(1+##/9*^16)&

```

An unnamed function taking two integers and returning an exact fraction.

### Explanation

This uses two nice tricks with the argument sequence `##`, which allows me to avoid referencing the individual arguments `u` and `v` separately. `##` expands to a *sequence* of all arguments, which is sort of an "unwrapped list". Here is a simple example:

```
{x, ##, y}&[u, v]

```

gives

```
{x, u, v, y}

```

The same works inside arbitrary functions (since `{...}` is just shorthand for `List[...]`):

```
f[x, ##, y]&[u, v]

```

gives

```
f[x, u, v, y]

```

Now we can also hand `##` to operators which will first treat them as a single operand as far as the operator is concerned. Then the operator will be expanded to its full form `f[...]`, and only then is the sequence expanded. In this case `+##` is `Plus[##]` which is `Plus[u, v]`, i.e. the numerator we want.

In the denominator on the other hand, `##` appears as the left-hand operator of `/`. The reason this multiplies `u` and `v` is rather subtle. `/` is implemented in terms of `Times`:

```
FullForm[a/b]
(* Times[a, Power[b, -1]] *)

```

So when `a` is `##`, it gets expanded afterwards and we end up with

```
Times[u, v, Power[9*^16, -1]]

```

Here, `*^` is just Mathematica's operator for scientific notation.

# Answer
> 4 votes
# Jelly, 9 bytes

```
÷3ȷ8P‘÷@S

```

Try it online! Alternatively, if you prefer fractions, you can execute the same code with M.

### How it works

```
÷3ȷ8P‘÷@S  Main link. Argument: [u, v]

÷3ȷ8       Divide u and v by 3e8.
    P      Take the product of the quotients, yielding uv ÷ 9e16.
     ‘     Increment, yielding 1 + uv ÷ 9e16.
        S  Sum; yield u + v.
      ÷@   Divide the result to the right by the result to the left.

```

# Answer
> 3 votes
**Python3, 55 31 29 bytes**

Python is awful for getting inputs as each input needs `int(input())` but here is my solution anyway:

v,u=int(input()),int(input());print((v+u)/(1+v\*u/9e16))

Thanks to @Jakube I don't actually need the whole prgrame, just the function. Hence:

```
lambda u,v:(v+u)/(1+v*u/9e16)

```

Rather self explanatory, get inputs, computes. I've used c^2 and simplified that as 9e16 is shorter than (3e8\**2).

**Python2, 42 bytes**

```
v,u=input(),input();print(v+u)/(1+v*u/9e16)

```

Thanks to @muddyfish

# Answer
> 2 votes
# J, ~~13~~ 11 bytes

```
+%1+9e16%~*

```

## Usage

```
>> f =: +%1+9e16%~*
>> 5e7 f 6e7
<< 1.06452e8

```

Where `>>` is STDIN and `<<` is STDOUT.

# Answer
> 2 votes
## Matlab, 24 bytes

```
@(u,v)(u+v)/(1+v*u/9e16)

```

Anonymous function that takes two inputs. Nothing fancy, just submitted for completeness.

# Answer
> 2 votes
# CJam, 16 Bytes

```
q~_:+\:*9.e16/)/

```

I'm still sure there are bytes to be saved here

# Answer
> 2 votes
# Dyalog APL, 11 bytes

```
+÷1+9E16÷⍨×

```

The fraction of the sum and \[the increment of the divides of ninety quadrillion and the product\]:

```
┌─┼───┐
+ ÷ ┌─┼──────┐
    1 + ┌────┼──┐
        9E16 ÷⍨ ×

```

`÷⍨` is "divides", as in "ninety quadrillion divides *n*" i.e equivalent to *n* divided by ninety quadrillion.

# Answer
> 2 votes
# Haskell, 24 bytes

As a single function that can provide either a floating point or fractional number, depending on the context in which it's used...

```
r u v=(u+v)/(1+v*u/9e16)

```

Example usage in REPL:

```
*Main> r 20 30
49.999999999999666
*Main> default (Rational)
*Main> r 20 30
7500000000000000 % 150000000000001

```

# Answer
> 2 votes
# Noether, 24 bytes

***Non-competing***

```
I~vI~u+1vu*10 8^3*2^/+/P

```

**Try it here!**

Noether seems to be an appropriate language for the challenge given that Emmy Noether pioneered the ideas of symmetry which lead to Einstein's equations (this, `E = mc^2` etc.)

Anyway, this is basically a translation of the given equation to reverse polish notation.

# Answer
> 1 votes
# Pyth, 14 bytes

```
csQhc*FQ*9^T16

```

Test suite.

Formula: `sum(input) / (1 + (product(input) / 9e16))`

Bonus: click here!

# Answer
> 1 votes
# Javascript 24 bytes

Shaved off 4 bytes thanks to @LeakyNun

```
v=>u=>(v+u)/(1+v*u/9e16)

```

Pretty straightforward

# Answer
> 1 votes
## Pyke, 12 bytes

```
sQB9T16^*/h/

```

Try it here!

# Answer
> 1 votes
# Julia, 22 bytes

```
u\v=(u+v)/(1+u*v/9e16)

```

Try it online!

# Answer
> 1 votes
# TI-Basic, 21 bytes

```
Prompt U,V:(U+V)/(1+UV/9ᴇ16

```

# Answer
> 1 votes
# TI-BASIC, 12 bytes

```
:sum(Ans/(1+prod(Ans/3ᴇ8

```

Takes input as a list of `{U,V}` on `Ans`.

# Answer
> 1 votes
# Microscript II, 28 bytes

```
1s16Es9*s>Fs>Fs<d*</+s<o<+</

```

# Answer
> 0 votes
## PHP, 44 45 bytes

Anonymous function, pretty straightforward.

```
function($v,$u){echo ($v+$u)/(1+$v*$u/9e16);}

```

# Answer
> 0 votes
## PowerShell, 34 bytes

```
param($u,$v)($u+$v)/(1+$v*$u/9e16)

```

Extremely straightforward implementation. No hope of catching up with anyone, though, thanks to the 6 `$` required.

# Answer
> 0 votes
# Oracle SQL 11.2, 39 bytes

```
SELECT (:v+:u)/(1+:v*:u/9e16)FROM DUAL;

```

# Answer
> 0 votes
# T-SQL, 38 bytes

```
DECLARE @U REAL=2000000, @ REAL=2000000;
PRINT FORMAT((@U+@)/(1+@*@U/9E16),'g')

```

Try it online!

Straightforward formula implementation.

# Answer
> 0 votes
# ForceLang, 116 bytes

```
def r io.readnum()
set s set
s u r
s v r
s w u+v
s c 3e8
s u u.mult v.mult c.pow -2
s u 1+u
io.write w.mult u.pow -1

```

# Answer
> 0 votes
# dc, 21 bytes

```
svddlv+rlv*9/I16^/1+/

```

This assumes that the precision has already been set, e.g. with `20k`. Add 3 bytes if you can't make that assumption.

A more accurate version is

```
svdlv+9I16^*dsc*rlv*lc+/

```

at 24 bytes.

Both of them are reasonably faithful transcriptions of the formula, with the only notable golfing being the use of `9I16^*` for c².

# Answer
> 0 votes
## Actually, 12 bytes

```
;8╤3*ì*πu@Σ/

```

Try it online!

Explanation:

```
;8╤3*ì*πu@Σ/
;             dupe input
 8╤3*ì*       multiply each element by 1/(3e8)
       πu     product, increment
         @Σ/  sum input, divide sum by product

```

# Answer
> 0 votes
# Java (JDK), 24 bytes

```
u->v->(u+v)/(1+u*v/9e16)

```

Try it online!

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

```
: f 2dup + s>f * s>f 9e16 f/ 1e f+ f/ ;

```

Try it online!

### Code Explanation

```
: f            \ start a new work definition
  2dup +       \ get the sum of u and v
  s>f          \ move to top of floating point stack
  * s>f        \ get the product of u and v and move to top of floating point stack
  9e16 f/      \ divide product by 9e16 (c^2)
  1e f+        \ add 1
  f/           \ divide the sum of u and v by the result
;              \ end word definition

```

# Answer
> 0 votes
# Math++, 26 bytes

```
?>u
?>v
(v+u)/(1+v*u/9e16)

```

---
Tags: code-golf, physics
---


title: Triple countdown sequence

text:
# Question
Title: Triple countdown sequence
Let's start with the natural numbers

```
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100...

```

Now we will make a new list, replacing each natural number `n` with a countdown from `n` to `1`.

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

```

Now we will repeat the process.

```
[1,2,1,1,3,2,1,2,1,1,4,3,2,1,3,2,1,2,1,1,5,4,3,2,1,4,3,2,1,3,2,1,2,1,1,6,5,4,3,2,1,5,4,3,2,1,4,3,2,1,3,2,1,2,1,1,7,6,5,4,3,2,1,6,5,4,3,2,1,5,4,3,2,1,4,3,2,1,3,2,1,2,1,1,8,7,6,5,4,3,2,1,7,6,5,4,3,2,1,6..

```

And now we will do it a third time:

```
[1,2,1,1,1,3,2,1,2,1,1,2,1,1,1,4,3,2,1,3,2,1,2,1,1,3,2,1,2,1,1,2,1,1,1,5,4,3,2,1,4,3,2,1,3,2,1,2,1,1,4,3,2,1,3,2,1,2,1,1,3,2,1,2,1,1,2,1,1,1,6,5,4,3,2,1,5,4,3,2,1,4,3,2,1,3,2,1,2,1,1,5,4,3,2,1,4,3,2,1...

```

This is the **triple countdown sequence**.

Your task is to implement the triple countdown sequence. You may either take input and give the value of the sequence at that index, or you may simply output the terms starting from the beginning without stop.1

This is so answers will be scored in bytes with fewer bytes being the goal.

---

1: Both zero and one indexing are permitted. Outputting the terms without halt includes lazy structures which can produce an infinite number of terms.

# Answer
# Haskell, ~~34~~ ~~33~~ 32 bytes

-1 byte thanks to Wheat Wizard!
-1 byte thanks to pxeger!

```
[1..]>>=f>>=f>>=f
f x=[x,x-1..1]

```

Try it online!
> 6 votes

# Answer
# 05AB1E, 6 bytes

```
∞3FLí˜

```

Try it online!

Infinitely outputs, thanks to Kevin Crujisen

# 05AB1E, 6 bytes

```
L3FLí˜

```

Try it online!

I doubt it could be beaten
> 6 votes

# Answer
# APL (Dyalog Extended), 12 bytes

Returns the *n*th number in the series.

```
⊢⊃1(∊…¨⍨)⍣3⍳

```

Try it online!

the argument

picks the element from

`1(``)⍣3⍳` repeat thrice with 1 as constant left argument and **i**ndices 1 through *n* as initial right argument:

**e**nlist (flatten)

the sequence

`¨` for each

with swapped arguments, i.e. counting down from that number to 1
> 6 votes

# Answer
# jq, 50 bytes

```
def f:[range(.)+1]|reverse[];
1|while(1;.+1)|f|f|f

```

Try it online!

funny how similar the second line is to the Zsh answer.

-1 from ovs.
> 5 votes

# Answer
# Zsh, 37 bytes

```
c()xargs -i seq {} -1 1
seq inf|c|c|c
```

Attempt This Online!

Full program which outputs infinitely, one per line (ATO link includes a wrapper to halt after N terms).

"Implicit" "list" "flattening" FTW! (Zsh doesn't actually have any of these features - it's just text!)

`c` is a function that outputs the `seq`uence from `{}` to `1` (with a step of `-1`) for each `{}` in the input (`xargs -i`). Then output "all" integers and pipe that to `c` three times.
> 4 votes

# Answer
# JavaScript (V8), 60 bytes

```
for(a=1;;a++)for(i=a;--i;)for(j=i;--j;)for(k=j;--k;)print(k)

```

Try it online!

Boring trivial solution.
> 4 votes

# Answer
# Husk, 6 bytes

```
!4¡ṁṫN

```

Try it online!

outputs an infinite list.
> 4 votes

# Answer
# Wolfram Language (Mathematica), 36 bytes

```
Do[Print[0;],{,∞},#,#,#]&@{,,1,-1}

```

Try it online!

Prints elements indefinitely.

---

A somewhat more interesting solution which generalizes to \\$n\\$-countdown sequences:

### Wolfram Language (Mathematica), 48 bytes

```
Nest[gArray[g,#,{#,1}]&,Print,3]@i~Do~{i,∞}

```

Try it online!
> 3 votes

# Answer
# PowerShell Core, 33 bytes

Outputs terms without stopping!

```
filter s{$_..1}
for(){++$x|s|s|s}

```

Try it online! *Note: the linked TIO limits the output*
> 3 votes

# Answer
# Jelly, 8 bytes

```
r1)⁺⁺Fị@

```

Try it online!

Because it is extremely cumbersome to produce infinite output in Jelly, it instead applies countdown 3 times to the input's range and outputs the input-th item. The part without indexing (6 bytes) ties with 05AB1E's equivalent.

```
r1)⁺⁺Fị@    Monadic main link. Input = n
r1)         [x,x-1..1] for each number x (autorange)
   ⁺⁺       Do the above; do the above (no autorange)
     Fị@    Flatten and get the nth item

```
> 3 votes

# Answer
# Scala, 60 bytes

```
Stream.from(1)flatMap>flatMap>flatMap>
def> =(_:Int)to(1,-1)

```

Try it in Scastie!

~~A less trivial solution should be coming soon.~~

`>` is a function that takes an `Int` and returns a range going from that number to 1. We then take an infinite `Stream` starting at 1, and apply `>` to each of those numbers thrice, flattening each time.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 45 bytes

```
Flatten[r@r@r@Range@#][[#]]&
r=Range[#,1,-1]&

```

Try it online!

-23 bytes from @att
> 2 votes

# Answer
# Raku, 33 bytes

```
(1..*,{.flatmap:{$_...1}}...*)[3]

```

Try it online!

This is a lazy list of countdown sequences, where the first element is the list of natural numbers, the second is the countdown sequence, the third is the double countdown sequence, and the fourth is the triple countdown sequence, et cetera. The triple countdown sequence is the one at index `3`, which is returned.
> 2 votes

# Answer
# , ~~59~~ 51 bytes

```
`[`=`for`;while(F<-F+1)i[F:1,j[i:1,k[j:1,show(k)]]]

```

Try it online!

Prints the resulting sequence infinitely.

---

Less boring:

### , 68 bytes

```
`!`=unlist;s=sapply;while(F<-F+1)cat(!s(!s(F:1,seq,,-1),seq,,-1),"")

```

Try it online!
> 2 votes

# Answer
# C++ (gcc), 101 bytes

```
#include<cstdio>
int a,x,y,z;main(){for(;;)for(x=a++;x--;)for(y=x;y--;)for(z=y;z;)printf("%d,",z--);}

```

Try it online!
> 2 votes

# Answer
# C (gcc), 69 bytes

Nested Ternary operator solution.

`a`, `b` and `c` are the triple countdown state from fastest to slowest, and `d` is the increasing count. `a` is printed for every step in the countdown. (make that a+1 thanks to AZTECCO

Thanks to AZTECCO for -10 bytes!! And -2 more!!! It took me an embarrassingly long time to figure out what's going on with the last suggestion, that's some serious golfing.

```
a,b,c,d;main(){for(;;a=!a?b=!b?c-=c?1:--d:b-1:a-1)printf("%d,",a+1);}

```

Try it online!
> 2 votes

# Answer
# Factor \+ `combinators.extras lists lists.lazy`, 58 bytes

```
[ 1 lfrom [ [ 1 [a,b] >list ] lmap-lazy lconcat ] thrice ]

```

Running in the listener, as `lmap-lazy` postdates build 1525, the one TIO uses. Note that output has been limited to 30 so I could actually take the screenshot. This limitation is not present in the code itself.

## Explanation

It's a quotation (anonymous function) that returns an infinite lazy list of the triple countdown sequence.

* `1 lfrom` An infinite lazy list of the natural numbers.
* `[ ... ] thrice` Apply a quotation (to the natural numbers) three times.
* `[ ... ] lmap-lazy` Use a quotation to map over a lazy list.
* `1 [a,b] >list` Create a list from an input number to one. e.g. `5` -\> `L{ 5 4 3 2 1 }`
* `lconcat` Concatenate a list of lists into a single list.
> 2 votes

# Answer
# Swift, 103 bytes

```
let a:([Int])->[Int]={$0.flatMap{(1...$0).reversed()}};(1...).forEach{a(a(a([$0]))).forEach{print($0)}}

```

Functional programming in Swift, excepting the `print` call, which obviously is non-pure.

`a` is a closure that converts an array of integers to an array of their countdown, which is called three times for every number.

Try it online!
> 2 votes

# Answer
# Nibbles, 6 bytes

```
<$/, 3,~.@\,

```

explanation

```
<$      # first int input elements
  /     # fold
   ,3   # [1,2,3] (any list of length 3 would work)
   ,~   # [1,2,...inf] (initial value to fold)
   .@   # map on accumulator
     \, # reverse of list from 1 to
        # implicit $ (the element of list to map)

```
> 2 votes

# Answer
# Python 3, 72 bytes

```
def c(x,i):i>0<x!=(print(x),c(x-1,i),c(x-1,i-1))
i=1
while 1:c(i,2);i+=1

```

Try it online!

-19 bytes thanks to Wheat Wizard by using even more recursion
-1 byte thanks to ovs
> 1 votes

# Answer
# JavaScript (V8), 51 bytes

```
e=f=>i=>{for(;--i;)f(i)};e(_=>e(e(e(print)))(-_))``

```

Try it online!
> 1 votes

# Answer
# MathGolf, 9 bytes

```
)╒3æ╒mx─§

```

Outputs the 0-based value.

Try it online.

**Explanation:**

```
)          # Increase the (implicit) input-integer by 1 (work-around for input 0)
 ╒         # Pop and push a list in the range [1,input+1]
  3æ       # Loop 3 times, using four characters as inner code-block:
    ╒      #  Convert each integer in the list to a [1,n] ranged list
     m     #  Map over each list:
      x    #   Reverse the list
       ─   #  Flatten the list of lists
        §  # After the loop, get the value at the (implicit) input as index
           # (after which the entire stack is output implicitly as result)

```
> 1 votes

# Answer
# C++ (gcc), ~~132~~ ~~123~~ ~~114~~ ~~113~~ 112 bytes

```
#include<argp.h>
main(int a,int b){if(a<2)for(;;)main(2,a++);while(--b)if(a<4)main(a+1,b);else printf("%d,",b);}

```

Try it online!

Thanks to @wheat-wizard for tip on removing all whitespace
> 1 votes

# Answer
# Julia 1.0, 56 bytes

```
~i=i:-1:1
!i=[.~i...;]
for i=1:-1%UInt println.(!!!i)end

```

Try it online!
> 1 votes

# Answer
# Japt, 13 bytes

There's gotta be a better way than this.

Outputs the `n`th term, 0-indexed.

```
gÈc!õ1}g3NËôÄ

```

Try it
> 1 votes

# Answer
# Perl 5, 48 bytes

```
sub d{sub c{map{reverse 1..$_}@_}sub{c c c++$i}}

```

Try it online!

Returns an anonymous sub that can be called repeatedly to obtain the next list of items in the sequence. Ungolfed and commented:

```
sub d {
    sub c {
        # This is where the magic happens. c(1) returns (1), c(2) returns (2, 1).
        # c(1, 2, 3) returns (1, 2, 1, 3, 2, 1)
        return map {reverse 1 .. $_} @_;
    }
    # 3 nested calls to c() to get the triple countdown
    return sub{c(c(c(++$i)))};
}

```
> 1 votes

# Answer
# Ruby, 48 bytes

```
x=0
loop{x-=1;eval"(x...0).map{|x|"*3+"p -x}}}"}

```

Try it online!

* outputs infinitely

We eval "(x...0).map{|x|"\*3 which becomes a depth 3 loop

x is decremented thus negative so that we can use range x..0

Then we put -x
> 1 votes

# Answer
# Vyxal, 9 bytes

```
ɾṘ3(vɾf)Ṙ

```

Try it Online!
> 1 votes

# Answer
# Charcoal, 36 bytes

```
Ｎθ≔⁰ηＷ›θＬυ«≦⊖ηＦ…η⁰Ｆ…κ⁰Ｆ…λ⁰⊞υμ»Ｉ±§υ⊖θ

```

Try it online! Link is to verbose version of code. Outputs the 1-indexed `n`th value. Explanation: Based on @AZTECCO's answer, generates the triple countup sequence for the negated natural numbers, and then negates the final value to produce the desired result.

```
Ｎθ

```

Input `n`.

```
≔⁰η

```

Start with no terms.

```
Ｗ›θＬυ«

```

Repeat until we have at least `n` terms.

```
≦⊖η

```

Get the next negated natural number.

```
Ｆ…η⁰Ｆ…κ⁰Ｆ…λ⁰⊞υμ

```

Generate the triple countup for that number.

```
»Ｉ±§υ⊖θ

```

Output the `n`th term, negating to give the desired result.
> 1 votes

# Answer
# Burlesque, 14 bytes

```
r1{m{ro^p}}3E!

```

Try it online!

```
r1    # Range 1..inf
{
 m{   # Apply to each
  ro  # Range from 1..N
  ^p  # Push in reverse
 }
}
3E!   # Run 3 times

```
> 1 votes

# Answer
# Rust, ~~77~~ 76 bytes

```
|i|{let g=|n|(1..=n).rev();(1..).flat_map(g).flat_map(g).flat_map(g).nth(i)}

```

Try it online!

*-1 bytes thanks to `..=n` trick*

Takes `i` as a `usize`, returns the `ith` item in the sequence.
Conveniently returns it as an `Option<i32>` monad, so if you somehow pass an `i` greater than the length of the sequence (impossible because it's an infinite sequence), it will return `None`.
Relevant meta ruling on returning monads

See below for explanation of how it generates the sequence.

# Rust, ~~94~~ ~~90~~ 89 bytes

```
let g=|n|(1..=n).rev();for i in(1..).flat_map(g).flat_map(g).flat_map(g){print!("{} ",i)}

```

Try it online!

*-4 bytes cos why was this a closure?*
*-1 bytes thanks to `..=n` trick*

Rust iterators are very fun.
Prints the entire sequence.

`(1..)` creates an infinite range starting at 1.
`flat_map(g)` is equivalent to `map(g).flatten()`.
`g` in this case generates a range from `n` to `1` inclusive. Rust ranges are strictly ascending, so we have to do `(1..=n).rev()`.
`=n` is used to tell Rust that the max here is inclusive, as it's a byte shorter than `n+1`.
I do wish there were a shorter way to call `flat_map(g)` three times without literally calling it three times...
> 1 votes

# Answer
# Math++, 64 bytes

```
a+1>a
a>b
b>c
c>d
d
d-1>d
5+3*!d>$
c-1>c
4+6*!c>$
b-1>b
3-2*!b>$

```
> 1 votes

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