# Question
Title: Write a Programming language of Unknown Completeness
Determining whether a Language is Turing Complete is very important when designing a language. It is a also a pretty difficult task for a lot of esoteric programming languages to begin with, but lets kick it up a notch. Lets make some programming languages that are so hard to prove Turing Complete that even the best mathematicians in the world will fail to prove them either way. Your task is to devise and implement a language whose Turing Completeness relies on a major unsolved problem in Mathematics.

## Rules

* The problem you choose must have be posed at least 10 years ago and must be unsolved, as of the posting of this question. It can be any provable conjecture in mathematics not just one of the ones listed on the Wikipedia page.
* You must provide a specification of the language and an implementation in an existing language.
* The programming language must be Turing complete if and only if the conjecture holds. (or if and only if the conjecture doesn't hold)
* You must include a proof as to why it would be Turing complete or incomplete based on the chosen conjecture. You may assume access to unbounded memory when running the interpreter or compiled program.
* Since we are concerned with Turing Completeness I/O is not required, however the goal is to make the most interesting language so it might help.
* This is a so the answer with the most votes will win.

## Target Criteria

What should a good answer do? Here are some things to look for when voting but are not technically required

# Answer
> 49 votes
## Legendre

This language is only Turing-complete if and only if Legendre's conjecture is false, i.e. there exists a integer n \> 0 such that there are no primes between n^2 and (n+1)^2. This language takes some inspiration from Underload, though in some respects it is very different from it.

Programs in Legendre are made up of series of positive integers (0 is especially banned, because it essentially negates the entire purpose of the language). Each integer corresponds to a base command in Legendre, or a potential user-defined one. Which command it is assigned to is based on the number of primes between its square and the next integer (equivalent to the OEIS sequence A014085).

The language's commands modify a stack, which can hold arbitrarily large positive integers. If the stack ever holds 0, the 0 is immediately removed. In detail, the commands are:

* 2 (smallest integer producing this command: 1): Push the next integer in the program onto the stack.
* 3 (smallest producing integer: 4): Pop the top integer on the stack and execute the command associated with it.
* 4 (smallest: 6): Pop the top integer. If it was 1, increment the top integer on the stack.
* 5 (10): Swap the top two stack items.
* 6 (15): Decrement the top integer on the stack. If that results in 0, pop the 0 and discard it.
* 7 (16): Duplicate the top integer on the stack.
* 8 (25): Halt execution and print the stack contents.

This is the basic instruction set, which is unable to do anything interesting, let alone loop. However, there is another command, which can be accessed only if Legendre's conjecture proves false.

* 0 (unknown): Remove all items from the stack and combine them into a new function, which will execute all commands starting at the original bottom of the stack and ending at the top, accessible as a command whose "command number" is equal to the one the next integer in the program source corresponds to.

If this command is somehow accessible, the language becomes Turing-complete, as one can simulate a Minsky machine in it.

When the command 8 is execute or the end of the program is reached, the program terminates and the (Unicode) character corresponding to each integer on the stack is printed.

### Example programs

```
1 2 1 3 1 10 4

```

This simple program pushes the number 2, then 3 and finally a 10, before executing a 4 (command: 3), which causes the 10 (command: 5) to be popped and executed, swapping the 2 and 3.

```
1 5 3 15 2 1 6 7

```

This program demonstrates the use of the indirect integer-to-command correspondence. First, a 5 is pushed, then a 15 and a 1, using three different ways of encoding the 2 command. Then, the 1 is popped and as a result, the 15 is incremented to a 16, and finally executed. The program ends with two instances of the number 5 on the stack.

```
1 1 1 5 ? 24 1 15 1 31 ? 31 24 31

```

This program demonstrates the use of the 0 command, using ? as a placeholder number. The program first stores '1 5' in the function 9, then '15 31' in 10, before running function 9 (using 24), which pushes 5 onto the stack, and the repeatedly decrements it, until it reaches 0 and is removed. Then, the program halts.

### Minsky machine

In order to convert a Minsky machine to Legendre code, the 0 command **must** be used. Because this command is inaccessible unless Legendre's conjecture is false, I have used a placeholder ? instead.

Note that all Minsky machine instruction line names need to have integers with different A014085 correspondences from each other and the base commands as well as 24 (9) and 31 (10).

Initialization:
```
1 1 1 1 ? 24

```
x INC (A/B) y:

A:

```
1 y 1 24 1 ? 1 6 1 1 16 1 24 ? x

```

B:

```
1 y 1 24 1 ? 1 10 1 6 1 1 16 1 10 1 24 ? x

```
x DEC (A/B) y z:

A:

```
1 4 1 10 1 15 1 10 1 31 1 1 1 10 1 z 1 1 1 16 1 24 1 31 1 ? 1 24 1 15 1 y 1 6 16 1 24 16 1 ? 1 1 16 1 10 1 1 16 1 24 ? x

```

B:

```
1 4 1 10 1 15 1 10 1 31 1 1 1 10 1 z 1 1 1 16 1 24 1 31 1 ? 1 24 1 15 1 10 1 y 1 6 16 1 24 16 1 ? 1 1 16 1 10 1 1 16 1 10 1 24 ? x

```
x HALT:
```
1 25 ? x

```

To create the final program, append all parts (with x,y,z replaced by their counterparts) and add a single integer to start the first instruction in the chain. This should prove the language's Turing-completeness in case Legendre's conjecture is proven false by counterexample.

### Interpreter

This interpreter is written in Python (3), and has been tested on all three above examples. Use the -a/--allowZero flags to allow ? to be used, -f/--file to run code directly from a file and -s/--stackOut to output the stack as a Python list instead. If no file is given, the interpreter enters a sort of REPL mode, which is best used with --stackOut.

```
import sys
import argparse
import io

class I_need_missing(dict): #used to avoid try/except statements. Essentially a dict
    def __missing__(self,key):
        return None

def appropriate(integer,prev): #returns number of primes between the square of the integer given and the next

    return_value = 0

    if prev[integer]:
        return prev[integer],prev
    if integer == "?":
        return 0,prev
    for i in range(integer ** 2, (integer + 1) ** 2):
        t = False
        if i > 1:
            t = True
            for j in range(2,int(i ** 0.5)+1):
                t = i/j != round(i/j)
                if not t:
                    break
        return_value += t

    prev[integer] = return_value
    return return_value,prev

def run_command(commandseries,stack,functions,prev): #Runs the appropriate action for each command.

    command,prev = appropriate(commandseries.pop(0),prev)

    halt = False

    if command == 0: #store in given number
        functions[appropriate(commandseries.pop(0),prev)[0]] = stack
        stack = []

    elif command == 2:#push
        stack.append(commandseries.pop(0))

    elif command == 3:#execute top instruction
        commandseries.insert(0,stack.pop())

    elif command == 4:#pop, add 1 to new top if popped value was 1
        if stack.pop() == 1:
            stack[-1] += 1

    elif command == 5:#swap top two integers/?
        stack[-1],stack[-2] = stack[-2],stack[-1]

    elif command == 6:#subtract 1 from top of stack
        stack[-1] -= 1
        if stack[-1] == 0:
            stack.pop()

    elif command == 7:#duplicate top of stack
        stack.append(stack[-1])

    elif command == 8:#halt
        halt = True

    else:#run custom
        try:
            commandseries[0:0] = functions[command]
        except TypeError:
            print("Warning: unassigned function " + str(command) + " is unassigned", file = sys.stderr)

    return commandseries,stack,functions,prev,halt

def main(stack,functions,prev):
    #Parser for command line options
    parser = argparse.ArgumentParser(description = "Interpreter for the Legendre esoteric programming language.")
    parser.add_argument("-a","--allowZero", action = "store_true")
    parser.add_argument("-f","--file")
    parser.add_argument("-s","--stackOut", action = "store_true")

    args = parser.parse_args()
    allow_zero = bool(args.allowZero)

    #Program decoding starts
    pre = ""

    if not args.file:
        pre = input()
        if pre == "":
            return
    else:
        pre = open(args.file).read()

    mid = pre.split()
    final = []

    for i in mid:
        if i == "?" and allow_zero:
            final.append("?")
        elif i != 0 or allow_zero: #and allow_zero)
            final.append(int(i))

    halt = False

    #Functional programming at its best
    while final and not halt:
        final,stack,functions,prev,halt = run_command(final,stack,functions,prev)

    #Halting and output
    else:
        if args.stackOut:
            print(stack)
        else:
            for i in stack:
                print(i == "?" and "?" or chr(i),end = "")
            print("")
        if args.file or halt:
            return
        else:
            main(stack,functions,prev)

if __name__ == '__main__':
    main([],I_need_missing(),I_need_missing())

```

# Answer
> 15 votes
## Union Closed

This programming language is Turing complete iff the Union-closed Sets conjecture is incorrect.

## Controls

List of Commands:
x++ Increment x (INC)
x-- Decrement x (DEC)
j(x,y) Add instruction set x if y is 0 to end of instruction queue

All variables are initialized as 0

## Syntax

Programs are written as a set of sets of commands.
Command1 Command2 Command3...
Command1 Command2...
...

For determining if the program is union closed, each set only accounts for the list of different commands that are in the set
j(x,y)!=j(a,b)
+(x)!=+(y)

If any command type (+,-,j) appears in at least half the sets, it does nothing.

Programs can end if there are no instructions on the end of the instruction queue

Infinite loops, including the empty loop, can be achieved using j(x,y)

## Interpreter

```
function union_arrays (x, y) {
  var obj = {};
  for (var i = x.length-1; i >= 0; -- i)
     obj[x[i]] = x[i];
  for (var i = y.length-1; i >= 0; -- i)
     obj[y[i]] = y[i];
  var res = [];
  for (var k in obj) {
    res.push(obj[k]);
  }
  return res;
}

function runCode(){
  var inputBox=document.getElementById("code");
  input=inputBox.value;
  input=input.split("\n").map(a=>a.split(" "));

  input=input.filter(x=>x.filter(y=>y.length>0).length>0);
  for(i=0;i<input.length;i++){
    for(j=0;j<input[i].length;j++){
      switch(input[i][j][0]){
        case"j":
          eval(input[i][j].split(",")[0].slice(2)+"=0;"+input[i][j].split(",")[1].slice(0,-1)+"=0")
          break;
        default:
          eval(input[i][j].slice(0,1)+"=0");
          break;
      }
    }
  }

  counts=[0,0,0];
  for(i=0;i<input.length;i++){
    count=[0,0,0];
    for(j=0;j<input[i].length;j++){
      switch(input[i][j][0]){
        case"j":
          count[2]=1;
          break;
        default:
          if(input[i][j][1]=="+"){
            count[0]=1;
          }
          else{
            count[1]=1;
          }
        break;
      }
    }
    for(j=0;j<3;j++){
      counts[j]+=count[j];
    }
  }
  for(i=0;i<input.length-1;i++){
    for(j=i+1;j<input.length;j++){
      valid=0;
      union=union_arrays(input[i],input[j]);
      for(k=0;k<input.length;k++){
        if(union_arrays(input[k],[]).sort().join("")==union.sort().join("")){
          valid=1;
        }
      }
      if(!valid){
        break;
      }
    }
    if(!valid){
      break;
    }
  }
  console.log(valid)
  var queue=[]
  if(valid){
    queue.push(input[0]);
    while(queue.length){
      for(i=0;i<queue[0].length;i++){
        if(queue[0][i][0]=="j"&&counts[2]<input.length/2){
          eval("if("+queue[0][i].split(",")[1].slice(0,-1)+"===0&&input["+queue[0][i].split(",")[0].slice(2)+"])queue.push(input["+queue[0][i].split(",")[0].slice(2)+"])");
        }
        if(queue[0][i][1]=="+"&&counts[0])
          eval(queue[0][i]);
        if(queue[0][i][1]=="-"&&counts[1])
          eval(queue[0][i]);
      }
      queue=queue.splice(0,1);
    }
  }
}
```

```
<input type="text" id="code" value=""/>
<button onClick="runCode()">Submit</button>

<p class=results></p>
```

## Turing Completeness

If all three commands, j(x,y), increment, decrement the commands are all available, so a Minsky machine can be simulated.

Any set with only j(x,y) which is reached using j(x,y) is HALT
x++ is INC
x-- is DEC
j(x,y) is JZ

If the union closed sets conjecture is correct, at least one of the three commands will always be disabled, thereby making it impossible for this language to be Turing complete.

# Answer
> 14 votes
## Fermat primes

The language works on two potentially infinite tapes, where each location of the tape can store an arbitrary integer. Both tapes are filled with `-1` at start. There is also two tape heads that start at position 0 on both tapes.

The interpreter will first read the input, and store the values into the first (data) tape, starting at position 0.

Then it will read the supplied program. For every number it encounters, it will first check if the value is a Fermat prime or not. If yes, it will write to the second (instruction) tape which Fermat prime it is, otherwise it will write `-1` to the instruction tape.

Next check the value at the instruction pointer, and do one of the following:

* `-1` or less: Exit the program
* `0`: Move the data tape position one to the left. Move the instruction tape position one to the right
* `1`: Move the data tape position one to the right. Move the instruction tape position one to the right
* `2`: Increase the value at the data tape position. Move the instruction tape position one to the right
* `3`: Decrease the value at the data tape position. Move the instruction tape position one to the right
* `4`: If the value at the current data tape position is zero, then move the instruction tape to the right, until you reach either a matching `5` (or larger) value on the instruction tape, or something smaller than `0`. If it is a `5` (or larger), move the instruction pointer the right once again, if it's smaller than `0` then exit the program. If value the current data tape position is not zero, simply move the instruction tape one to the right
* `5` or more: Move the instruction pointer to the left, until you reach the corresponding `4` value, or you find something less than `0`. In the case of the latter, exit the program.

(by matching `5` (or more) and `4` values it means that while searching for the proper value on the instruction tape any time it encounters the same value as the initial command (either `5` (or more) or `4`), it will have to skip the appropriate number of the other value (`4` or `5` (or more) respectively) on the search)

Loop, until the instruction says you have to exit the program.

When the program exits, output the values on the data tape from position `0` until the first tape position that contains a `-1` value.

## Proof

Note that the language essentially maps to an IO-less Brainfuck interpreter, where `F_5` is required to be able to do any kind of proper loops.

However based on the Fermat prime conjecture there are only 5 Fermat primes (`F_0` \- `F_4`). If `F_5` exists the language is Turing-complete, as we know that Brainfuck is Turing-complete. However, without `F_5` you won't be able to do neither branching nor looping, essentially locking you into very simple programs.

## Implementation

(tested with ruby 2.3.1)

```
#!/usr/bin/env ruby
require 'prime'

CHEAT_MODE = false
DEBUG_MODE = false
NUM_CACHE = {}

def determine_number(n)
  return n.to_i if CHEAT_MODE
  n = n.to_i
  -1 if n<3

  return NUM_CACHE[n] if NUM_CACHE[n]

  i = 0

  loop do
    num = 2**(2**i) + 1
    if num == n && Prime.prime?(n)
      NUM_CACHE[n] = i
      break
    end
    if num > n
      NUM_CACHE[n] = -1
      break
    end
    i += 1
  end

  NUM_CACHE[n]
end

data_tape = Hash.new(-1)
instruction_tape = Hash.new(-1)

STDIN.read.each_char.with_index { |c,i| data_tape[i] = c.ord }
File.read(ARGV[0]).split.each.with_index do |n,i|
  instruction_tape[i] = determine_number(n)
end

data_pos = 0
instruction_pos = 0

while instruction_tape[instruction_pos] >= 0
  p data_tape, data_pos, instruction_tape, instruction_pos,'------------' if DEBUG_MODE

  case instruction_tape[instruction_pos]
  when 0 then data_pos -= 1; instruction_pos += 1
  when 1 then data_pos += 1; instruction_pos += 1
  when 2 then data_tape[data_pos] += 1; instruction_pos += 1
  when 3 then data_tape[data_pos] -= 1; instruction_pos += 1
  when 4 then
    if data_tape[data_pos] == 0
      count = 1
      instruction_pos += 1
      while count>0 && instruction_tape[instruction_pos] >= 0
        count += 1 if instruction_tape[instruction_pos] == 4
        count -= 1 if instruction_tape[instruction_pos] >= 5
        instruction_pos += 1
      end
      break if count != 0
    else
      instruction_pos += 1
    end
  else
    count = 1
    instruction_pos -= 1
    while count>0 && instruction_tape[instruction_pos] >= 0
      count += 1 if instruction_tape[instruction_pos] >= 5
      count -= 1 if instruction_tape[instruction_pos] == 4
      instruction_pos -= 1 if count>0
    end
    break if count != 0
  end
end

data_pos = 0

while data_tape[data_pos] >= 0
  print data_tape[data_pos].chr
  data_pos += 1
end

```

Examples:

This will write `H` (short for `Hello World!`) to the screen with a newline:

```
17 17 17 17 17 17 17 17 17 17
17 17 17 17 17 17 17 17 17 17
17 17 17 17 17 17 17 17 17 17
17 17 17 17 17 17 17 17 17 17
17 17 17 17 17 17 17 17 17 17
17 17 17 17 17 17 17 17 17 17
17 17 17 17 17 17 17 17 17 17
17 17 17
5
17 17 17 17 17 17 17 17 17 17
17

```

Save as `example.fermat` and run it like this (note: you always need to have an input):

```
$ echo -n '' | ./fermat.rb example.fermat

```

This next example will do a simple Caesar style cypher by incrementing each value of the input by one. You obviously have to replace `?` with the 5th Fermat prime:

```
17 65537 5 17 ? 257

```

You can try it out that it works by enabling cheat mode and using `2 4 1 2 5 3` as the source code:

```
$ echo 'Hello' | ./fermat.rb example2_cheat.fermat

```

# Answer
> 12 votes
# Swallows w/ Coconut v2

As the previous version had errors which made it invalid for this contest, and I don't want to have the upvotes from the previous version count for this version which is significantly different, this version is being submitted as a new post.

This language is not Turing complete if the Collatz Conjecture can be proven for all positive integers. Otherwise, the language is Turing complete.

This language was based off of Cardinal.

First, the contVal of the program is calculated using the formula
contVal=sum(sum(ASCII values of row)\*2^(row number-1))

Next, 2 Swallows headed in opposite directions are created at each A or E and all conditional turn statements are set to wait for initialization.
Swallows created at an E are headed left/right and swallows created at an A are headed up/down.

Finally, the code will perform steps until all pointers have been removed or contVal has fallen to one.

At each step, if contVal%2==0 it will be divided by 2, otherwise, it will be multiplied by three and incremented by one.

## Commands:

0 : set value to 0
\+ : increment value by 1
\> : change direction to right
v : change direction to down
\< : change direction to left
^ : change direction to up
R : Subsequent pointers after the first pointer compare with the value of the first pointer. If equal, go straight, else turn right.
L : Subsequent pointers after the first pointer compare with the value of the first pointer. If equal, go straight, else turn left.
E : Duplicate the pointer but heading in the directions left and right
A : Duplicate the pointer but heading in the directions up and down
? : Remove the pointer if the value is 0

```
function runCode(){
  var inputBox=document.getElementById("code");
  input=inputBox.value;
  area=input.split('\n');
  width=0;
  height=area.length;
  for(i=0;i<height;i++){
    width=Math.max(width,area[i].length);
  }
  //Determine the endurance of the swallows
  contVal=0;
  for(i=0;i<height;i++){
    for(j=0;j<area[i].length;j++){
      contVal+=((j+1)<<i)*area[i].charCodeAt(j);
    }
  }
  //Spawn the African and European swallows and initialize the conditionals
  pointerList=[];
  condList=[];
  for(i=0;i<height;i++){
    for(j=0;j<area[i].length;j++){
      if(area[i][j]=='A'){
        pointerList.push([i,j,0,0]);
        pointerList.push([i,j,2,0]);
      }
      if(area[i][j]=='E'){
        pointerList.push([i,j,1,0]);
        pointerList.push([i,j,3,0]);
      }
      if(area[i][j]=='R'||area[i][j]=='L'){
        condList.push([i,j,-1]);
      }
    }
  }
  output='';
  while(1){
    for(i=0;i<pointerList.length;i++){
      switch (pointerList[i][2]){
        case 0:
          pointerList[i][1]++;
          break;
        case 1:
          pointerList[i][0]++;
          break;
        case 2:
          pointerList[i][1]--;
          break;
        case 3:
          pointerList[i][0]--;
          break;
      }
      if(pointerList[i][1]<0||pointerList[i][0]<0||pointerList[i][0]>=height||pointerList[i][1]>=area[pointerList[i][0]].length){
        pointerList.splice(i,1);
      }
      else{
        switch(area[pointerList[i][0]][pointerList[i][1]]){
          case "+":
            pointerList[i][3]++;
            break;
          case "0":
            pointerList[i][3]=0;
            break;
          case ">":
            pointerList[i][2]=1;
            break;
          case "v":
            pointerList[i][2]=2;
            break;
              case "<":
            pointerList[i][2]=3;
            break;
          case "^":
            pointerList[i][2]=0;
            break;
          case "R":
            for(j=0;j<condList.length;j++){
              if(pointerList[i][0]==condList[j][0]&&pointerList[i][1]==condList[j][1]){
                if(condList[j][2]==-1){
                  condList[j][2]=pointerList[i][3];
                  pointerList.splice(i,1);
                }
                else{
                  if(pointerList[i][3]!=condList[j][2]){
                    pointerList[i][2]=(pointerList[i][2]+1)%4;
                  }
                }
              }
            }
            break;
          case "L":
            for(j=0;j<condList.length;j++){
              if(pointerList[i][0]==condList[j][0]&&pointerList[i][1]==condList[j][1]){
                if(condList[j][2]==-1){
                  condList[j][2]=pointerList[i][3];
                  pointerList.splice(i,1);
                }
                else{
                  if(pointerList[i][3]!=condList[j][2]){
                    pointerList[i][2]=(pointerList[i][2]+3)%4;
                  }
                }
              }
            }
            break;
          case "A":
            pointerList.push([pointerList[i][0],pointerList[i][1],0,pointerList[i][3]]);
            pointerList.push([pointerList[i][0],pointerList[i][1],2,pointerList[i][3]]);
            break;
          case "E":
            pointerList.push([pointerList[i][0],pointerList[i][1],1,pointerList[i][3]]);
            pointerList.push([pointerList[i][0],pointerList[i][1],3,pointerList[i][3]]);
            break;
          case "?":
            pointerList.splice(i,1);
        }
      }
    }
    if(contVal%2===0){
      contVal=contVal/2;
    }
    else{
      contVal=contVal*3+1;
    }
    if(!pointerList.length||contVal==1){
      break;
    }
  }
  console.log(output);
}
```

```
<input type="text" id="code" value=""/>
<button onClick="runCode()">Submit</button>

<p class=results></p>
```

## Explanation:

If the Collatz Conjecture can be proven for all positive integers, the duration of any program run in this language is finite, as contVal will always converge to 1, thereby ending the program.

Otherwise, I simply need to prove that this language can implement the following functions

Increment: which is represented by +
Constant 0: which is represented by 0
Variable access: variables are stored as pointers as they travel
Statement concatenation: by changing the distance travelled to operations, the order in which operations are performed can be changed
For loop: In this language

```
E   > V
    ^+R
      +
      A

```

will act as a for loop \>count up to 1 (further code could be added to the loop)

Similarly, the code

```
Rv
^<

```

Will act as a do until equal to the conditional value set in R loop.

# Answer
> 11 votes
# Perfection/Imperfection

Whew, that was fun.

Perfection/Imperfection is only complete if there are infinite perfect numbers. If there are, it's called Perfection, and if there are not, it is called Imperfection. Until this mystery is solved, it holds both names.

A perfect number is a number whose divisors sum to the number, so six is a perfect number because `1+2+3=6`.

Perfection/Imperfection has the following functions:

Perfection/Imperfection is stack-based, with a zero-indexed stack.

**Commands:**

`p(x, y)`: pushes x to the stack in the yth position.

`z(x, y)`: pushes x to the stack in the yth position, gets rid of what was previously in the yth position

`r(x)`: removes the xth item from the stack

`k(x)`: returns the xth item on the stack

`a(x, y)`: adds x and y. When used with strings, it puts them together in order xy.

`s(x, y)`: subtracts y from x. with strings, removes the last len(y) from x

`m(x, y)`: multiplies x and y. If used with strings, multiplies x times len y.

`d(x, y)`: divides x by y

`o(x)`: prints x

`i(x, y)`: if x evaluates to true, then it executes function y

`n()`: returns the counter the code block is being called on.

`q()`: returns the length of the stack

`t()`: user input

`e(x, y)`: If x is an integer, if x and y have the same value, then this returns 1. if y is a string then it gets the length of y. if x is a string, then it converts y to a string and checks if they are the same, and if they are, returns 1. Otherwise it returns 0.

`l(x, y)`: if x is larger than y, then it returns 1. If there is a string, then it uses the length of the string.

`b()`: stops the program.

`c(x, y)`: runs x, then y.

To get the equivalent of a Python `and`, multiply the two values together. For `or`, add the values, and for `not`, subtract the value from 1. This only works if the value is 1 or 0, which can be achieved by dividing the number by itself.

Data types: integers and strings. Strings are denoted by `''`, and all non-integer numbers are rounded.

**Syntax:**

Code consists of nested functions inside of ten `{}`s. For example, a program that would get to inputs and print them added would be: `{o(a(t(), t()))}`. In the background of the program there is a counter that starts at 0 and progresses by 1 every time it executes a code block. The first code block runs at `0`, and so on. Once the ten code blocks are executed, the sixth one is executed every time the counter reaches a perfect number. You do not need to have all ten code blocks for the program to work, but you need 7 if you want to make a loop. To better understand how this language works, run the following program, which prints the counter every time the counter reaches a perfect number: `{}{}{}{}{}{}{o(n())}`.

The interpreter can be found here: repl.it/GL7S/37. Either select 1 and type your code in the terminal, or paste your code in the `code.perfect` tab and select 2 when you run. It will make sense when you try it.

**Proof of Turing completeness/lack of Turing completeness.**

According to this software engineering stack exchange article, a Turing complete must be able to have a form of conditional repetition of jump, and have a way to read or write memory. It can read/write memory in the form of the stack, and it can loop due to the fact that the 6th code block is executed every time the counter reaches a perfect number. If there are an infinite number of perfect numbers, it can loop indefinitely and is Turing complete, and otherwise it is not.

Self Bitwise Cyclic Tag interpreter that takes 5 characters, 1 or 0, as input:

```
{p(t(),0)}{(p(t(),0)}{p(t(),0)}{p(t(),0)}{p(t(),0)}{p(0,0)}{c(i(e(k(s(q(),k(0))),0),c(r(q()),i(l(k(0),0),z(s(k(0),1),0)))),i(e(k(s(q(),k(0))),1),c(z(a(k(0),1),0),i(e(k(q()),1),p(k(s(q(),k(0))),1)))))}

```

It can be expanded to take any number of chars as input. It could take infinite input, but only if there are infinite perfect numbers!

# Answer
> 10 votes
# Soles

This programming language is Turing complete iff the Scholz conjecture is true.

I wrote this language because @SztupY was saying that there wouldn't be any results that rely on the conjecture to be true to be Turing complete

## List of Commands

```
+(x)      Increment x (INC)
-(x)      Decrement x (DEC)
j(x,y)    Jump to instruction x if y is 0 (JZ)
x         End program (HALT)

```

With these commands, this language can simulate a Minsky machine

## Interpreter

I would highly recommend not running this. It uses an extraordinarily slow method of checking the addition chain.

```
function runCode(){
  var inputBox=document.getElementById("code");
  input=inputBox.value;
  input=input.split(" ");
  counter=1;
  lvals=[0];

  l=(x,arr)=>{
    if(arr[x-1]){
      return arr[x-1];
    }
    minim=Number.MAX_SAFE_INTEGER;
    console.log(min);
    for(i=Math.floor(x/2);i>0;i--){
      minim=Math.min(minim,l(i,arr)+l(x-i,arr)+1);
    }
    return minim;
  };
  cont=1;
  pointer=0;
  while(cont){
    lvals[Math.pow(2,counter)-2]=l(Math.pow(2,counter)-1,lvals);
    lvals[counter-1]=l(counter,lvals);
    if(lvals[Math.pow(2,counter)-2]>n-1+lvals[counter-1]){
      break;
    }
    switch(input[pointer][0]){
      case "+":
        x=input[pointer].slice(2,-1);
        eval(x+"++")
        break;
      case "-":
        x=input[pointer].slice(2,-1);
        eval(x+"--")
        break;
      case "j":
        x=input[pointer].split(",")[0].slice(2);
        y=input[pointer].split(",")[0].slice(0,-1);
        eval("if(!"+y+")pointer="+x+"-1");
        break;
      case "x":
        cont=0;
        break;
    }
    pointer++;
    if(pointer>input.length){
      break;
    }
    counter++;
  }
}
```

```
<input type="text" id="code" value=""/>
<button onClick="runCode()">Submit</button>

<p class=results></p>
```

## Turing completeness

The language uses a counter for number of commands run which it checks against the Scholz conjecture to modify the turing completeness of the language.

If the Scholz conjecture is true, this program works exactly like a normal Minsky machine with
Increment
Decrement
Jump if Zero
Halt

However, if the Scholz conjecture is false, the counter will eventually reach a value for which the Scholz conjecture does not hold true. As the language has been designed to exit upon reaching a number which the Scholz conjecture is false, the program will exit every time after running that many commands. Therefore, all programs will have limited length. As this disagrees with the requirements for the language to be Turing complete,

> "The tape cannot be fixed in length, since that would not correspond to the given definition and would seriously limit the range of computations the machine can perform to those of a linear bounded automaton",

the language would not be Turing complete should the Scholz conjecture be false

# Answer
> 9 votes
# Betrothed

Betrothed Github.

The readme and specification is on the github, under "README.txt".

Generally, a Betrothed program is composed of pairs of lines, whose lengths are distinct twin prime pairs or betrothed pairs (no duplicates can occur). The program is executed by find "pliable subsets" of the first line in the pair within the second line. The number of such subsets, combined with the levenshtein distance between the original second line and the second line without the pliable subsets, determine the command to execute.

I will excerpt the proof for this post:

```
V. PROOF OF TURING COMPLETENESS

Now, no language can be Turing Complete with bounded program size. Therefore, if Betrothed
is Turing Complete, it must have unbounded program size. Since the lengths of the lines of
a Betrothed program must be twin prime pairs or betrothed pairs, and since both sequences
are unproven to be infinite or finite, Betrothed has unbounded program size if and only if
there are infintie betrothed pairs, there are infinite twin prime pairs, or both.

    Next: to prove that if Betrothed has an unbounded program size, then it is Turing
Complete. I will use the op-codes from the above table to demonstrate key factors of a
Turing Complete language; they are of the form  [index]<[ld]> .

  1. Conditional goto: 6<> 5<>, or if-popjump. This can be used to form a loop.
  2. Inequality to a constant K: 10<K>
  3. Arbitrarily large variable space: you can use some separator constant C.

    With this, I have sufficient reason to believe that Betrothed is Turing Complete.

```

# Answer
> 6 votes
# Amicable Parity

This language is based on whether there are any amicable numbers with opposite parity.

## Commands

```
x : End program if not on top line
+ : increment stored value
- : decrement stored value
{ : set next goto x value to current x value
} : goto previous x value set by {
j : Go down one line if the special value is an amicable number and the
    parity is opposite to the matching number (loops back to top). If the
    special value is not an amicable number and not on the top line, go up
    one line.

```

## Control flow

The program cycles repeatedly from left to right before looping back to the start. If it encounters a "j", it checks the value to determine if it should change rows. If the number is an amicable number with opposite parity to its match, it goes down one row (looping back to top), Otherwise, if the number is an amicable number, it goes up one row if not already in the top row.

The program can only end if the program reaches an x in any row outside of the top row.

## Turing Completeness

This program can be used to simulate a Minsky machine assuming that there is a pair of amicable numbers with opposite parity.

j,{ and } can be used to simulate JZ(r,x) although it would check for amicable numbers as opposed to zero.
\+ is INC(r)
\- is DEC(r)
x is HALT

If you can not leave the first row, the x and } commands do nothing. This results in the program being unable to enter a HALT state unless it is an empty program. Therefore, under the description that Turing completeness requires a HALT state, the language would be Turing incomplete.

## Interpreter

```
sumDiv=r=>{
  sum=0;
  for(i=1;i<=Math.sqrt(r)&&i!=r;i++){
    if(r%i===0){
      sum+=i+r/i;
    }
    if(i*i==r){
      sum-=i;
    }
  }
  return sum;
};
function runCode(){
  var inputBox=document.getElementById("code");
  input=inputBox.value;
  input=input.split("\n");
  val=2;
  exit=0;
  loop=0;
  for(j=0;!exit;){
    for(i=0;i<input[j].length;i++){
      if(input[j][i]=="x"&&j){
        exit=1;
        break;
      }
      else if(input[j][i]=="j"){
        if(val==sumDiv(sumDiv(val))&&val!=sumDiv(val)&&(val+sumDiv(val))%2){
          j=(j+1)%input.length;
          i--;
        }
        else if(j&&val!=sumDiv(sumDiv(val))){
          j--;
          i--;
        }
      }
      else if(input[j][i]=="+"){
        val++;
      }
      else if(input[j][i]=="-"){
        val--;
      }
      else if(input[j][i]=="{"){
        loop=i;
      }
      else if(input[j][i]=="}"&&j){
        i=loop;
      }
      if(input[j].length==i+1){
        i=-1;
      }
    }
  }
}
```

```
<input type="text" id="code" value=""/>
<button onClick="runCode()">Submit</button>

<p class=results></p>
```

# Answer
> 5 votes
# Taggis

Taggis is a language based on tag systems.

Taggis's turing completeness is based on the Collatz Conjecture

## Syntax

A Taggis program's syntax is simply three strings (production rules) consisting entirely of the letters a, b, and c, separated by spaces.

## Execution

Taggis's only program state is a string consisting of the same three characters.

Taggis implements a TS(3, 2) tag system, where in every step the first 2 letters of the current "tag" are removed, and the very first letter that was in that removed portion gets its corresponding production rule appended to the end of the string.

For example, the Taggis program `bc a aaa` implements the 3n + 1 problem, where iterations are represented by a corresponding number of `a`s and the 3n + 1 step is replaced with (3n + 1) / 2 \[1\], leading to the program output:

```
aaa // 3
  abc
    cbc
      caaa
        aaaaa // 5
          aaabc
            abcbc
              cbcbc
                cbcaaa
                  caaaaaa
                    aaaaaaaa // 8
                      aaaaaabc
                        aaaabcbc
                          aabcbcbc
                            bcbcbcbc
                              bcbcbca
                                bcbcaa
                                  bcaaa
                                    aaaa // 4
                                      aabc
                                        bcbc
                                          bca
                                            aa // 2
                                              bc
                                                a // 1 and halt because we then begin an infinite loop
                                                 HALT

```

## Turing completeness

Of course, this simple system may seem far too simple to emulate Turing completeness, but it turns out that any Turing machine with 2 symbols (a class that includes universal machines) can be converted to a tag system with 2 removed characters from the head, and 32 * m production rules, where `m` is the number of states in the Turing machine.

The smallest known universal Turing machine with only 2 symbols uses 18 states and thus the corresponding tag system contains a whopping 576 production rules \[2\].

However, the computational class of the set of all tag systems with 3 productions and 2 removed symbols is tied to the Collatz Conjecture \[2\]. If the Collatz Conjecture is proved to be false, then Taggis is Turing-complete. Otherwise, it is based on ANOTHER unsolved problem in mathematics, finding a smaller Turing machine than

```
def taggis(inp, a, b, c):
    current = inp
    seen = set()
    while True:
        seen.add(tuple(current))

        yield current

        head = current[0]

        current = current[2:]

        current.extend([a, b, c][head])

        if tuple(current) in seen:
            return

def parse():
    program = input().split(" ")

    assert len(program) == 3, "There has to be exactly 3 production rules!"

    productions = []

    for production in program:

        production = [{"a": 0, "b": 1, "c": 2}[x] for x in production]
        productions.append(production)

    program_input = [{"a": 0, "b": 1, "c": 2}[x] for x in input()]

    k = 0

    for step in taggis(program_input, *productions):
        print(' ' * k +''.join(['abc'[x] for x in step]))

        k += 2
    print(' ' * (k - 1) + 'HALT')

parse()

```
1. which is equivalent to the original Collatz function as 3n + 1 of an odd `n` will always be even and therefore the division can be automatically applied
2. Tag systems and Collatz-like functions, *Liesbeth De Mol*,

# Answer
> 2 votes
# Newline

Disclaimer: It is a bit of a mess and pretty simple. This is the first language I have ever written and the conjecture is the only one I understood. I know another user had a longer answer with the same one but I decided to write this anyway.

To write in Newline you must have a lot of time and newlines (`\n`). This works off of the Legendre conjecture being true. Every operator must fall on a number in the Legendre conjecture that we start with n = 1. Every time you have an operator you take the amount of \n's and plug that into the Legendre Conjecture and get the range that the next prime amount of \n's must fall in. So to start off you do `\n\n` then you move on to an operator then `\n` then another operator we are at 3 newlines. Now the next one is it 5 so you add `\n\n` and on operator making sure that the last operator line has the right amount of newlines that you are on a prime amount that falls in the Legendre conjecture that we started.

Numbers (the array) is like the variables. Every time an operator runs (that uses numbers) it increments.

```
+ adds
- subtracts
/ divide
* multiply
s sqrt
% mod
a push to vars
g sets stack to numbers
q pushes value of stack to numbers
i increment
d decrement
r stops subtraction at 0
w turns back on subtraction past 0
[ starts loop
] ends loop runs until stack is 0
{ starts loop
} ends loop and loops until loops[ln] is 0
k increment loops

```

As long as we have unlimited primes that follow the rules this language has non finite tape.

# Minsky machine

```
\n\ng\nr\n\n[\n\nd\n\n\n\n]

```

How it works:

```
\n\ng     # the first two newlines are to get to a prime number of newlines (2) then sets the value of stack to the first variable in the array numbers (see code in link)

\nr       # gets to the next number and makes it so subtraction stops at 0

\n\n[     # starts the loop

\n\nd     # decrements stack

\n\n\n\n] # ends loop

```

Try it out on KhanAcademy.

---
Tags: popularity-contest, language-design
---


title: Ticking Quine-Bomb!

text:
# Question
Title: Ticking Quine-Bomb!
## Challenge:

Create a program or function that takes an integer input, which outputs a new program/function as specified below.

### Input:

Integer `n`: Time in seconds before the Time Bomb explodes.

### Output:

The original program which had the time in seconds `n` as input, will output a new program/function that does the following:

* Has `n` seconds passed since the previous program was run? Print `BOOM!`
* Else: Print a program/function which, when run itself, resets the timer back to `n` seconds (and acts the same as the first outputted program/function).

NOTE: It is not exactly the same as the first outputted program/function (in most languages at least), because the starting time has changed (see clarification example below).

### Pseudo-code Example:

Let's say the original program is `ABC` and the input is `60` seconds:

`ABC` & `60` outputs `DEF(60)`.

* If `DEF(60)` is run within 60 seconds, it will output `DEF_G(60)`, which acts exactly the same as `DEF(60)`, but with a new starting time.
* If `DEF(60)` is run after 60 seconds, it will output `BOOM!`.

### Clarification example what I mean with 'starting time':

1. Base program with input `60` seconds is run at `12:00:00`. It outputs the first output program with a starting time of `12:00:00`.
2. This first output program with starting time of `12:00:00` is run at `12:00:45`. It outputs a second output program with a starting time of `12:00:45`.
3. This third output program with a starting time of `12:00:45` is run at `12:01:25`. It outputs a fourth output program with a starting time of `12:01:25`.
4. This fourth output program with a starting time of `12:01:25` is run at `12:05:00`. It will output `BOOM!`.

Note how the first output would print `BOOM!` after `12:01:00`, but the output program has progressed so even though it's `12:01:25` at step 3, it will still output the next program instead of `BOOM!` (because the output-of-output programs has starting times beyond that first output program).

## Challenge Rules:

* Default quine rules apply.
* At least `n` seconds should have passed. So if the input is `60` and starting time was `12:00:00`, at `12:01:00` it will still output the v2 program, but at `12:01:01` it will output `BOOM!`.
* The output programs will not take any input (except for an empty unused parameter if it's shorter). The starting time should be given to the next programs as 'hard-coded' value (which is why the output of an output program isn't exactly the same as the previous (in most languages).
* Only the size of your main program/function is counted in terms of bytes.
* You can output the program/function either as string (or comparable reasonable format, like byte/character array/list), as function if your language supports this, or other reasonable formats (please ask if you aren't sure).

## 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.

# Answer
> 2 votes
# JavaScript, 51 bytes

```
f=(t,o=setTimeout(_=>o=0,t*1e3))=>_=>o?f(t):'BOOM!'

```

Test in browser

## old version

```
f=(t,o=0)=>{setTimeout(()=>o=1,t*1000);return ()=>o?'BOOM!':f(t)}

```

Test in browser

# Answer
> 4 votes
# JavaScript, 53 bytes

```
f=(d,t=1/0,n=Date.now()/1e3)=>n>t?'BOOM!':_=>f(d,d+n)

```

```
g=
f=(d,t=1/0,n=Date.now()/1e3)=>n>t?'BOOM!':_=>f(d,d+n)

// please notice that `delay` may take longer time than experted time on a slow / busy machine
// which may lead an incorrect result
delay=n=>new Promise(r=>setTimeout(r,n*1e3));

assertFine=s=>console.log(s!=='BOOM!'?s:'FAIL');
assertBoom=s=>console.log(s==='BOOM!'?s:'FAIL');

(async function () {
  console.log('start test');
  let p1 = g(3);
  assertFine(p1); // should not boom
  await delay(2);
  let p2 = p1();
  assertFine(p2); // should not boom
  await delay(2);
  let b1 = p1();
  assertBoom(b1); // should boom
  let p3 = p2();
  assertFine(p3); // should not boom
  await delay(2);
  let b2 = p2();
  assertBoom(b2); // should boom
}());
```

---

Old answer (returning should be a string)

# JavaScript, 78 bytes

```
(f=(o,t,d)=>(x=d,n=Date.now()/1e3)=>o&&n>t?'BOOM!':`(f=${f})(${[1,n+x,x]})`)()

```

```
g=
(f=(o,t,d)=>(x=d,n=Date.now()/1e3)=>o&&n>t?'BOOM!':`(f=${f})(${[1,n+x,x]})`)()

// please notice that `delay` may take longer time than experted time on a slow / busy machine
// which may lead an incorrect result
delay=n=>new Promise(r=>setTimeout(r,n*1e3));

assertFine=s=>console.log(s!=='BOOM!'?s:'FAIL');
assertBoom=s=>console.log(s==='BOOM!'?s:'FAIL');

(async function () {
  console.log('start test');
  let p1 = g(3);
  assertFine(p1); // should not boom
  await delay(2);
  let p2 = eval(p1)();
  assertFine(p2); // should not boom
  await delay(2);
  let b1 = eval(p1)();
  assertBoom(b1); // should boom
  let p3 = eval(p2)();
  assertFine(p3); // should not boom
  await delay(2);
  let b2 = eval(p2)();
  assertBoom(b2); // should boom
}());
```

# Answer
> 1 votes
# Java 8, 234 bytes

```
n->"v->{long t=System.nanoTime();t/=1e9;String s=\"v->{long t=System.nanoTime();t/=1e9;String s=%c%s%1$c;return t-%d>"+n+"?%1$cBOOM!%1$c:s.format(s,34,s,t);}\";return t-"+(System.nanoTime()/1e9)+">"+n+"?\"BOOM!\":s.format(s,34,s,t);}"

```

Sorry to post my own challenge right away. It is mainly meant as further clarification of the challenge, and I was doubting whether to add it to the question itself or post it as an answer (and decided to post it as an answer to not clutter the challenge post).
And although I would like to say it's also something to (try and) beat, that isn't even worth mentioning because, well.. Java (almost) always gets beaten. ;p

Try it online.

Example output:

```
v->{long t=System.nanoTime();t/=1e9;String s="v->{long t=System.nanoTime();t/=1e9;String s=%c%s%1$c;return t-%d>60?%1$cBOOM!%1$c:s.format(s,34,s,t);}";return t-70492.687613232>60?"BOOM!":s.format(s,34,s,t);}

```

Try the outputted lambda-function here.

Example output:

```
v->{long t=System.nanoTime();t/=1e9;String s="v->{long t=System.nanoTime();t/=1e9;String s=%c%s%1$c;return t-%d>60?%1$cBOOM!%1$c:s.format(s,34,s,t);}";return t-70548>60?"BOOM!":s.format(s,34,s,t);}

```

### Explanation:

The main function takes an integer input and returns a String. It basically returns a function which is a quine, with the integer input and starting time (in seconds as timestamp) as hard-coded values.

**Main function:**

```
n->        // Method with integer parameter and String return-type
  "v->{long t=System.nanoTime();t/=1e9;String s=\"v->{long t=System.nanoTime();t/=1e9;String s=%c%s%1$c;return t-%d>"
          //  First part of the output-function
  +n      //  With the integer input placed as hard-coded value
  +"?%1$cBOOM!%1$c:s.format(s,34,s,t);}\";return t-"
          //  The second part of the output-function
  +(System.nanoTime()/1e9)
          //  With the current time in seconds as hard-coded starting time
  +">"+n  //  And the integer input again (for the output of the output function)
  +"?\"BOOM!\":s.format(s,34,s,t);}"
          //  The final part of the output-function

```

`n=60` was used in the examples below:

**First output program:**

```
v->{                   // Method with empty unused parameter and String return-type
  long t=System.nanoTime();t/=1e9;
                       //  New starting time in seconds
  String s="v->{long t=System.nanoTime();t/=1e9;String s=%c%s%1$c;return t-%d>60?%1$cBOOM!%1$c:s.format(s,34,s,t);}";
                       //  Unformatted (quine) result-function
  return t-            //  If the difference between the new starting time
    70492.687613232    //  and hard-coded starting time from the main function
    >60?               //  is larger than the hard-coded integer from the main function
     "BOOM!"           //   Return "BOOM!"
    :                  //  Else:
     s.format(s,34,s,  //   Return the formatted (quine) result-function,
              t);}     //   with this new starting time as new hardcoded value

```

**Second output program:**

The same as the first output program, except that `70492.687613232` is replaced with `70548`.

# Answer
> 1 votes
## Perl 5 \+ `-p`, 88 bytes

```
$_="\$s=$_;\$t=$^T;".'$_=q{say$^T-$t<$s?qq{\$t=$^T;\$s=$s;\$_=q{$_};eval}:"BOOM!"};eval'

```

Output programs must be run with `-M5.010` for `say`, but not `-p`.

Try it online!

# Answer
> 0 votes
# 05AB1E, 50 bytes

```
"‘ÒÞ!""žažb‚žcª60β"D.VsI’"34ç ìD«ÿÿ©ÿDU-›iX®:ëÿ’D«

```

Can definitely be golfed a bit more, but it's quite tricky to output a semi-quine which outputs a quine-program with modified values.

Try it online or try a 20-second example run.

**Explanation:**

```
"‘ÒÞ!"                     # Push the string "‘ÒÞ!"
"žažb‚žcª60β"              # Push the string "žažb‚žcª60β"
 D                         # Duplicate it
  .V                       # Execute it as 05AB1E code:
                           #  ža          : Push the current hours
                           #    žb        : Push the current minutes
                           #      ‚       : Pair them together
                           #       žcª    : Append the current seconds
                           #          60β : Convert from this integer list to base-60
s                          # Swap the seconds-integer and duplicated "žažb‚žcª60β"-string
I                          # Push the input
’"34ç ìD«ÿÿ©ÿDU-›iX®:ëÿ’  "# Push the string '"34ç ìD«ÿÿ©ÿDU-›iX®:ëÿ',
                           # where the `ÿ` are automatically replaced with the stack-values
 D«                        # Duplicate it, and append them together
                           # (after which the string is output implicitly as result)

```

Example resulting program:

```
"34ç ìD«30žažb‚žcª60β©35555DU-›iX®:ë‘ÒÞ!"34ç ìD«30žažb‚žcª60β©35555DU-›iX®:ë‘ÒÞ!

```

Which is based on the default quine: `"34çìD«"34çìD«`.

```
"34ç ìD«30žažb‚žcª60β©35555DU-›iX®:ë‘ÒÞ!"
                           # Push this string
 34ç                       # Push 34, converted to a character: '"'
    ì                      # Prepend it in front of the string
     D«                    # Duplicate this string, and append them together
                           # (we now have the quine-string at the top of the stack)
  žažb‚žcª60β              # Get the current time in seconds similar as above
             ©             # Store it in variable `®` (without popping)
              35555        # Push the time this program was generated
                   DU      # Store a copy in variable `X`
                     -     # Subtract the two times
30                    ›i   # If the original input-integer is larger than this:
  X®:                      #  Replace integer `X` with `®` in the generated quine-string
                       ë   # Else:
  ‘ÒÞ!                     #  Push dictionary string "BOOM!"
                           # (and output the top of the stack implicitly as result)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `‘ÒÞ!` is `"BOOM!"`.
NOTE: The reason the space is there between `çì` is because otherwise it's interpret as a dictionary-string (`triumph`) due to the `’...’`.

---
Tags: code-golf, quine, date
---


title: Tips for golfing in dc

text:
# Question
Title: Tips for golfing in dc
What general tips do you have for golfing in dc?

dc is a calculator utility for UNIX/Linux that predates the C language. I am interested in how to make my dc programs (calculations?) shorter. I'm looking for ideas that can be applied to general that are at least a little bit specific to dc (eg. removing comments is not a helpful answer)

Please post one tip per answer.

# Answer
> 6 votes
# Arrays

Although they're a headache for beginners, `dc` offers arrays. They work like this:

```
value index :a    # store `value' in array linked to top of stack `a', with index `index'
      index ;a    # push a[index] on (main) stack

```

As usual, the first element has the index 0. Arrays can be useful when working with sequences, like in the SUDSI sequence, especially in combination with counters. Arrays can reduce the amount of number-shuffling you need to do (and the number of counters and comparisons) if you want to select a particular element without destroying your environment. For example, if you want to move a stackful of numbers into an array, you could write a recursive function that uses `z` (stack depth) or `z 1-` as the index, stores the element, and checks whether `z == 0` to terminate itself.

```
[z 1- :a z 0 !=F]dsFx    # or I could just write such a function for you :)

```

Be aware of the following:

* Arrays are associated with instances on named stacks. If you push a new value on a stack that has an array associated with it, that array will also be "pushed back", and a "new" array will take its place. The old array won't be usable until the corresponding value on the named stack is also usable (i.e., on top of its stack). This is a complicated concept that would be better explained with a good animation, which is beyond me.
* You **can** store stuff in a named array without actually pushing a value into the corresponding named register. However, if you do this, you **cannot** access the stack/register with that name for the rest of the session. `dc` will crash.
* If you pop a value off a named stack, any values in the corresponding array will be lost—no warnings, no safeguards, nothing. Just gone (which can also be useful).

# Answer
> 6 votes
# If-then-else statements

Suppose we want to check the condition `a==b` (let `a` and `b` be stored in their respectively-named registers).

edit:
```
[         # Everything is wrapped in one big macro
  [         # An inner macro for our *then* part
              # <-- Stuff to execute if a==b here
  2Q          # Then quit the inner and outer macro
]sE       # `E' is for Execution register ;)
la lb =E  # if a==b, execute E
          # if E is executed, it will quit the whole macro, so the rest is never reached:
          # <-- Stuff to execute if a!=b here
]x        # End macro; Execute

```

Let `(foo)` be a placeholder, for the purpose of condensing:

```
[[(then)2Q]sE(condition)E(else)]x

```

Pretty sure this is the most compact if statement possible (also featured here).

# Answer
> 5 votes
# You can save input with `d`

By using `d`, which duplicates the ToS (top of stack) you can move the input out of the way for later use, while still being able to use it.

# Answer
> 5 votes
# 0 to the nth power instead of conditionals/macros

Sometimes you might need something like ternary conditional:

```
A == B ? C : D;

```

A nice way to handle this is described in @Joe's answer. However we can do better:

```
0AB-^E*C+

```

where E is D - C.

This tests for equality by raising 0 to the power of the difference of the two values. This results in 1 if equal and 0 otherwise. The rest just scales the 1 or 0 to the values C or D. This works because `dc` gives 00 = 1 and 0n = 0 for n != 1.

# Answer
> 4 votes
Digits `A` to `F` may be used in substitution for the numbers 10 to 15. However they must still be treated effectively as base 10 digits (assuming input base is 10) when in different places. In other words, with input base 10 `FF` would not represent 255, it would represent `(15 * 10) + 15` or 165.

In fact this works for all digits `0` to `F` in any input base `2` to `16`. So if the input base is 5, then `26E` would be `(2 * 5^2) + (6 * 5) + 14`, or 94.

Note this behaviour is in effect for the unmodified GNU sources. However, as @SophiaLechner points out, RedHat-based distros appear to use bc-1.06-dc\_ibase.patch which changes this behaviour so digits \>= ibase are treated as `ibase - 1`, regardless of their actual value. Note the TIO `dc` appears not to have bc-1.06-dc\_ibase.patch (even though its Fedora 28 ¯\_(ツ)\_/¯ ).

# Answer
> 4 votes
Sometimes it is necessary to discard a number from the stack. One way to do this is to simply pop it into an unused variable, i.e. `st`. However in some situations, you can pop it to a couple of other places, e.g. the input base when you have no more numerical input or to the precision specifier if you don't have any more operations to do where precision would make a difference. In the former case, use `i`. In the latter case, use `k`.

# Answer
> 4 votes
# Length Calculation: `Z`, `X`, and `z`

`Z` pops the ToS and pushes the number of digits (decimal) if it's a number or the number of characters if it's a string. This can be useful for detecting the length of a result (for buffering output) or computing string length. Note that for numbers, `Z` pushes the combined length of the integer part and the fraction part.

`X` pops the ToS and pushes the number of digits in the fraction part of the number. If the ToS was a string, `0` is pushed.

To find the number of digits in the integer part of the number, one might use `dZrX-`. If you haven't changed the precision from the default `k==0`, using `1/Z` is shorter, but suppose you need to maintain a particular non-zero precision after the operation: `Kr0k1/Zrk` is rather an eyesore.

`z` pushes the number of items on the stack. One of my favourite commands, it does not actually pop any values! It could be used to generate a sequence of numbers or increment a counter. Using `zd` repeatedly (say, at the start of a macro) could let one test a calculation on each natural or whole number in ascending order.

# Answer
> 3 votes
# If an operator is restricted from source, make a new one with `a`

Something that has come in handy for me a couple of times now is to avoid using a specific operator by pushing the ASCII value of the operator, using `a` to convert it to a string, and `s`toring this in a register to be executed as a macro later on. For example, I need to do division, but am either disallowed from or trying to avoid using the character `/`. I can, instead do `47asd` and then in the future when I need to divide 16 by 4, `16 4 ldx`.

* This will only work for single-character operators (can't build up a string), and will not work for commands like `s` that need to be postfixed by something.
* This adds quite a few bytes, and is therefore only suitable when avoiding the specific character is necessary or somehow affords a score bonus.

# Answer
> 2 votes
When initialising a ~~function~~ macro (we'll use `F`) that you want to run immediately, use something like `dsFx` rather than `sFlFx`. The same works for variables: `dsa` rather than `sala`.

If you need to do other stuff in between the storing and the loading (e.g., `sa[other stuff]la`), still consider whether the above is viable: If you leave a value on the stack before the other operations, will it be back at the top by the end of those operations?

# Answer
> 2 votes
Just discovered this by accident. Yet another way to generate a zero: `_`.

`_` is a signal to dc that the following digits are a negative number. Example:

```
_3 # pushes -3

```

But what if we don't follow it with a number?

```
_ # pushes 0...sometimes

```

This works when the next non-blank character following the underscore is not a digit. If a digit follows it, even after a newline, it is interpreted as a negative sign.

```
c4 5_6  # -6,5,4
c4 5_ 6 # -6,5,4
c4 5_
6       # -6,5,4 # still a negative sign since the next thing it sees is a digit
c4 5_z  #  3,0,5,4 # if it's followed by a non-digit, it's a 0
c4 5_p6 #  6,0,5,4
c4 _*   #  0 # 4*0=0

```

# Answer
> 1 votes
If the contents of the entire stack needs printing at the end of a program, a recursive macro loop could be used to achieve this. However, it is much shorter to simply use the `f` command.

# Answer
> 1 votes
`dc` reads input a line at a time. If you need to read in multiple items, doing it one-per line either requires a `?` for every line to be read, or a cumbersome macro loop. Instead, if all input items can be put on one space-separated line, then a single `?` will read all the input items, pushing each one onto the stack.

For example in `seq 10 | dc -e'?f'`, `seq` outputs integers 1-10, one per line. the `?` will just read the first `1` which will be output when `f` dumps the whole stack. However in `seq 10 | tr '\n' ' ' | dc -e'?f'`, the `tr` makes the input integers all space separated. In this case the `?` will read all the integers from the line in one go, and `f` will output them all.

# Answer
> 1 votes
# Avoiding whitespace

Avoiding whitespace comes up in quite a few challenges, and is generally easy in `dc`. Aside from strings, the one very specific time that whitespace becomes necessary is when pushing multiple numbers in a row: `1 2 3`. If this must be avoided:

* Execute an empty macro in between: `1[]x2[]x3[]x`.
* If brackets are off the table, store a NOP of a macro ahead of time: `35asn` and execute *it* in between: `1lnx2lnx3lnx`.

---
Tags: code-golf, tips
---


title: FizzBuzz but time-based

text:
# Question
Title: FizzBuzz but time-based
Make a program that outputs the number of seconds from the beginning of today (00:00:00 of the day you run it) to the second you ran it. However, if this number is divisible by three, print `Fizz` instead. If it is divisible by five, print `Buzz` instead. If it is divisible by three and five, print `FizzBuzz`.

Don't pad the number printed with extra zeroes (44 instead of 00044). You don't need to take leap seconds into account (saying for the universe in which people answer this years after I post it). Standard loopholes apply, shortest program wins.

# Answer
> 3 votes
# Jelly, 26 bytes

A simple port of Dennis's "1-2-fizz-4-buzz" solution which evaluates the formatted time as seconds first

```
7ŒTṣ”:Vḅ60µ3,5ḍTị“¡Ṭ4“Ụp»ȯ

```

**Try it online!**

# Answer
> 2 votes
# Python 2, 73 bytes

```
import time
a=time.time()%86400//1
print(a%3<1)*"Fizz"+(a%5<1)*"Buzz"or a

```

Try it online!

-37 bytes using time.time instead of datetime thanks to negative seven
-4 bytes thanks to ArBo (switched to Python 2)

# Answer
> 2 votes
# 05AB1E, ~~33~~ 30 bytes

*-3 bytes from Grimy*

```
žažbžc)60βÐ3Öi"Fizz"?}5Öi”ÒÖ”,

```

Try it online!

# Answer
> 1 votes
# PowerShell, ~~117~~ ~~94~~ ~~90~~ 71 bytes

-23 bytes thanks to mazzy
-4 bytes thanks to AdmBorkBork
-19 bytes thanks to mazzy again

```
(([int]$x=date|% tim*|% t*ls*),('Fizz'*!($x%3)+'Buzz'*!($x%5))|sort)[1]

```

Try it online!

An even cheaper way to compute the day's seconds. TotalSeconds also returns as a float so that had to be truncated as well. Plugs that value into this Fizzbuzz answer by AdmBorkBork so give him a thumbs-up as well.

# Answer
> 1 votes
## Batch, 145 bytes

```
@set s=%time:~,8%
@set/as=((%s::=)*60+%,f=s%%3,b=s%%5,t=f+b
@for %%a in (Fizz.%f% Buzz.%b% FizzBuzz.%t%)do @if %%~xa==.0 set s=%%~na
@echo %s%

```

Explanation: `%time%` is (at least on my system) formatted `hh:mm:ss.ff` so we start by chopping off the fractions of seconds. Then the shortest way to do the base 60 conversion is to replace the `:`s with operators and evaluate, and the divisibility by 3, 5 and 15 is also calculated. This is then tested and the number of seconds replaced with the appropriate string if necessary before being printed.

# Answer
> 1 votes
# MathGolf, 24 bytes

```
t♪/╔%_╕Σ╠δ╕┌╠δ`+Γ\35α÷ä§

```

Try it online!

## Explanation

```
t                          unix timestamp as integer milliseconds
 ♪/                        divide by 1000
   ╔%                      modulo 86400
     _                     duplicate TOS
      ╕Σ╠δ                 Decompress "Σ╠" and capitalize to get "Fizz"
          ╕┌╠δ             Decompress "┌╠" and capitalize to get "Buzz"
              `            duplicate the top two items
               +           pop a, b : push(a+b)
                Γ          wrap last four elements in array
                 \         swap top elements (swaps 2nd copy of time to TOS)
                  35α      push [3, 5]
                     ÷     is divisible
                      ä    convert from binary
                       §   get from array

```

# Answer
> 0 votes
# Jelly, 45 bytes

```
%3,5¬ȧ"“Fizz“Buzz”o"““”Fȯ⁸
7ŒTṣ”:V×⁽½c,60,1SÇ

```

Try it online!

This is so bad

34 bytes if I steal Dennis's FizzBuzz

# Answer
> 0 votes
# Bash, 154

```
z=$(($(date +%s)-$(date -d "$(date +%F) 0" +%s)))
[[ 0 -eq "($z%3)" ]]&&a=1&&echo -n "fizz"
[[ 0 -eq "($z%5)" ]]&&echo "buzz"||[ $a -eq 1 ]&&echo||echo $z

```

could probably golf down last two lines...

# Answer
> 0 votes
# JavaScript (Node.js), ~~125~~ 120 bytes

```
x=Date().match(/\d\d/g).slice(3,6).reduce((a,j,i)=>a+=60**(2-i)*j)
console.log((x%3==0?'Fizz':'')+(x%5==0?'Buzz':'')||x)

```

Try it online!

---

First line parses a date string for `[hours, minutes, seconds]` and adds them together, second line is just FizzBuzz.

# Answer
> 0 votes
# Perl 5, 74 bytes

```
$t+=$_*60**$g++for(gmtime)[0..2];say+(($t%3==0&&Fizz).($t%5==0&&Buzz))||$t

```

Try it online!

# Answer
> 0 votes
# Bash, 76 bytes

```
date +'%H 60*%M+60*%S+[p]sc[[]sc[Fizz]n]sa[[]sc[Buzz]n]sbd3%0=ad5%0=blcx'|dc

```

Try it online!

# Answer
> 0 votes
# APL (Dyalog Unicode), 40 bytesSBCS

```
{∨/d←0=4/3 5|⍵:d/'FizzBuzz'⋄⍵}60⊥3↑3↓⎕TS

```

Try it online!

`⎕TS`**T**ime **S**tamp; e.g. `[2019,06,14,07,48,20,317]`

`3↓` drop three; e.g. `[07,48,20,317]`

`3↑` take three; e.g. `[07,48,20]`

`60⊥` evaluate as base-60 digits; e.g. `28100`

`{``}` apply the following anonymous lambda to that:

the argument; e.g. `28100`

`3 5|` the division remainder when that is divided by 3 and 5; e.g. `[2,0]`

`0=` Boolean mask where that is equal to 0; e.g. `[0,1]`

`4/` replicate those numbers for 4 copies of each; e.g. `[0,0,0,0,1,1,1,1]`

`d←` assign that to `d`

`∨/``:` if any of those are true (OR-reduction); e.g. `true`:

`d/'FizzBuzz'` use `d` to mask the characters of the string; e.g. `"Buzz"`

else:

the argument; e.g. `28100`

# Answer
> 0 votes
# AutoIt, 90 bytes

```
$a=(@HOUR*60+@MIN)*60+@SEC
ConsoleWrite($a&(Mod($a,3)=0?"Fizz":"")&(Mod($a,5)=0?"Buzz":""))

```

It looks really bad without whitespace.

(FYI: AutoIt is a Windows basic-like scripting language)

# Answer
> 0 votes
# Pyth, 36 bytes

```
Js%.dZ84600|+*!%J3"Fizz"*!%J5"Buzz"J

```

Try it online!

Loosely based on the Python 2 answer.

---
Tags: code-golf, date
---


title: Transpose a page of text

text:
# Question
Title: Transpose a page of text
**EDIT** I modified the wording of the rules to make some things which were implicit more explicit. I also added some emphasis to clear up some points of apparent confusion, and explicitly defined the option of making a standalone program instead of a function.

The goal here is to make a function that takes a text file (or string) and transposes it so that lines become columns and vice versa.

**Example:**

```
I am a text.
Transpose me.
Can you do it?

```

Results in:

```
ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?

```

**The rules:**

* You are allowed to assume that the only whitespace characters used are `" "` and `"\n"` and that there is no trailing whitespace on any line.
* You may assume that the file is ASCII. Which endline marker you want to use is up to you.(CRLF or LF). It must work correctly on the example, but it should also work on **any** input that satisfies the above assumptions.
* You might have to insert spaces (as in the example) where there were none in order to keep the columns in line.
* Your result **must not** have trailing whitespace **on any line**.
* The final newline character(for the last line) is optional.
* **It should be either a function or a complete program.** If your **function** accepts a string, then it should return the results as a string. If it accepts a filename, then you return the name of the file where you saved the result. You are additionally allowed to write a **complete program** that accepts input from STDIN and outputs the correct result to STDOUT; if you do this, you must **not** output anything to STDERR.
* Shortest procedure wins, but I will upvote any answer I like.

Based on the rules, the output on the example is either 53 or 52 bytes long (for LF newlines) depending on whether the final newline is included or not.

**Note:** It is not a specific requirement, but if your function, when run twice successively is not identical to the original(the final newline might be differ, and any empty lines at the end of the file will be deleted), then you are *probably* breaking one of the rules.

# Answer
# Japt, 6 bytes

```
y mx1R

```

Try it
Run it twice \- returns original string

---

## Explanation

```
y

```

Transpose the input

```
m  R

```

Map over each line

```
x1

```

Trim right
> 2 votes

# Answer
## J (~~31~~ 40)

```
f=:3 :';(,&LF@dlb&.|.)&.><"1|:>LF cut y'

```

This is a function that takes a string, and returns a string (i.e. a character *vector* with linefeeds inserted in the right places, and not a matrix.)

Edit: no trailing whitespace on any line.

Test:

```
   f=:3 :';(,&LF@dlb&.|.)&.><"1|:>LF cut y'

   string=:stdin''
I am a text.
Transpose me.
Can you do it?
^D

   $string
42
   $f string
53
   f string
ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?

```
> 4 votes

# Answer
**Python 2.7 (~~97~~ ~~79~~ ~~94~~ 90)**

EDIT: Missed the function requirement;

I'm fairly sure this will be improved on since I'm sort of a beginner here, but to start with;

```
c=lambda a:'\n'.join(''.join(y or' 'for y in x).rstrip()for x in map(None,*a.split('\n')))

```

The code uses a simple `split` to split the string into a vector of rows. It then uses `map` with a function value as `None` (the unity function) and the splat operator to transpose and pad the vector (similar functionality to `zip_longest` in Python3)

The rest of the code just maps `None` to space, trims and reassembles the matrix to a single string again.

```
>>> a = 'I am a text.\nTranspose me.\nCan you do it?'
>>> c(a)
'ITC\n ra\naan\nmn\n sy\napo\n ou\nts\need\nx o\ntm\n.ei\n .t\n  ?'
>>> len("""c=lambda a:'\n'.join(''.join(y or' 'for y in x).rstrip()for x in map(None,*a.split('\n')))""")
88
# (+2 since `\n` is considered by `len` to be a single char)

```
> 4 votes

# Answer
**Ruby 111**

Golfed:

```
def f t;s=t.lines;s.map{|l|l.chomp.ljust(s.map(&:size).max).chars}.transpose.map{|l|l.join.rstrip+?\n}.join;end

```

Ungolfed:

```
def transpose_text(text)
  max_length = text.lines.map(&:size).max
  text.lines.map do |line|
    line.chomp.ljust(max_length).chars
  end.transpose.map do |chars|
    chars.join.rstrip + "\n"
  end.join
end

```

Ruby has an array transpose function, so this simply pads the lines out, turns them into an array of characters, uses Ruby's Array#transpose function, then turns the array of characters back into lines.

Golfing it was simply using single-character identifiers, removing spaces, using a temporary for text.lines, and putting the calculation for max\_length inline (there are no points for efficiency).
> 4 votes

# Answer
## R, 171

```
function(e){p=strsplit
x=t(plyr::rbind.fill.matrix(lapply(p(p(e,"\n")[[1]],""),t)))
x[is.na(x)]=" "
cat(apply(x,1,function(y)sub(" *$","",paste(y,collapse=""))),sep="\n")}

```

Usage example:

```
text <- "I am a text.
Transpose me.
Can you do it?"

(function(e){p=strsplit
x=t(plyr::rbind.fill.matrix(lapply(p(p(e,"\n")[[1]],""),t)))
x[is.na(x)]=" "
cat(apply(x,1,function(y)sub(" *$","",paste(y,collapse=""))),sep="\n")})(text)

ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?

```

Trailing whitespace is removed.
> 4 votes

# Answer
# Bash+coreutils+sed, 83

```
eval paste `sed 's/.*/<(fold -w1<<<"&")/'`|expand -t2|sed 's/\(.\) /\1/g;s/ \+$//'

```

`fold` and `paste` do the important work. The rest is just formatting.

Accepts input from stdin and outputs to stdout:

```
$ < tr.txt ./transposefile.sh
ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?
$ < tr.txt ./transposefile.sh | ./transposefile.sh
I am a text.
Transpose me.?
Can you do it
$

```
> 4 votes

# Answer
**C (278 bytes)**

*Edit: This actually breaks the rules, since it takes a filename in as an argument but writes to stdout. I'll edit it later to write to a file and then print the filename to stdout.*

This is my first code golf ever, so have mercy. Some plain old C. Place the input in `test.txt` and let it run!

`clang transpose.c -o transpose && ./transpose test.txt`

```
#import <stdio.h>
#import <stdlib.h>
#import <string.h>

#define BUFFER_SIZE 1024

#define MAX(A,B) ((A)>(B)?(A):(B))

int main(int argc, char **argv) {
    char line[BUFFER_SIZE];

    FILE *f; int nLines, maxLen;

    f = fopen(argv[1], "r");
    while(!feof(f) && fgets(line, BUFFER_SIZE, f)) {
        nLines++;
        maxLen = MAX(maxLen, strlen(line));
    }
    fclose(f);

    for (int charPos = 0; charPos < maxLen; charPos++) {
        f = fopen(argv[1], "r");
        for (int linePos = 0; linePos < nLines; linePos++) {
            fgets(line, BUFFER_SIZE, f);
            printf("%c", charPos < strlen(line) && line[charPos] != '\xA' ? line[charPos] : ' ');
        }
        printf("\n");
        fclose(f);
    }

    return 0;
}

```

By using short variable names, removing gratuitous formatting, and allowing file handles to leak, and disabling all warnings this is reduced to 278 bytes. (Since this uses implicit imports, it may not link properly on all systems. Works on my machine!)

```
#import <stdio.h>
int main(int C,char**V){char L[1024];int A,B,D,I,J,*F=fopen(V[1],"r");while(!feof(F)&&fgets(L,1024,F)){A++;D=strlen(L);B=B>D?B:D;}for(I=0;I<B;I++){F=fopen(V[1],"r");for(J=0;J<A;J++)fgets(L,1024,F)&&printf("%c",I<strlen(L)&&L[I]!='\n'?L[I]:' ');printf("\n");}}

```
> 3 votes

# Answer
## AutoHotkey 210

```
f(i){
StringSplit,o,i,`n
m:=0
loop % o0 {
a:=A_index
if (t:=Strlen(p:=o%a%))>m
m:=t
StringSplit,l%a%,o%a%
}
loop % m {
a:=A_index,n:=""
loop % o0
n.=(j:=l%A_index%%a%)=""?" ":j
s.=Rtrim(n," ") "`n"
}
return s
}

```

### Test

```
text=
(
I am a text.
Transpose me.
Can you do it?
)
msgbox % f(text)

```
> 3 votes

# Answer
# Bash, 124 bytes

```
D=`mktemp -d`;split -l1 - $D/;for F in $D/*;do grep -o . $F>$F+
done;paste $D/*+|sed -e's/\([^\t]\)\t/\1/g;s/\t/ /g;s/ *$//'

```

It reads standard input and writes standard output. Try it:

```
echo $'I am a text.\nTranspose me.\nCan you do it?' | script.sh

```

How it works:

* `split` input into single lines (files in temporary directory `$D`)
* split lines into single characters using `grep` (files \*+)
* layout characters side-by-side using `paste` (TAB-separated columns)
* remove alignment TABs, replace filler TABs with BLANKs, trim using `sed`

Edit:

* -9: Removed tidy-up code `;rm -r $D` (thanks Tim)
* -2: use `+` instead of `_` as suffix and shorten `${F}_` to `$F+`
* -3: remove prefix `L` from split result files
> 3 votes

# Answer
# Ruby: 88 characters

(Posted because it's shorter then the other Ruby solutions. Not checked whether my code introduces anything new compared to those. If you already posted a Ruby solution and you feel this is mostly a copy of yours, please comment and I will retire my answer.)

```
f=->t{l=t.split$/;r=[""]*m=l.map(&:size).max;l.map{|l|m.times{|i|r[i]+=l[i]||" "}};r*$/}

```

Sample run:

```
irb(main):001:0> f=->t{l=t.split$/;r=[""]*m=l.map(&:size).max;l.map{|l|m.times{|i|r[i]+=l[i]||" "}};r*$/}
=> #<Proc:0x99a9e68@(irb):1 (lambda)>

irb(main):002:0> sample='I am a text.
irb(main):003:0' Transpose me.
irb(main):004:0' Can you do it?'
=> "I am a text.\nTranspose me.\nCan you do it?"

irb(main):005:0> puts f[sample]
ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?
=> nil

irb(main):006:0> puts f[f[sample]]
I am a text.
Transpose me.
Can you do it?
=> nil

```
> 3 votes

# Answer
# Retina, 40 bytes

```
P`.+
~L0$`.
L,$.%'vs,$.(x$%=),`.+
m` *$

```

**Try it online!**

Based on this program that I created to transpose any size of rectangle, which uses Leo's suggestion for transposing a rectangle of a known size.

Edit: Golfed more and no longer has trailing spaces on lines.
> 3 votes

# Answer
### Ruby — 144 characters

Here's my first attempt, golfed:

```
def f t
t.split(?\n).each{|l|l<<' 'until l.size==t.split(?\n).map(&:size).max}.map{|x|x.split('')}.transpose.map{|l|l.join.rstrip}.join(?/n)
end

```

For output, run `puts f text` where `text` is any multi-line string adhering to the rules above. The ungolfed version is below:

```
def text_transpose(text)
  lines = text.split(?\n)
  maxlen = lines.map(&:size).max
  lines.each { |line| line << ' ' until line.size == maxlen }
       .map  { |line| line.split('') }.transpose
       .map  { |char| char.join.rstrip }.join(?\n)
end

```

For a similar, but ultimately better solution in Ruby, check out Wayne Conrad's code above.
> 2 votes

# Answer
**PHP 194**

```
function x($a){$a.="\n";$s=strlen($a);$i=0;while($c<$s)if($a{$c}!="\n")$b[$i++].=$a{$c++};else{$c++;for(;$i<$s;$i++)$b[$i].=" ";$i=0;}ksort($b);return rtrim(implode("\n",array_map("trim",$b)));}

```

Non-golfed:

```
function x($a) {
    $a.="\n";
    $s=strlen($a);
    $i=0;
    while($c<$s)
        if($a{$c}!="\n")
            $b[$i++].=$a{$c++};
        else{
            $c++;
            for(;$i<$s;$i++)
                $b[$i].=" ";$i=0;
        }
    ksort($b);
    return rtrim(implode("\n",array_map("trim",$b)));
}

```

This is my first golfing attempt, so please be kind! Also, tips/suggestions would be greatly appreciated!
> 2 votes

# Answer
## MATHEMATICA 117 chars

```
t = "I am a text.\nTranspose me.\nCan you do it?";

f=(m=Length/@(f=Flatten[Characters/@StringSplit[#,"\n"],{{2},{1}}])//Max;
StringJoin@@@(PadLeft[#,m," "]&/@f)//Column)&

```
> 2 votes

# Answer
# Perl (92+1)

reads stdin and writes to stdout. adding 1 to the score for `say`

```
@L=map[grep!/\n/,split//],<>;do{$_=join'',map shift@$_||$",@L;s/ +$//;say}while grep@$_>0,@L

```
> 2 votes

# Answer
# CJam, ~~32~~ 25 bytes

CJam is newer than this challenge, so this answer is not eligible for being accepted.

Considerably shortened by user23013.

```
qN/_z,f{Se]}z{S+e`);e~N}%

```

Test it here.

```
qN/                       "Read input, split into lines.";
   _z,                    "Transpose, get length (find maximum line length).";
      f{Se]}              "Pad each line to that length with spaces.";
            z             "Transpose.";
             {         }% "Map this block onto each line in the result.";
              S+          "Add a space to ensure there's at least one.";
                e`        "Run-length encode.";
                  );      "Discard the trailing run of spaces.";
                    e~    "Run-length decode";
                      N   "Push a newline.";

```
> 2 votes

# Answer
# Javascript, 103

```
s=>[...s].map((_,i)=>s.split`
`.map(b=>r+=b[q=b[i]||q,i]||' ',r=q='')&&r.replace(/ *$/,q?`
`:q)).join``

```

*Less golfed*

```
s=>[...s].map(
     // we need 'i' ranging from 0 to the length of the longest input line
     // so we scan all the input string, that is surely longer
     // but we need to check that after some point the output must be empty
     (_, i) => (
       r = '', // the current output row, starts empty
       q = '', // flag to check if we are beyond the longest line
       s.split('\n') // split in rows
       .map(
         b => ( // for each input row in b
           q = b[i] || q, // if there is a char at position i in b, i goes to q
           r += b[i] || ' ' // add to output the char at position i or a fill space
         )
       ),
       q // if q is still '', we are beyond the longest input line
       ? r.replace(/ *$/,`\n`) // trim leading space and add newline
       : '' // no output
     )
   ).join('')

```

**Test**

```
F=
s=>[...s].map((_,i)=>s.split`
`.map(b=>r+=b[q=b[i]||q,i]||' ',r=q='')&&r.replace(/ *$/,q?`
`:q)).join``

function go() {
  var text=I.value
  var output = F(text)
  O.textContent = output
}

go()
```

```
#I { width:50%; height:5em }
```

```
<textarea id=I>I am a text.
Transpose me.
Can you do it?</textarea><br>
<button onclick='go()'>Transpose</button>
<pre id=O></pre>
```
> 2 votes

# Answer
## Perl 5, 25 bytes

Note that this uses ANSI escape sequences and as such does not work on TIO, you can however see it in action here.

```
$"="";$_="[1;$.H@F"

```

### Explanation

This code first changes the list separator (`$"`) value to be a vertical tab, followed by the ANSI escape sequence for 'go backwards 1 column' (`\x1b[1D`), then we set the implicitly printed variable `$_` to be a string that starts with the ANSI escape sequence for 'start printing at line 1 column `$.` (where `$.` is the current line of text)' (`\x1b1;$.H`) and interpolates the list `@F` (which is a list of all the characters on that line, populated by autosplit (`-a`) with an empty split pattern (`-F`)) which places the contents of `$"` in between each item, moving the cursor vertically down instead of continuing output after the previous character.

Try it online!
> 2 votes

# Answer
## C++ (243 characters)

Here's a function that takes and returns a string.

I could've shaved a couple dozen chars, but decided to keep it as not-stupid code (runs fast, reads okay). Maybe I only decided to do that because this is my first code golf... I'm not hardcore enough yet :)

```
string f(string s){stringstream ss(s);vector<string> v;for(size_t i=0;getline(ss,s);++i){if(v.size() < s.size())v.resize(s.size());for(size_t j=0;j<s.size();++j){v[j].resize(i,' ');v[j].push_back(s[j]);}}s="";for(auto& i:v)s+=i+'\n';return s;}

```

With formatting:

```
string f(string s)
{
    stringstream ss(s);
    vector<string> v;

    for(size_t i = 0; getline(ss, s); ++i)
    {
        if(v.size() < s.size())
            v.resize(s.size());

        for(size_t j = 0; j < s.size(); ++j)
        {
            v[j].resize(i, ' ');
            v[j].push_back(s[j]);
        }
    }

    s = "";
    for(auto& i : v)
        s += i + '\n';

    return s;
}

```
> 1 votes

# Answer
Python 2.7 - **115 chars**:

oneliner:

```
>>> a
'I am a text.\nTranspose me.\nCan you do it?'

>>> "".join(["".join(i)+'\n' for i in zip(*[x+" "*(len(max(a.splitlines(), key=len))-len(x)) for x in a.splitlines()])])
'ITC\n ra\naan\nmn \n sy\napo\n ou\nts \need\nx o\ntm \n.ei\n .t\n  ?\n'

```

and in a cleaner printing:

```
>>> print "".join(["".join(i)+'\n' for i in zip(*[x+" "*(len(max(a.splitlines(), key=len))-len(x)) for x in a.splitlines()])])
ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?

```

**in 115 chars:**

```
>>> len(""""".join(["".join(i)+'\n' for i in zip(*[x+" "*(len(max(a.splitlines(), key=len))-len(x)) for x in a.splitlines()])])""")
115

```
> 1 votes

# Answer
## GolfScript, 51 chars

```
n%.{,}%$-1=" "*:y;{y+y,<}%zip{n\+0{;).32=}do}%((;\+

```

This is a first attempt; I suspect it can be improved. Most of the code is to comply with the padding and trailing space removal requirements — without them, just `n%zip n*` would suffice.

Ps. The following **46**-character version will do the job for the given sample input, but will crash if any input column consists entirely of spaces:

```
n%.{,}%$-1=" "*:y;{y+y,<}%zip{0{;).32=}do]}%n*

```

I assume that's enough to disqualify it, even if the challenge doesn't explicitly say so.
> 1 votes

# Answer
Python ~~89~~ 103 chars

```
def f(a):return'\n'.join([''.join(i).rstrip()for i in zip(*[j+' '*99 for j in a.split('\n')])]).rstrip()

```

I feel dirty. ~~90~~ 104 chars for industrial strength version. :^)
> 1 votes

# Answer
# Scheme/Racket 113

The text:

```
(define t (list
    (string->list "I am a text.")
    (string->list "Transpose me.")
    (string->list "Can you do it?")
))

```

Without new lines and extra white spaces:

```
(define s(λ(v x)(if(= x 0)'()(cons(list->string(car v))(s(cdr v)(- x 1))))))(s(apply map list t)(length(car t)))

```

The user-friendly version

```
(define text (list
    (string->list "I am a text.")
    (string->list "Transpose me.")
    (string->list "Can you do it?")
))

(define transpose
    (λ(text length)
        (if (= length 0)
            '()
            (cons (list->string (car text)) (transpose (cdr text) (- length 1)))
)))

(transpose (apply map list text) (length (car text)))

```
> 1 votes

# Answer
## Haskell

```
import Data.List
main = interact (unlines . transpose . lines)

```

It was so short, I needed to add in white space...
> 1 votes

# Answer
# Mathematica, 95 chars

```
f=""<>Riffle[Thread@PadRight@Characters@StringSplit[#,"\n"]//.{0->" ",{x___," "..}:>{x}},"\n"]&

```
> 1 votes

# Answer
# K, 56

This should meet the spec now.

Accepts a string, returns a string.

```
{`/:{$[" "=*|x;|(+/&\" "=|x)_|x;x]}'x@'/:!max@#:'x:`\:x}

```

.

```
k)f:{`/:{$[" "=*|x;|(+/&\" "=|x)_|x;x]}'x@'/:!max@#:'x:`\:x}
k)f"I am a text.\nTranspose me.\nCan you do it?"
"ITC\n ra\naan\nmn\n sy\napo\n ou\nts\need\nx o\ntm\n.ei\n .t\n  ?\n"
k)f f"I am a text.\nTranspose me.\nCan you do it?"
"I am a text.\nTranspose me.\nCan you do it?\n"

```
> 1 votes

# Answer
# Groovy, 98 chars

```
{i->o=[].withDefault{''};i.readLines().each{it.toList().eachWithIndex{c,d->o[d]+=c}};o.join('\n')}

```

online

ungolfed:

```
{i->
o=[].withDefault{''};//create list with empty string as default value
i.readLines()
.each{
    it.toList() //split every line to characters
    .eachWithIndex{
        c,d->o[d]+=c //append to string from list with right index
    }
};
o.join('\n')}//join list with newlines
}

```
> 1 votes

# Answer
# C (MinGW), ~~272~~ ~~262~~ ~~259~~ ~~254~~ ~~234~~ ~~229~~ 228 bytes

-15 bytes thanks to ceilingcat

The TiO link requires the string.h include, but MinGW does not.

```
n,a,i,j;*f(int*s){char*p,**L=a=n=i=0,*r;for(;p=strtok(L?0:s,"\n");j>a?a=j:0)j=strlen((L=realloc(L,++n*8))[n-1]=p);for(p=r=calloc(n+1,a+1);i<a;i++,*p++=10){for(j=0;j<n;j++)*p++=i<strlen(L[j])?L[j][i]:32;while(p[-1]==32)p--;}s=r;}

```

Try it online!
> 1 votes

# Answer
# Pyth, 11 bytes

```
# aYcw1;.tY

```

Try it online!

Takes input as a string, outputs a list of lists

# Pyth, 25 bytes

```
# aYcw1=+Z1;jbcj"".n.tY)Z

```

Takes input as a string, outputs a string.

Try it online!
> 1 votes

# Answer
# J, ~~28~~ 26 Bytes

Saved 2 bytes thanks to frownyfrog

```
t=.,@:(,&LF"1)@|:@:>@cutLF

```

Takes a string, returns a string. I'm not sure if there's a shorter version of the 'cutopen' ~~function~~ *verb* that I could use.

There's also the shorter

```
t=.|:@:>@cutLF

```

But I'm not sure it falls within the OP's guidelines, as it returns an array of characters.

### How it works:

```
                     cutLF   | Splits the input on new lines and boxes them
                    @        | Composes verbs (as does @:, but they're not equal)
                   >         | Unboxes this, forming an array of the lines
                 @:          |
               |:            | Transposes the array
      (      )@              |
       ,&LF                  | Appends a new line...
           "1                | To each row of the array
    @:                       |
   ,                         | Flatten the result
t=.                          | Assign this verb to t

```

The other version works the same, but doesn't convert the transposed array to a properly formatted string.

### Examples:

```
NB. Define a multi-line string

    text =: 0 : 0
I am a text.
Transpose me.
Can you do it?
)

    t text
ITC
 ra
aan
mn    NB. There's whitespace after the 'n' here, but I assume it doesn't count as trailing since it's part of the original string
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?

    t t text
I am a text.     NB. Again, whitespace here, but it's part of the argument of the second 't' (added by the first 't' to keep columns straight)
Transpose me.
Can you do it?

```
> 1 votes

# Answer
# Lua, ~~203~~ 189 bytes

```
t={{}}i=1m=0(...):gsub(".",function(c)n=#t[i]if c=="\n"then i=i+1t[i]={}else t[i][n+1]=c end m=m<=n and n+1or m end)
for x=1,m do for p=1,i do io.write(t[p][x]or" ")end _=m<=x or print()end

```

Try it online!

I saw another Lua solution here, but I don't think there's a problem with posting 2 solutions on the same language. If there is, tell me :)
> 1 votes

# Answer
# Python 2, ~~87~~ 101 bytes

```
lambda s:T('\n'.join(map(T,map(''.join,zip(*[t.ljust(len(s))for t in s.split('\n')])))))
T=str.rstrip

```

Try it online!
> 1 votes

# Answer
# MATLAB: ~~24~~ ~~42~~ 29 bytes

```
@(s)deblank(string(char(s)'))

```

**Usage**

```
s=["I am a text.";"Transpose me";"Can you do it?"];
@(s)deblank(string(char(s)'))
ans(s)

```

**Output**

```
ans =

  14×3 char array

    'ITC'
    ' ra'
    'aan'
    'mn'
    ' sy'
    'apo'
    ' ou'
    'ts'
    'eed'
    'x o'
    'tm'
    '.ei'
    '  t'
    '  ?'

```

Might be cheating here, as it's hard (as far as I can see) to get a string with newlines into MATLAB without using an array, so I went ahead and used an array for the input. Other than that, it does what it says on the tin - turns the string into a matrix of chars, transposes it and trims the whitespace.

**Edit:** Changed (and lengthened) the program as I didn't see the requirement for whitespace to be trimmed.

**Edit:** -13 bytes thanks to sundar.
> 1 votes

# Answer
# 05AB1E, 6 bytes

```
ζεðÜ}»

```

Try it online.
Try it when taking the output as input-list again.

**Explanation:**

```
ζ         # Zip the input-list, swapping rows and columns
 ε  }     # For-each:
  ðÜ      #  Remove trailing spaces
     »    # Join the resulting list by new-lines (and output implicitly)

```
> 1 votes

# Answer
# MATL, 5 bytes

```
!Z{Zv

```

Try it on MATL Online

Input is taken implicitly, and conveniently, the shorter lines get spaces added to them by the environment to make them all equal in length.

`!` \- transpose

`Z{` \- Convert to cell array (since we'll need to hold arrays of different lengths after the next step)

`Zv` \- deblank i.e. remove the trailing spaces
> 1 votes

# Answer
# Octave, ~~35~~ 29 bytes

```
@(s)strjoin(cellstr(s'),'\n')

```

Try it online!

*(-1 byte thanks to Luis Mendo, -5 bytes thanks to strjoin from this SO answer)*
> 1 votes

# Answer
# JavaScript, 102 100 bytes

```
q=>[...q].reduce((r,e,j)=>(y=w.map((e,i)=>w[i][j]||" ").join``.trimEnd())?r+y+`
`:r,"",w=q.split`
`)

```

# Run it here:

```
f = q=>[...q].reduce((r,e,j)=>(y=w.map((e,i)=>w[i][j]||" ").join``.trimEnd())?r+y+`
`:r,"",w=q.split`
`);

console.log(f(`I am a text.
Transpose me.
Can you do it?`));
```
> 1 votes

# Answer
**PHP 227 217**

Here's my attempt:

```
function f($s){$p=array_map;$s=$p(str_split,explode("
",$s));foreach($s as&$l)$l=array_pad($l,max($p(count,$s)),' ');array_unshift($s,null);foreach(call_user_func_array($p,$s)as$l)$r.=rtrim(implode($l))."
";return$r;}

```

Ungolfed:

```
<?php
function f($s) {
    $s=array_map(str_split, explode("\n",$s));
    foreach($s as &$l)
        $l=array_pad($l, max(array_map(count, $s)),' ');
    array_unshift($s, null);
    foreach(call_user_func_array(array_map, $s)as$l)
        $r.=rtrim(implode($l))."\n";
    return $r;
    }
$s="I am a text.
Transpose me.
Can you do it?";
echo f($s);
echo strlen(f($s));

```
> 0 votes

# Answer
**Haskell: 191 chars**

```
import Data.List
h [] = ' '
h (x:_) = x
t [] = []
t ([]:x) = t (" ":x)
t ((x:y):z) = takeWhile (any (/= ' ')).map (dropWhileEnd (== ' '))$(x:map h z):t (y:[s |(_:s)<-z])
m = (unlines.t.lines)

```
> 0 votes

# Answer
# JavaScript, ~~177~~ 173 bytes

```
s=>{l=s.split`
`.sort((a,b)=>b.length-a.length)[0];for(i=0,t=[];i<l.length;i++){t[i]=s.split`
`.map(i=>i+" ".repeat(l.length-i.length)).map(j=>j[i]).join``}return t.join`
`}

```
~~```
s=>{l=s.split`\n`.sort((a,b)=>b.length-a.length)[0];for(i=0,t=[];i<l.length;i++){t[i]=s.split`\n`.map(i=>i+" ".repeat(l.length-i.length)).map(j=>j[i]).join``;}return t.join`\n`}

```~~

If you can help me shorten this up, please do so.
> 0 votes

# Answer
# PHP, ~~95+0~~ ~~108+1~~ 110 bytes

```
foreach($input as $s)for($y=0;~$c=$s[$y];)$r[$y++].=$c>"
"?$c:" ";echo rtrim(join("
",array_map(rtrim,$r)));

```

takes input from STDIN; breaks at the first empty line. Run with `-nr` or try it online.

Still trying to find something shorter than the additional rtrim to get rid of the second newline.
> 0 votes

# Answer
# Perl 5, 81 bytes

```
chomp(@a=<>);say((join"",map{(substr$_,0,1,"")||$"}@a)=~s/\s+$//r)while"@a"=~/\S/

```

Try it online!
> 0 votes

# Answer
# Lua, 205 bytes

```
L={}C=0 R=io.read I=R()while I~=""do L[C]=I C=C+1 I=R()end M=0 for i=0,C-1,1 do if#L[i]>M then M=#L[i]end end for i=1,M,1 do for j=0,C-1,1 do io.write(L[j]:sub(i,i)==""and" "or L[j]:sub(i,i))end print()end

```

Try it online!

Ungolfed

```
lines={}
count=0
R=io.read
input=R()

-- reads input in until an empty line is found
-- lines are added to the lines table
while input~="" do
    lines[count]=input
    count=count+1;
    input=R()
end

-- find the length of the longest string
max_len=0
for i=0,count-1,1 do
    if #lines[i]>max_len then
        max_len=#lines[i]
    end
end

-- loop through each character of each string
for i=1,max_len,1 do
    for j=0,count-1,1 do
        -- print the string's next character
        -- or a space if there is not another character
        if lines[j]:sub(i,i)=="" then--this if statement is golfed into a
            io.write(" ")            --pseudo-ternary statement in the golfed version
        else
            io.write(lines[j]:sub(i,i))
        end
    end
    print()
end

```
> 0 votes

# Answer
## Pyth, 2 bytes

```
.t

```

Try it here!

Performs the built in transpose function on an input list, outputting a list of lines.

---

## Pyth, 7 bytes

```
V.t.zdN

```

Try it here!

The above program, modified to use the input and output format specified in the challenge.
> 0 votes

# Answer
# Excel VBA, 154 bytes

Takes input from `[A1]` and outputs to the console.

```
x=Split([A1],vbLf):u=UBound(x):For i=0To u:l=Len(x(u)):m=IIf(m>l,m,l):Next:For i=1To m:For j=0To u:s=s+Mid(x(j)&String(m,32),i,1):Next:?RTrim(s):s="":Next

```

### Ungolfed

```
x=Split([A1],vbLf)              ''  Split input by lines
u=UBound(x)                     ''  Get number of lines
For i=0To u                     ''  Iterate over lines
l=Len(x(u))                     ''  Get length of line `i`
m=IIf(m>l,m,l)                  ''  Compare to max length; Store Max
Next                            ''  Loop
For i=1To m                     ''  Iterate over chars in line
For j=0To u                     ''  Iterate over lines
s=s+Mid(x(j)&String(m,32),i,1)  ''  Append `i`th char of `j`th line to `s`
Next                            ''  Loop
?RTrim(s)                       ''  Remove right whitespace, print
s=""                            ''  Reset `s`
Next                            ''  Loop

```
> 0 votes

# Answer
# K (oK), 43 bytes

**Solution:**

```
{"\n"/{(-+/&\32=|x)_x}@'+(|/#:'x)$x:"\n"\x}

```

Try it online!

**Explanation:**

Break on newlines, pad lines to same lengths, transpose, trim trailing whitespace and join on newlines. Feels like there has to be an easier way...

```
{"\n"/{(-+/&\32=|x)_x}@'+(|/#:'x)$x:"\n"\x} / the solution
{                                         } / lambda
                                         x  / input x
                                    "\n"\   / split (\) on "\n"
                                  x:        / save as x
                                 $          / pad right with left
                         (      )           / do this together
                            #:'x            / count (#:) each (') x
                          |/                / max
                        +                   / transpose
      {              }@'                    / apply (@) lambda to each (')
                    x                       / input x
                   _                        / drop
       (          )                         / do this together
                |x                          / reverse (|) x
             32=                            / equal to ASCII 32 aka " "
           &\                               / min
         +/                                 / sum
        -                                   / negate
 "\n"/                                      / join (/) on "\n"

```
> 0 votes

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