# Question
Title: Finding prime numbers without using "prime characters"
Your task, if you choose to accept it, is to write a program/function that accepts an integer \\$N\\$ as input. The program/function should output/return a list of the first \\$N\\$ prime numbers. But here's the catch: you are not allowed to use *prime characters* in your code. A prime character is a character whose Unicode code point is a prime number. In the printable ASCII range, these are:

```
%)+/5;=CGIOSYaegkmq

```

But the rule also applies to non-ASCII characters if your code uses those.

* A valid input is an integer \\$N\\$ where \\$0 \< N \le T\\$, where you can choose \\$T\\$, but it has to be greater than or equal to \\$10000\\$. \\$T\\$ does not have to be finite.
* For invalid inputs (non-integers, integers out of range), throw an exception or output/return nothing/null.
* An integer with leading/trailing whitespace as input is considered invalid.
* An integer with a `+` as sign character as input is considered invalid.
* An integer with leading zeros as input is considered valid.
* If your language allows you to pass an already-parsed integer as input, the above parsing rules (except the range one) don't apply, because the int is already parsed.
* The input is always base-10.
* Use of built-in prime generators and primality testers (this includes prime factorization functions) is not allowed.
* The source restriction is imposed on Unicode characters, but the byte counting for the score can be in another encoding if you wish.
* The output can contain a single trailing newline, but this is not required.
* If you output/return the prime number list as a string, then every prime number must be delimited by one or multiple non-digit char(s). You can choose which delimiter you use.
* This is a challenge, the shortest code in bytes wins.

## Stack Snippet to verify your code

You can use the below Stack Snippet to verify that your code does not contain prime chars:

```
var primes=[],max=10000;for(var i=2;i<=max;i++){primes.push(i);}for(var N=2;N<Math.sqrt(max);N++){if(primes.indexOf(N)===-1){continue;}primes=primes.filter(function (x){return x===N||x%N!==0;});}function setText(elem,text){var z=('innerText' in elem)? 'innerText' : 'textContent';elem[z]=text;}function verify(inputCode,resultSpan){var invalidChars=[];var success=true;for(var i=0;i<inputCode.length;i++){var cc = inputCode.charCodeAt(i);if (cc>max){setText(resultSpan,"Uh oh! The char code was bigger than the max. prime number calculated by the snippet.");success = false;break;}if (primes.indexOf(cc)!==-1){invalidChars.push(inputCode[i]);}}if (invalidChars.length===0&&success){setText(resultSpan, "Valid code!");}else if(success) {  var uniqueInvalidChars = invalidChars.filter(function (x, i, self){return self.indexOf(x)===i;});setText(resultSpan, "Invalid code! Invalid chars: " + uniqueInvalidChars.join(""));    }}document.getElementById("verifyBtn").onclick=function(e){e=e||window.event;e.preventDefault();var code=document.getElementById("codeTxt").value;verify(code,document.getElementById("result"));};
```

```
Enter your code snippet here:<br /><textarea id="codeTxt" rows="5" cols="70"></textarea><br /><button id="verifyBtn">Verify</button><br /><span id="result"></span>
```

# Answer
# CJam, ~~19~~ ~~18~~ ~~30~~ ~~34~~ ~~33~~ ~~19~~ ~~17~~ ~~21~~ 20 bytes

Try it online.

```
{_3\#,2>__ff*:~-<N*}

```

This is probably one of the most horribly inefficient algorithms I've ever implemented. But I did it for the size!

My answer consists of a code block, which acts like an anonymous function in CJam. Run it with an integer immediately preceding it on the stack, and the resulting list is dumped onto the stack. I treat the upper bound on the input as infinite so I don't have to check that bound.

My algorithm starts by raising 3 to the `input`th power, which is guaranteed to give a number larger than the `input`-th prime if the input is valid. Then a list of the integers from 2 to this number minus one is generated, which is a large enough swath to contain all the prime numbers we want. To get rid of the composite numbers... *sigh*... we create a list of every pairwise product, which should generate all composite numbers from 4 to some stupidly large value, large enough for our purposes. Then it's just a matter of removing every element from the original list that is in this composite list, trimming it down to the first `input` elements, and joining the elements with the newline character.

The algorithm *should* work for any input. However, whether or not the interpreter/computer has enough memory or time is a whole other question, because the time and space requirements are exponential with respect to the input. So if the input is larger than about 5 for the online interpreter or about 8 for the offline one, then the answer to that question is probably no.
> 10 votes

# Answer
# Python 3.7+, 183 bytes

```
for E,E.__clªss_ᵍᵉtitᵉᵐ__ in[__builtins__.__loªdᵉr__,ᵉxᵉc],:E[f'd{101:c}f F(n\x29:\n p,f\x3d1,1\n whil{101:c} n>0:p,f\x3d-~p,f*p*p\73n-\x3df{37:c}p>0!\x3dprint(p\x29']

```

Try it online!

Assumes an infinite upper bound, takes integer input via function argument, and prints the primes on separate lines.

Without substitutions for characters (except `\n`):

```
for E,E.__class_getitem__ in[__builtins__.__loader__,exec],:E[f'def F(n):\n p,f=1,1\n while n>0:p,f=-~p,f*p*p;n-=f%p>0!=print(p)']

```

The string in the above code:

```
def F(n):
 p,f=1,1
 while n>0:p,f=-~p,f*p*p;n-=f%p>0!=print(p)

```

Python 3.7 added the `__class_getitem__` magic method: if `A` is a class, then `A[x]` calls `A.__class_getitem__(x)`. Assigning `exec` to this attribute of a class allows us to call it without `)`. Unfortunately, we cannot create our own class without either using the `class` keyword (`a`) or calling the `type` function (`)`), so we must use a built-in class. The only one that allows the assignment to be made without error is `__builtins__.__loader__`.

Python normalizes all identifiers to NFKC, and this allows us to spell `__class_getitem__`, `__loader__`, and `exec` without using any of the letters `aegm`. The exact substitutions are U+00AA for `a`, U+1D49 for `e`, U+1D4D for `g`, and U+1D50 for `m`. We use a `for` loop to make assignments without using `=`, and these let us call `exec` via `E[f'...']` in the body.

Inside the string passed to `exec`, we use octal (`\73` instead of `;`), hex (`\x3d` instead of `=`), and decimal (`{37:c}` instead of `%`) escapes for banned characters. The code simply tests the primality of each positive integer using Wilson's theorem. A function was used instead of a lambda as the recursion limit causes the latter to stop working well below 10000.
> 15 votes

# Answer
# Java. 474 bytes

```
i\u006dport j\u0061v\u0061.util.*\u003bvoid b(int b\u0029{Lon\u0067 c\u003d2L,d,f[]\u003d{}\u003bfor(f\u003dArr\u0061ys.copy\u004ff(f,b\u0029,Arr\u0061ys.fill(f,0L\u0029\u003bb-->0\u003b\u0029for(d\u003d0L\u003bf[b]<1\u003bf[b]\u003dd<1?c:f[b],d\u003d0L,c\u002b\u002b\u0029for(lon\u0067 h:f\u0029d\u003dh>0&&c\u002fh*h\u003d\u003dc?1:d\u003bj\u0061v\u0061x.x\u006dl.bind.JAXB.un\u006d\u0061rsh\u0061l(""\u002bArr\u0061ys.\u0061sList(f\u0029,Lon\u0067.cl\u0061ss\u0029\u003b}

```

Takes input via function argument, outputs via thrown exception.

Indented:

```
i\u006dport j\u0061v\u0061.util.*\u003b
void b(int b\u0029{
    Lon\u0067 c\u003d2L,d,f[]\u003d{}\u003b
    for(f\u003dArr\u0061ys.copy\u004ff(f,b\u0029,Arr\u0061ys.fill(f,0L\u0029\u003bb-->0\u003b\u0029
        for(d\u003d0L\u003bf[b]<1\u003bf[b]\u003dd<1?c:f[b],d\u003d0L,c\u002b\u002b\u0029
            for(lon\u0067 h:f\u0029
                d\u003dh>0&&c\u002fh*h\u003d\u003dc?1:d\u003b
    j\u0061v\u0061x.x\u006dl.bind.JAXB.un\u006d\u0061rsh\u0061l(""\u002bArr\u0061ys.\u0061sList(f\u0029,Lon\u0067.cl\u0061ss\u0029\u003b
}

```

Escaped characters removed:

```
import java.util.*;
void b(int b){
    Long c=2L,d,f[]={};
    for(f=Arrays.copyOf(f,b),Arrays.fill(f,0L);b-->0;)
        for(d=0L;f[b]<1;f[b]=d<1?c:0,d=0L,c++)
            for(long h:f)
                d=h>0&&c/h*h==c?1:d;
    javax.xml.bind.JAXB.unmarshal(""+Arrays.asList(f),Long.class);
}

```

Explanation:

```
Long c,d,f[]={};                                                //Initialize variables.

for(f=java.util.Arrays.copyOf(f,b),Arrays.fill(f,0L);b-->0;)
    f=java.util.Arrays.copyOf(f,b),Arrays.fill(f,0L)            //Initialize f to an array of 0's.
                                                     b-->0      //Iterate over the first b primes.

for(d=0L;f[b]<1;f[b]=d<1?c:0,d=0L,c++)
    d=0L                        d=0L                            //Initialize d to 0.
         f[b]<1                      c++                        //Increment c while the b'th prime is 0.
                f[b]=d<1?c:0                                    //If d = 0, the b'th prime = c, else continue.

for(long h:f)                                                   //Iterate over all found primes.

d=h>0&&c/h*h==c?1:d;
  h>0                                                           //Ignore non-found primes.
       c/h*h==c                                                 //Equivalent to c%h==0
               ?1:d                                             //If h is prime and c is divisible by h, d = 1. Otherwise d stays unchanged.

javax.xml.bind.JAXB.unmarshal(""+Arrays.asList(f),Long.class)   //Print solution to stderr
javax.xml.bind.JAXB.unmarshal(                   ,Long.class)   //Prints what's contained to stderr.
                                 Arrays.asList(f)               //Convert f to list.
                              ""+                               //Convert to string.

```

My original solution used a `return` statement. After asking this question on StackOverflow, regettman was kind enough to provide a way to output/return without using prime letters.

As usual, suggestions are welcome :)
> 9 votes

# Answer
# Ruby, 74

```
->n,*o{o<<[2..n*n][0].find{|x|!o.find{|y|1.>x.^y.*x.div y}}until o[n-1]
o}

```

Explanation:

`*o` initializes an empty output array. until it has `n` items, we find the smallest number \>=2 that doesn't divide any item currently in `o`, then add it to `o`. To test for division, yikes. All the good operators are disallowed, and I can't even use `divmod`. Best I could see was to use `x.div y`, which takes x divided by y and rounds down, then multiply that by y again. If it equals x, there was no rounding, so y divides x. `1.>x.^` is an equality test, checking whether the result of xor is 0. The `.` before every operator is because you can't mix `.`-free operator calls and parenthesis-free method calls.

Edit: The range-checking specifications were added after I posted this, I think. To comply requires 79 characters:

```
->n,*o{o<<[*2..-~n*n].find{|x|!o.find{|y|1.>x.^y.*x.div y}}until o[n-1]||n<1
o}

```
> 6 votes

# Answer
# CJam, ~~38~~ ~~37~~ 30 bytes

```
{_~2#,2>\{(\{1$37c~},\p}*'<(~}

```

Try it here

I think this should comply with all the rules and works for any non-negative *N* (i.e. *T* is infinite). It's horribly inefficient though, so don't try it for large numbers.

This is a block - the closest thing to an (unnamed) function - which expects an integer on the stack, prints all the prime numbers and leaves the stack without its input. For all invalid inputs it will either throw an error or print nothing.

Most of the code is input validation, followed by the sieve of Eratosthenes. I only needed to work around the input restriction in 3 places:

* `)` is increment in CJam. I needed that once, but could replace it with `~` (bitwise complement) because I was squaring the numbers afterwards anyway.
* `%` is modulo. I'm using `37c~` instead, which first creates the character `%` and then eval's that. This makes the code a lot slower.
* `;` pops and discards an element from the stack. I need to do this at the end. Instead I'm using `'<(~` which pushes the character `<`, decrements it and eval's that.
> 4 votes

# Answer
# Bash + coreutils, 227 bytes

```
printf -vb br`dc<<<Di14B8209P`
printf -vc -- $[$1-0]
[ "${1#$c}" -o $c -lt 1 ]||{
for i in {2..104729}
{
for f in `jot $[i-1] $[i-1] 1`
{
[ 0 -lt `dc<<<"$i $f~p"` ]||$b
}
[ $f -lt 2 ]&&printf $i\ &&: $[c--]
[ $c -lt 1 ]&&$b
}
}

```

This was quite tricky. Some things I ran into:

* Most loops (`while` and `until`) are unusable because they most close with `done` which is a shell keyword and cannot be the result of a variable expansion (unless `eval` is used, but that is out too). The only usable loop is `for`/`in` which allows `{`/`}` instead of `do`/`done`. `for (( ; ; ))` is also not usable.
* `=` is out, so we need another way to assign variables. `printf -v` is good for this.
* We know that p(10000) is 104729 so for the outer loop for potential primes we can simply loop from 2 to 104729 and break once we have enough primes
* `jot` generates the list of potential factors in the inner loop. If a potential factor divides a potential prime, then it is not prime and we break out early
* Fortunately `break` is a shell builtin and not a keyword, so may be generated as a result of an expansion. `dc` converts a base 13 number to the bytestream `eak`.
* To check if a potential factor divides a potential prime, we cannot use the usual `/` or `%` shell arithmetic operators. So this is outsourced to `dc`s `~` operator, which pushes quotient and remainder to the stack.
* `-lt` \- less-than - is the only usable shell comparison operator.
* `echo` is no use for output. `printf` works though as long as we avoid `%`

Getting the input validation right is a bit of a pain. This returns nothing in the case of invalid input.

### Output:

```
$ ./primenoprime.sh 10
2 3 5 7 11 13 17 19 23 29 $

```
> 4 votes

# Answer
# Rust, 2720 1695 bytes

```
|n|for i in 0..n{if i<3&&i>1||i&1>0&&0<[0x2196820D864A4c32816D129A64B4cB6Eu128,0x4A2882D129861144A48961204A0434c9|1<<28,0x148A48844224064B0834992132424030|1<<80,0x64048928124108A00B40B4086c304204|1<<0|1<<84|1<<120,0xc02104c94112422180124496804c3098,0x220824B0826896810804490000982D32|1<<104,0x69009244304340069004264940A28948|1<<36,0x86122D22400c06012410DA408088210,0x14916022c044A0020110D301821B0484,0x4cA2100800422094092094D204A6400c|1<<84,0x34c108144309A24A48B081041018200|1<<28|1<<64,0x241140A2180032402084490880422402|1<<8|1<<20|1<<68,0x29260008360044120A41A00101840128|1<<72,0xc20c26484822006D10100480c0618283|1<<100,0x10c02402190024884420482024894810|1<<44|1<<7*8|1<<104,0x60901300264B0400802832cA01140868,0x430800112186430c32100100D0248082|1<<16,0x24880906002D20430092900c10480424,0x4000814196800880430082090932c040|1<<60,0x926094022080c3292048489608481048|1<<4*13,0xA04204901904004A0104422812000|1<<7*8,0x800084424002982c02c801348348924|1<<96,0x1864328244908A0004D0048442043698|1<<28|1<<112,0x861104309204A44028024001020A0090,0x4424990912486084c90804422c004208|1<<36,0x4040208804321A011000211403002400|1<<88,0xA2020c90116802186030014084c30906,0x8801904800841028224148929860004,0x120100100c061061020004A442681210,0x140128040A0c94186412422194032010|1<<7*8,0x4882402D20410490014000D040A40A29,0x822902002484490424080130100020c1|1<<76,0xA0cA0006112100104816814802486100|1<<20,0x2414480906810c044200B09104000240|1<<120,0x84420004802c10c860A00A011242092|1<<16|1<<112,0x12824414814804820022130406980032,0x2c00D86424812004D028804340101824,0x180110c04120cA41020000A241081209,0x48044320240A08320941220A41804A4,0x820104128864008A6086400c001800|1<<96][i>>8]&1<<{[i&{1<<8}-1][0]>>1}{print!{"{}
",i}}}

```

Try it online!

Lookup table generator

Yikes, I'm fairly confident rust doesn't even count as primitive recursive with the restrictions, because mutability and function calls are disallowed, meaning there is no way to maintain state across loop iterations. Works up to 10111.

My strategy was to form a lookup table by packing the primality of every odd number into array of 128 bit integers, and then just using a good old fashioned mask and shift to recover the value. The `5`s in the hexadecimal representation are dealt with by removing the 1 bit and orring it in at runtime. To deal with operator precedence issues, I abused the fact that blocks are also expressions, so I can use curly braces instead of parentheses.
> 4 votes

# Answer
# Haskell, 90 bytes

```
\n->[fst c|c<-zip[p|p<-[2..],not$or[b>p-1&&b-1<p|b<-[u*v|u<-[2..p-1],v<-[2..p-1]]]][1..n]]

```

This is an anonymous function which takes an integer `n` as input.

How it works: `[p|p<-[2..],not$or[b>p-1&&b-1<p|b<-[u*v|u<-[2..p-1],v<-[2..p-1]]]]` (first example of prime number one-liners at the Haskell wiki but with the `elem` function replaced) creates an infinite list of primes. `zip` it with the numbers from `1`to `n` to make a list of `(prime, seq. number)` pairs. Remove seq. number, again. Result is a list of primes of length `n`.
> 3 votes

# Answer
# Rust, 64897 bytes

```
|n|println!{"{:?}",&[2,3,6-1,7,11,13,17,19,23,29,31,37,41,43,47,60-7,0x3b,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,0x97,0x9d,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,0xfb,0x101 ...}

```

(code snipped due to character limit, full solution here)

The following rust features become unavailable due to the prime restriction:

* function calls, as they require ')'
* regular bindings, since they require let (e)
* macro definitions, they require macro-rules! (a,e,m)
* match statements, they require match (a,m) and =\> (=)
* mutability, since it's always introduced with the mut keyword (m).
* return (e), break (a,e), continue (e)
* else (e)

What you can technically use:

* if. But without else, they're useless in expression contexts, so only good for side effects.
* macros. Standard macros like print! are usually followed by (), but it's actually legal to use {} or \[\] instead. Without this, the task would be impossible.
* closures, in the most narrow sense. You can't call them (requires ()) or bind them(requires let), but you can define a single non-recursive one. Without this, the task would obviously become impossible.
* structs.
* for loops. These are promising, since they actually allow variable binding, and they take an iterator, which can still be defined with the range syntax. The iterator can even be an expression.
* Builtin operators, except +, % and /. The short-circuiting logical operators seem promising.

I simply couldn't make anything Turing-complete with these tools. I'm sorry. All that was left was to include the full first 10000 primes, cleaned of 5's. At least you can slice it and have a valid solution, in the most narrow sense possible.

I very much would like experts on Turing tarpit diving (or on Rust!) to tell me if I could have done anything better!
> 2 votes

# Answer
## GNU APL, ~~75 68 67 65 59 56~~ 55 characters

`⎕IO` must be `1`.

```
∇z←p n
z←2,j←3
j←j--2
→2×⍳∨⌿1>z|j
z←z,j
→2×⍳n>⍴z
z←n↑z∇

```

I came back on this months later realizing that I had an extra space!
> 1 votes

# Answer
# Jelly, 9 bytes

```
2ḍƇ`L<3Ʋ#

```

Try it online!

The character codes are `[50, 7693, 391, 96, 76, 60, 51, 434, 35]`

## How it works

```
2ḍƇ`L<3Ʋ# - Main link. Takes N on the left
       Ʋ  - Define a monad f(k):
  Ƈ       -   Filter the range [1, 2, ..., k] on the following:
 ḍ `      -     Divides k cleanly?
    L     -   Length
     <3   -   Less than 3?
2       # - Count up k = 2, 3, 4, ... until n integers return true.
            Return those integers

```
> 1 votes

# Answer
# JavaScript (V8), 131 bytes

```
[].fill.constructor`M${`for(N\x3D1\x3bM\x3bn-N||--M-print(n\x29\x29for(n\x3Di\x3DN-\x3D-1\x3bi-->2\x3b\x29n\x2fi-~~[n\x2fi]||n--`}`

```

Try it online!
> 1 votes

# Answer
# Pyth \- 12 bytes

Uses pyth's prime factorization function to see if # is prime. Uses `!tPT` trick suggested to me at my answer for primes under million problem.

```
<f!tPTr2^T6Q

```

Since the filter only works for primes under n and not first n, I just looked up the inverse of pi(x) for 10,000 and got 104,000 so I use primes under 10⁶ and get first n. This doesn't actually run, so you should test by replacing `^T6` with `^T3` and restrict n to under 1000. Input from stdin and output to stdout.

```
<          Q     Slice first n
f     r2^T6      filter on range 2->10⁶
 !               Logical not (gives true if tail is empty)
  t              Tail (all but first, so gives empty if prime fact is len 1)
   PT            Prime factorization of filter var (len 1 if num is prime)

```
> 0 votes

# Answer
# 05AB1E, 11 bytes

```
∞¦ʒDÑPQ}sôн

```

Input as integers.

Try it online or verify it's valid, and some test cases.

Or 14 bytes if we include string inputs, and comply to the other rules:

* Non-integer strings; leading whitespaces; or leading `+` are invalid
* Leading `0` are valid

```
∞ʒDÑPQ}s0ì>ôн¦

```

Try it online or verify it's valid, and some test cases.

**Explanation:**

```
∞        # Push an infinite positive list: [1,2,3,...]
 ¦       # Remove the leading 1: [2,3,4,...]
  ʒ      # Filter it by:
   D     #  Duplicate the current integer
    Ñ    #  Pop and push a list of its divisors
     P   #  Take the product of this list of divisors
      Q  #  Check if it's still the same as the duplicated integer
         #  (only if the divisors are {1,value}, the value will be a prime)
  }s     # After the filter: swap so the (implicit) input-integer is a the top
    ô    # Split the infinite list into parts of that size
     н   # Pop and leave just the first part

```

*For the program with additional string input validation:*

* The  will prepend a leading `"0"` to the input (to fix the test cases with leading `+`, which would otherwise be interpret as integers);
* The `>` will then increase the string-integer by 1 (implicitly converting it to an integer if it's valid first), because we haven't removed the leading `1` with `¦` yet;
* The `¦` will then:
    + Remove the leading `1` from the list for valid inputs;
    + Or remove the `1` from itself, leaving an empty string for invalid inputs. Because the `s0ì>ô` will have been no-ops, after which `н` will leave not the first part, but the first integer in the list, which is the `1`.

*Minor notes:*

1. Uses 05AB1E encoding, with the following codepoint-integers.
2. `ôн` could have been `£`, but unfortunately `£` with code-point 163 is a prime.
3. Even if prime-builtins were allowed, `Å` in the builtin `Åp` with code-point 197 is a prime as well. Although `<ÝØ` would in that case be a short 'valid' alternative: Try it online or verify it's 'valid', and some test cases.  pushes a list in the range `[0,input)`, whereas `Ø` converts each value in this list to their 0-based value'th prime.
> 0 votes

---
Tags: code-golf, restricted-source, primes
---


title: This will eventually stop…

text:
# Question
Title: This will eventually stop…
Given an input string `S`, print `S` followed by a non-empty separator in the following way:

* Step 1: `S` has a `1/2` chance of being printed, and a `1/2` chance for the program to terminate.
* Step 2: `S` has a `2/3` chance of being printed, and a `1/3` chance for the program to terminate.
* Step 3: `S` has a `3/4` chance of being printed, and a `1/4` chance for the program to terminate.
*
* Step `n`: `S` has a `n/(n+1)` chance of being printed, and a `1/(n+1)` chance for the program to terminate.

### Notes

* The input string will only consist of characters that are acceptable in your language's string type.
* Any non-empty separator can be used, as long as it is always the same. It is expected that the separator is printed after the last print of `S` before the program terminates.
* The program has a `1/2` chance of terminating before printing anything.
* A trailing new line is acceptable.
* Your answer must make a genuine attempt at respecting the probabilities described. Obviously, when `n` is big this will be less and less true. A proper explanation of how probabilities are computed in your answer (and why they respect the specs, disregarding pseudo-randomness and big numbers problems) is sufficient.

### Scoring

This is , so the shortest answer in bytes wins.

# Answer
> 18 votes
# Pyth, 7 bytes

```
WOh=hZQ

```

Try it online!

## How it works

Pseudocode:

```
while rand_int_below(1 + (Z += 1)):
    print(input)

```

# Answer
> 30 votes
# C#, 94 85 bytes

My first answer!

```
using System;s=>{var r=new Random();for(var i=2;r.Next(i++)>0;)Console.Write(s+" ");}

```

Previous attempt (I liked that `goto`):

```
using System;s=>{var i=2;var r=new Random();a:if(r.Next(i++)>0){Console.Write(s+" ");goto a;}}

```

Ungolfed:

```
using System;
class P
{
    static void Main()
    {
        Action<string> f = s =>
        {
            var r = new Random();
            for (var i = 2; r.Next(i++) > 0;) Console.Write(s + " ");
        };

        f("test");

        Console.ReadKey();
    }
}

```

Note: in C# the `Random.Next(N)` method returns a nonnegative integer in the \[0, N-1\] range, so we can just check that the number returned is greater than 0.

# Answer
> 12 votes
# R, ~~47~~ ~~46~~ 43 bytes

43 bytes due to Robin Ryder in the comments.

```
s=scan(,"")
while(sample(T<-T+1)-1)print(s)

```

Try it online!

### Explanation

```
s=scan(,"")  # Takes input from stdin.
             T<-T+1    # T is 1 by default, so this
                       # evaluates to 2, and will increment
                       # at each step.
      sample(T<-T+1)   # Take a sample of size 2, i.e. generate
                       # a list of integers from 1 to 2 in random order
      sample(T<-T+1)-1 # Subtract one from every element of this list.
while(sample(T<-T+1)-1)# while() will treat the first value in this list
                       # as a logical value, i.e. FALSE for zero and TRUE
                       # for nonzero values. The other elements of the list
                       # are ignored, triggering a warning.
                       print(s) # print s

```

# Answer
> 11 votes
# 05AB1E, 8 bytes

```
[NÌL.R#,

```

Try it online!

**Explanation**

```
[         # start loop
 NÌL      # push range [1 ... current_iteration+2]
    .R    # pick a random number
      #   # if true (1), exit loop
       ,  # print input

```

# Answer
> 11 votes
## Javascript, ~~60~~ ~~58~~ 54 bytes

```
f=(s,n=1)=>Math.random()<n/++n?console.log(s)+f(s,n):0

```

Will output string `s`. The seperator which is printed if the program terminates is `NaN` or `0`.

```
f=(s,n=1)=>Math.random()<n/++n?console.log(s)+f(s,n):0

f('test')
```

`Math.random()` returns a value between 0 and 1. If that value is under `n/(n+1)`, then `s` will be pritned.

4 bytes saved thanks to @Neil

# Answer
> 10 votes
# Java 8, ~~72~~ ~~62~~ 61 bytes

```
s->{for(int n=2;Math.random()<1f/n++;System.out.println(s));}

```

-10 bytes thanks to *@cliffroot*.
-1 byte thanks to *@JollyJoker*.

Delimiter is a new-line.

**Explanation:**

Try it here.

```
s->{                          // Method with String parameter and no return-type
  for(                        //  Loop
    int n=2;                  //   Start `n` on 2
    Math.random()<1f/n++;     //   Continue loop as long as a random decimal (0.0-1.0)
                              //   is smaller than 1/`n` (and increase `n` by 1 afterwards)
    System.out.println(s)     //   Print the input-String
  );                          //  End of loop
}                             // End of method

```

# Answer
> 9 votes
# Mathematica, 43 bytes

```
(n=1;While[RandomInteger@n>0,Print@#;n++])&

```

*JungHwan Min saved 1 byte (above) and suggested something better (below)*

# Mathematica, 37 bytes

```
For[n=1,RandomInteger@n++>0,Print@#]&

```

# Answer
> 8 votes
## Clojure, ~~61~~ 56 bytes

Oh why didn't I go with a `for` in the first place? But actually to be pedantic `doseq` has to be used as `for` is evaluated lazily.

```
#(doseq[n(range):while(>(rand-int(+ n 2))0)](println %))

```

Original:

```
#(loop[n 2](if(>(rand-int n)0)(do(println %)(recur(inc n)))))

```

# Answer
> 8 votes
## \>\<\>, ~~124~~ 112 bytes

```
i:0( ?v
 &5a ~/
&p0[^ >"\_\^x0!>"0&1+:&p1&:&p2&:&p3&:&p4&:&p0&1+:&p3&:&p4&:
=?v[/!}l]:?!;1
{:   ?^  >
:o>_ {:?!^

```

Try it online! (You can also watch it at the fish playground, but due to some bugs you have to add a `}` after the `l` in the fourth line and add a bunch of newlines after the code to make it work properly.)

Randomness is tricky in \>\<\>. The only random instruction is `x`, which picks the fish's direction randomly from four choices (left, right, up and down), so turning that into something with probability 1/*n* is not straightforward.

The way this code does it is by using \>\<\>'s self-modifying capabilities to build a Tower of Randomness below the code, so at the fourth stage, for example, the code looks like:

```
i:0( ?v
 &5a ~/
&p0[^ >"\_\^x0!>"0&1+:&p1&:&p2&:&p3&:&p4&:&p0&1+:&p3&:&p4&:
=?v[/!}l]:?!;1
{:   ?^  >
:o>_ {:?!^
>!0x^
\  _\
>!0x^
\  _\
>!0x^
\  _\
>!0x^
\  _\

```

The fish starts at the bottom of the tower. At each level of the tower, the `x` is trapped between two mirrors, so the fish can only escape by going left or right. Either of these directions sends the fish up to the next level of the tower, but going left also pushes a `0` to the stack. By the time the fish gets to the top of the tower, the stack contains some number of `0`s, and this number follows a binomial distribution with *n* trials and *p* = 1/2.

If the length of the stack is 0 (which has probability 1/2*n*), the program halts. If the length is 1 (with probability *n*/2*n*), the fish prints the input and a newline and builds another level of the tower. If the length is anything else, the fish discards the stack and goes back to the bottom of the tower. In effect, out of the possibilities that actually do something, *n* of them print the input string and one of them halts the program, giving the required probabilities.

# Answer
> 7 votes
# Python 3, 72 69 66 bytes

* Saved 3 bytes thanks to Jonathan Allan: Import shorthand and start count from 2.
* Saved 3 bytes thanks to L3viathan: Pointed randint() was inclusive and also shortened while condition.

```
from random import*
s=input();i=1
while randint(0,i):print(s);i+=1

```

Try it online!

# Answer
> 6 votes
# QBIC, ~~19~~ 17 bytes

*Dropped `=1`, switched conditionals, saved 2 bytes*

```
{p=p+1~_rp||?;\_X

```

## Explanation

```
{       Infinitely DO
p=p+1   Add 1 to p (p starts as 0, so on first loop is set to 1, then 2 etc...)
~       IF
  _rp|| a random number between 0 and p
        (implicitly: is anything but 0)
?;      THEN print A$ (which gets read from the cmd line)
\_X     ELSE QUIT
        END IF and LOOP are auto-added at EOF

```

# Answer
> 6 votes
# Braingolf, 23 bytes

```
#|V12[R!&@v!r?<1+>1+]|;

```

Try it online!

Generates random number `x` where `0 <= x < n+1`, terminates if `x` is 0, otherwise increments `n` and loops. Separator is `|`

## Explanation:

```
#|V12[R!&@v!r?<1+>1+]|;  Implicit input of commandline args to stack
#|                       Push |
  V                      Create stack2 and switch to it
   12                    Push 1, then 2
     [..............]    Do-While loop, will run indefinitely unless conditional skips
                         Closing bracket
      R                  Return to stack1
       !&@               Print entire stack without popping
          v              Switch to stack2
           !r            Generate random number 0 <= x < n where n is last item on stack
             ?           If last item is greater than 0..
              <          ..Move first item to end of stack
               1+        ..and increment, this is the loop counter number
                 >       ..Move back
                  1+     ..and increment, this is the upper range of the RNG
                    ]    ..end loop
                     |   Endif
                      ;  Suppress implicit output

```

# Answer
> 6 votes
## Alice, 18 bytes

```
/?!\v
\iO/>]qhUn$@

```

Try it online!

### Explanation

```
/     Reflect to SE. Switch to Ordinal.
i     Read all input as a string and push it to the stack.
!     Store the string on the tape.
/     Reflect to E. Switch to Cardinal.
>     Ensure that the IP moves east. This begins the main loop.

  ]   Move the tape head to the right. We'll be using the tape head's
      position as a counter variable. Note that this tape head is independent
      of the one used in Ordinal mode to point at the input string.
  q   Push the tape head's position to the stack.
  h   Increment it (so that it's 2 initially).
  U   Get a uniformly random number in [0,n).
  n   Logical NOT. Gives 1 with probability 1/n and 0 otherwise.
  $@  Terminate the program if we got a  1.
  \   Reflect to NE. Switch to Ordinal.
  ?   Retrieve the input from the tape.
  O   Print it with a trailing linefeed.
  \   Reflect to E. Switch to Cardinal.

v     Send the IP south where it runs into the > to start the next
      loop iteration.

```

# Answer
> 6 votes
# PHP, 31 bytes

```
for(;rand()%~++$c;)echo$argn._;

```

Try it online!

# Answer
> 6 votes
## Perl, 26 bytes

**24 bytes code + 2 for `-nl`.**

```
print while rand++$i+1|0

```

Try it online!

# Answer
> 3 votes
# Charcoal, 14 bytes

```
Ａ²γＷ‽γ«θ_Ａ⁺γ¹γ

```

Try it online! Link is to verbose version of code. Uses `_` as the separator. Note: output caching is disabled, so please don't hammer Dennis's server!

# Answer
> 3 votes
# MATL, 9 bytes

```
`G@QYrq]x

```

Try it online!

### Explanation

```
`        % Do...while
  G      %   Push input
  @      %   Push iteration index k, starting at 1
  QYrq   %   Random integer uniformly distributed in {0, 1, ..., k}. This is the
         %   loop condition. If non-zero (which occurs with probability k/(1+k))
         %   proceed with next iteration; else exit loop
]        % End
x        % Delete, as there are one too many strings. Implicitly display the stack

```

# Answer
> 3 votes
# Perl 6,  ~~50 41 38 36~~  26 bytes

```
{put $_//last for (($,$_),*⊎$_...*).map(*.pick)}

```

Try it

```
{eager ->{(++$).rand>.5??.put!!last}...*}

```

Try it

```
{eager ->{(++$).rand>.5??.put!!0}...0}

```

Try it

```
{eager ->{(++$).rand>.5&&.put}...!*}

```

Try it

```
.put while (++$/).rand>.5

```

(with `-n` commandline argument)

Try it

# Answer
> 3 votes
## Python 3, 55 bytes

```
v=s=input();i=2
while hash(v)%i:print(s);i+=1;v=hash(v)

```

## Explanation

To save having to import random, I've exploited the fact that the hash built-in is randomly seeded each time a python process is fired up (at least in MacOS). Each hash of the last hash should generate a series of pseudo-random integers.

If the hash is pseudo-random enough, the modulo with `i` is zero with probability `1/i`.

## Notes

I'm a little bothered by the redundant hash, but without a do-while, or in-condition assignment in Python, I'm a little stuck.

# Answer
> 3 votes
# C#

This is same length as the top C# answer, but:

```
using System;s=>{var x=(1<<31)/new Random().Next();for(;++x>0;)Console.Write(s+" ");}

```

Just wanted to point out that some math can produce the correct probability.

```
int.MaxValue/new Random().Next()-1

```

Is equivalent to

```
(int)(1 / new Random().NextDouble()) - 1;

```

And the function f(x)=1/x-1 is:

f(1) = 0

f(1/2) = 1

f(1/3) = 2

f(1/4) = 3

So 1/2 a chance to be rounded down to 0, 1/6 a chance to be rounded down to 1, and 1/(n+1)(n+2) a chance to be rounded down to n.

Maybe some other language could capitalize on this.

EDIT: Fixed my mistake

I thought of something to make it smaller.

EDIT EDIT: I am just all kinds of wrong. Pulled the Random out of the loop because if it's evaluated multiple times, it won't work.

EDIT EDIT EDIT: I got rid of the variable i. I'm going to stop trying to shrink it now. Nope, lied. Got rid of another byte.

# Answer
> 3 votes
# Vyxal `ROM`, 7 bytes

```
{&›¥℅|,

```

Try it Online!

Explanation:

```
{    |   # While...
 &›      # ...Increment the register (initially 0)...
   ¥     # ...Retrieve value n from the register...
    ℅    # ...Random value from range[0..n]...
     |   # ...Returns true, do:
      ,  #   Print the input string

```

# Answer
> 2 votes
# Charcoal, 17 bytes

```
ＳαＡ²βＷ‽β«⁺α¶Ａ⁺β¹β

```

Try it online! Verbose code included. Respects specs because it uses a random range from `0` to `n`.

# Answer
> 2 votes
# C++, 97 96 57 bytes

Here my first try on codegolf :)

```
#include<iostream>
int main(){std::string S;std::cin>>S;int i=1;while(rand()%++i)puts(S.data());}

```

I saved one byte by using `for`

```
#include<iostream>
int main(){std::string S;std::cin>>S;for(int i=1;rand()%++i;)puts(S.data());}

```

Saved 39 bytes since nobody seems to count the includes

```
void p(string S){for(int i=1;rand()%++i;)puts(S.data());}

```

ungolfed

```
#include <iostream>
int main()
{
  // Create and read string from inputstream
  std::string S;
  std::cin >> S;

  // rand % i: create random int in range [0, i-1]
  // Zero is seen as false and all positive int as true
  int i = 1;
  while (rand() % ++i)
    puts(S.data());
}

```

# Answer
> 2 votes
# braingasm, 22 bytes

edit: Same byte count, but I realized I could sneak in the new tape `L`imit feature.

```
,[>,]>L+[+$rzQ>[.>]:>]

```

Uses `0` as separator. Works like this:

```
,[>,]                   Read a byte and move to next cell until end of input.
     >                  After the loop we're in an empty cell;
                          Leave it empty and move to the next.
      L                 Set tape limit here:
                          The tape will then wrap around if we move further.
       +                Increase current cell by one.
                          This cell will be our counter.
        [            ]  Loop until the counter is zero.
                          That won't happen, so it's an infinite loop.
         +              Increase again, so the first time the counter is 2.
          $r            Get a random number, 0 <= r > current cell
            zQ          Quit the program if that random number was 0
              >         Wrap around to the start of the tape.
               [.>]     Print the input stored on the tape
                          The loop will stop at the blank cell.
                   :    Print the blank cell as a number ("0")
                    >   Go to the next (last) cell

```

# Answer
> 2 votes
# C, 41 bytes

```
n;f(char*s){for(n=1;rand()%++n;puts(s));}

```

Assumes `rand` is seeded. Try it online!

# Answer
> 2 votes
# Python, 54 bytes

```
lambda s:int(1/random()-1)*(s+'|')
from random import*

```

Try it online!

Generated the number of copies as `floor(1/p)-1` with `p` uniformly chosen from the unit interval. The number of copies is `n` when `1/p-1` falls between `n` and `n+1`, which happens when `1/(n+2) < p < 1/(n+1)`. This happens with probability `1/(n+1)-1/(n+2)` or `1/((n+1)*(n+2)`. This is the desired probability of outputting `n` copies: `1/2` prob of 0, `1/6` prob of 1, `1/12` prob of 2,...

# Answer
> 2 votes
# F#, 161 bytes

Definitely not the best language to golf, but I decided to give it a try (besides, I do not know anything about F#, so any tips on how to improve my answer will be welcome).

```
let f s=
 let r,z=System.Random(),(<>)0
 let p _=printfn"%s"s
 seq {for i in 2|>Seq.unfold(fun i->Some(i,i+1))do yield r.Next(i)}|>Seq.takeWhile z|>Seq.iter p

```

Execute with:

```
[<EntryPoint>]
let main argv =
    "test" |> f
    0

```

Writes a new line as separator.

# Answer
> 2 votes
# Ruby, 29+1 = 30 bytes

Uses the `-n` flag.

```
i=1;puts$_ while i>rand(i+=1)

```

Try it online!

# Answer
> 2 votes
## PowerShell, 31 bytes

```
for($i=2;random($i++)){"$args"}

```

`Get-Random $i` outputs an `n` where `0 <= n < $i`, separator is implicit newline.

# Answer
> 1 votes
# Python, 75 bytes

The other Python answer is shorter, but I wanted to try it a different way:

```
from random import*
f=lambda d=1,s=input():randint(0,d)and s+'!'+f(d+1)or''

```

# Answer
> 1 votes
# Dart - 73 chars

`import"dart:math";p(s,{i=2}){while(new Random().nextInt(i++)>0)print(s);}`

This function implements the algorithm by taking a string as input and printing it as necessary. The separator is obviously newline. To run it, you need a main method like `main(){p("foo");}`.

It's hard to be small when you need to import the math library and instantiate the `Random` class.

Try it online

# Answer
> 1 votes
# APL (Dyalog), 17 bytes

Requires `⎕IO←0` which is default on many systems.

```
{⎕←⍺⋄×?⍵:⍺∇1+⍵}∘2

```

This is a monadic function derived from a dyadic function by currying the right argument.

`{` anonymous function

`⎕←⍺` print ⍺ (the string)

`⋄` then

`×?⍵:` if the signum of a random int in the range \[0,-1\] is 1, then:

`⍺ ∇ 1+⍵` recurse with 1+ as new right argument

(implicit, else: stop)

`}∘2` with 2 as bound right argument

Try it online! Sets `⎕RL←0` (**R**andom **L**ink) to avoid TIO's regeneration of the same random number.)

# Answer
> 1 votes
# C# 79 bytes

does a divide by 0 error count as terminating?

```
using System;s=>{for(int i=1;2>1/new Random().Next(++i);Console.Write(s+' '));}

```

# Answer
> 1 votes
## Scala ~~76~~ ~~72~~ 71 Bytes

```
def w[T](s:T)={var x=2;while(Random.nextFloat>1f/x){x+=1;print(s+" ")}

```

This uses a template because it works fine for strings, and saves a character. Other than that, it's a pretty basic implementation. Scala picks up a couple bytes by not having a proper++ operator. Random.nextFloat returns a random value between 0 and 1, and 1f/x forces float division. This implementation uses a space as a separator, with no trailing newline.

# Answer
> 1 votes
# Lua, ~~50~~ 46 bytes

```
i=2while 1<math.random(i)do i=i+1print(...)end

```

Assumes that it is already seeded

Try it online!

# Answer
> 1 votes
# JS (ES6), 47 bytes

```
x=>{for(i=1;Math.random()<i/(i+1);i++)alert(x)}

```

Unlike the other ES6 answer, this uses a for loop and alert bombs instead of recursion. The seperator that is printed when the program stops is undefined.

# Answer
> 1 votes
# k, 20 bytes

```
`0:((*1?2+)(1+)/0)#,

```

Explanation:

```
`0:((*1?2+)(1+)/0)#,
                0    /set x to 0
           (1+)      /add 1 to x...
    (*1?2+)    /     /...while randint [0,2+x) is > 0
   (             )#, /make array with that many copies of the string
`0:                  /output array line by line

```

Probabilities:

```
 5#{(((#:'=x{(*1?2+)(1+)/0}\0)@!x))%x}2000000      /experimental
0.5001625 0.1667005 0.083024   0.050034 0.0333645
 {(1%x)*-1_1.,*\{(x-1)%x}x}2+!5                    /calculated
0.5       0.1666667 0.08333333 0.05     0.03333333

```

# Answer
> 1 votes
# Forth (gforth), 71 bytes

```
include random.fs
: f 1 1 do i 1+ random i = ?leave 2dup type cr loop ;

```

Try it online!

Technically will end after the \[maximum single-cell number\]th iteration, but the chance of that happening is at least 2-64 on most systems (and likely 2-32 on others)

### Code Explanation

```
include random.fs  \ load the random library to generate random numbers

: f                \ start a new word definition
  1 1 do           \ loop from 1 to 0 (start at 1 stop when we reach 0 via integer overflow)
    i 1+ random    \ get a random integer from 0 to n
    i =            \ check if the value equals n
    ?leave         \ end the loop if true
    2dup type cr   \ otherwise, print the input string followed by newline
  loop             \ go back to beginning of loop
;                  \ end the word definition

```

# Answer
> 1 votes
# Thunno 2, 7 bytes

```
(ṅƙɼḅ;£

```

Attempt This Online!

#### Explanation

```
(ṅƙɼḅ;£  # Implicit input
(        # while
 ṅ       # (condition)  0-based iteration index
  ƙ      #              increment twice
   ɼ     #              random item from [1..that]
    ḅ    #              equals one?
     ;£  # (body)  print input string with newline
         # Implicit output

```

# Answer
> 1 votes
# Trilangle, 104 bytes

```
'0.<_.<.>i.S)#..\_/.L',z$)<.Se(*8'.3....LS:.)~<#+7....@..^.-/...,>j))2<.L,z,<......><#(,.#o.....\",o,../

```

Try it on the online interpreter!

The random number instruction `$` creates a random number along the whole range of integers. This program uses the sign of \\$\left|rand\left(\right)\right|+\frac{INT\\\_MIN}{i+1}\\$ to determine whether to terminate.

I don't currently have the ability to create the colorized drawing I normally do, but here's an annotated disassembly. I created this first, then wrote the program, and then tweaked this to match the output of the disassembler.

```
; Get the string and its length. Pretty standard.
    PSI #0
input_loop: ; 0.2
    GTC
    BNG input_cleanup
    SWP
    INC
    JMP input_loop
input_cleanup: ; 2.0
; Put the iteration number on top of the stack. Rather than popping the -1 to
; push 0, just increment it.
    INC
; These swaps happened to be here, and they don't do anything
    SWP
    SWP
; Increment the iteration number and check whether to terminate
check_term: ; 2.10
    INC
    RND
; RND gives a number in [-0x800000, 0x7fffff].
; Terminate with probability 1/(i+1).
    DP2
    POP
; Get INT_MIN as 2^23. This overflows and becomes a negative number.
    PSI #3
    PSI #8
    MUL
    DEC
    EXP
; then do the division and compare
    SWP
    INC
    DIV
    SWP
    BNG rand_neg
; Stack: [...s, s.length, i, INT_MIN/(i+1), rand]
; Terminate when rand + INT_MIN/(i+1) < 0
    ADD
compare: ; 3.2
; Flip the sign, then end when it's positive instead of negative. It turned out
; to save room to make the positive branch terminate.
    NOT
    BNG print_begin
    JMP end ; disassembler quirk ¯\_(ツ)_/¯
rand_neg: ; 4.0
; Stack: [...s, s.length, i, INT_MIN/(i+1), rand]
; Terminate when INT_MIN/(i+1) - rand < 0
    SUB
    JMP compare
end: ; 5.0
    EXT
print_begin: ; 6.0
    POP
; Print the string.
; DP2 + POP is shorter than PSI #1 + IDX
    DP2
    POP
print_loop: ; 6.6
    BNG print_done
    DUP
; INC + INC is shorter than PSI #2 + ADD
    INC
    INC
    IDX
    PTC
    POP
    DEC
    JMP print_loop
; Print a separator, then loop back.
print_done: ; 8.0
    PSC ','
    PTC
    POP
    POP
    JMP check_term

```

I have a feeling that this can be shrunk, as there's a significant amount of unused space, but I haven't figured anything out yet.

# Answer
> 1 votes
# JavaScript (Node.js), 40 bytes

```
x=>Array(0|.5/Math.random()).fill(x)+','

```

Try it online!

Act same

# Answer
> 0 votes
# Bash, ~~71~~ 59 bytes

```
i=1;while((0<`shuf -i0-$i -n1`));do echo $1;i=$((i++));done

```

Try it online!

While is a better tool for this job

# Answer
> 0 votes
# TI-BASIC, ~~24~~ 22 bytes

-2 thanks to @lirtosiast

```
:Prompt Str1           //4 bytes
:While randInt(0,Ans+1 //9 bytes
:Disp Str1             //4 bytes
:Ans+1                 //4 bytes
:End                   //1 byte

```

Since all non-zero values are truthy, taking a random integer in between `0` and `n-1` will give a random boolean with the correct probability.

# Answer
> 0 votes
# Runic Enchantments, 20 bytes

```
i0q11+:'RA0=?;S:$S4?

```

Try it online!

Note that input is implicitly split on whitespace characters, so they need to be escaped.

### Explanation

```
>                        Implicit entry
 i0q1                    Read input and set up stack
     1+                  Increment counter (value needs to be 2 for first loop)
       :'RA0=            Generate random value (non destructive to stack) and compare with 0
             ?;          If *not* 0, terminate
               S:$S      Otherwise duplicate and print string
                   4?    Skip next 4 instructions (implicit loop)

```

Newline variant, as printing a whitespace character as a separator costs an extra byte.

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


title: As programmers say: Strive to be lazy

text:
# Question
Title: As programmers say: Strive to be lazy
## Story

Have you seen this post from 9gag? Maybe you got the feeling to make your own sentences. But then you realize that you could just golf a script in half an hour, and you will never have to deal time with that.

## The submission

Your program will get an input string which it will return with added quotation marks as explained below. Standard loopholes are forbidden. Output as a list of lines is allowed. Trailing spaces and empty lines that don't break the output are allowed.

## The rules of input

* The input only contains printable ASCII characters.
* The input may contain spaces. The words are determined with them.
* It's guaranteed that a space will never be followed by another space.
* The case of no input or empty string doesn't matter.

## The rules of output

If one word is given then the program has to return the string between quotation marks.

If the input string has 2 or more words, it first returns the initial input, but the first word is in quotation marks. Then on the next line, it returns the initial input, but with the second word in quotes. And so on for the remaining words.

In general, the program has to return as many lines as there are words in the input.

## Examples:

```
test -> "test"

This is codegolf -> "This" is codegolf
                    This "is" codegolf
                    This is "codegolf"

This is a significantly longer, but not the longest testcase -> "This" is a significantly longer, but not the longest testcase
                                                                This "is" a significantly longer, but not the longest testcase
                                                                This is "a" significantly longer, but not the longest testcase
                                                                This is a "significantly" longer, but not the longest testcase
                                                                This is a significantly "longer," but not the longest testcase
                                                                This is a significantly longer, "but" not the longest testcase
                                                                This is a significantly longer, but "not" the longest testcase
                                                                This is a significantly longer, but not "the" longest testcase
                                                                This is a significantly longer, but not the "longest" testcase
                                                                This is a significantly longer, but not the longest "testcase"

Here is an another one -> "Here" is an another one
                          Here "is" an another one
                          Here is "an" another one
                          Here is an "another" one
                          Here is an another "one"

```

This is , so the least byte answer wins!

# Answer
## vim, 38 bytes

```
:s/"/<C-d>/g
qqysW"Ypds"W@qq@qdk:%s/<C-d>/"/g

```

Try it online!

Requires the vim-surround plugin.

If the input does not contain `"` characters, this can be done in **19 bytes**:

```
qqysW"Ypds"W@qq@qdk

```

Here, we record a recursive macro (`qq ... @qq@q`) that surrounds a word with quotation marks (`ysW"`), duplicates the line (`Yp`), deletes the quotation marks (`ds"`), and moves to the next word (`W`) before calling itself recursively. After it terminates, there are two extraneous lines, which are deleted with `dk`.

The full solution simply wraps this with `:s/"/<C-d>/g` at the beginning, which replaces existing `"` characters with an unprintable character, and `:%s/<C-d>/"/g` at the end, which undoes the replacement.
> 10 votes

# Answer
## Haskell, 65 bytes

```
([]#).words
a#(b:c)=unwords(a++('"':b++"\""):c):(a++[b])#c
_#_=[]

```

Returns a list of lines.

Try it online!
> 8 votes

# Answer
# Jelly,  ~~15~~  14 bytes

```
Ḳ⁾""j$€⁹¦K¥ⱮJ$

```

**Try it online!**

### How?

```
Ḳ⁾""j$€⁹¦K¥ⱮJ$ - Link: list of characters, S
Ḳ              - split (S) at spaces -> A
             $ - last two links as a monad:
           Ɱ   -   map...
            J  -   ...across: range of length -> I = [1,2,...len(A)]
          ¥    -   ...doing: last two links as a dyad: i.e. f(A, i) for i in I
      € ¦      -     sparse application...
       ⁹       -     ...to indices: chain's right argument, i
     $         -     ...action: last two links as a monad:
 ⁾""           -       literal list of characters = ['"', '"']
    j          -       join (with A[i]) -> (e.g. with ['i','s']) ['"','i','s','"']
         K     -     join with spaces

```
> 8 votes

# Answer
# Retina 0.8.2, 17 bytes

```

" $'¶$` "
^|$
"

```

Try it online! Link includes test suite. Explanation:

```

" $'¶$` "

```

Expand each space by duplicating the line and then inserting quotation marks.

```
^|$
"

```

Fix the first and last lines.
> 7 votes

# Answer
# JavaScript (ES6),  ~~43 42 41~~  38 bytes

*Saved 3 bytes thanks to @mazzy*

Uses the non-standard but widely supported `RegExp.leftContext` and `RegExp.rightContext`. That's a lot of different quotes...

```
s=>s.replace(/(\S+) ?/g,`$\`"$1" $'
`)

```

Try it online!
> 7 votes

# Answer
# Java, ~~235 183~~ 132 bytes

```
s->{String a[]=s.split(" "),r="",t;for(int l=a.length,i=0,j;i<l;i++,r+="\n")for(j=0;j<l;)r+=(t=i==j?"\"":"")+a[j++]+t+" ";return r;}

```

-52 bytes by abusing a variety of things (static access, list vs array, print instead of returning, etc. Thanks @ValueInk!)
-51 bytes by beung lazy and letting @KevinCruijssen do the work for me
Try it online
> 6 votes

# Answer
# Ruby with `-an`, 53 bytes

The flags `-an` are read each line and split to `$F`.

```
$F.size.times{|i|a=$F.dup;a[i]=?"+a[i]+?";puts a*' '}

```

Try it online!
> 5 votes

# Answer
First code golf attempt hopefully it's not terrible and hopefully it's not rule breaking

## Kotlin, ~~105~~ ~~112~~ ~~147~~ 117 bytes/chars

```
fun main(a:Array<String>){val q=a[0].split(" ")
q.forEach{println(q.fold(""){i,n->i+if(it==n)"\"$n\" " else n+" "})}}

```

Try it online!
> 5 votes

# Answer
# 05AB1E, 14 bytes

```
ð¡©ε®y…"ÿ"Nǝ}»

```

Try it online!

---

+1 byte (and it works for the edge case) thanks to Emigna. -1 byte thanks to Kevin!
> 4 votes

# Answer
## JavaScript, ~~91~~ ~~97~~ ~~75~~ 78 bytes

```
f=

t=>t.split` `.map((c,i,a)=>[...a.slice(0,i),`"${c}"`,...a.slice(i+1)].join` `)

// and test
console.log(f("Hello folks and world").join('\n'));
```

Outputs a list of lines as a JavaScript array. The last entry has a trailing space as allowed in the question. The test code writes each entry to the console on a separate line for demonstration purposes.

Thanks to Shaggy for 19 bytes off and no leading spaces - when the spread operator is used on an empty array to initialize an array literal, no slots are created in the array produced by the spread operator:

```
let empty = [];
let array = [...empty, value]
//  produces an array of length 1 containing value

```

<sub>(The 91 byte version had a leading space on the first line, the 97 byte version took 6 bytes to remove it.)</sub>
> 4 votes

# Answer
# Python 3, 79, 69, 65 bytes

```
w,i=input(),0
while~i:m=w.split();m[i]='"%s"'%m[i];print(*m);i+=1

```

Try it online!

Shaved 10 bytes thanks to xnor. And now this is 65 bytes as per Erik the Outgolfer solution. Program ends with IndexError but this is fine.
> 4 votes

# Answer
# Java 8, ~~72~~ ~~71~~ ~~67~~ 62 bytes

```
s->s.replaceAll("(?<=(^.*))(\\S+) ?(?=(.*$))","$1\"$2\" $3\n")

```

Try it online.

**Explanation:**

```
s->                    // Method with String as both parameter and return-type
  s.replaceAll("...",  //  Replace all matches in this regex
               "...")  //  With this
                       //  And then return the result

```

*Regex explanation:*

```
(?<=(^.*))(\\S+) ?(?=(.*$))   # === MATCH ===
(?<=     )                    # A positive look-behind to:
     ^.*                      #  The optional leading portion of the string
    (   )                     #  (which is captured in capture group 1)
           \\S+               # Followed by one or more non-space characters,
                              # so the next word in line
          (    )              # (which is captured in capture group 2)
                 ?            # Followed by an optional space
                  (?=     )   # Followed by a positive look-ahead to:
                      .*$     #  The trailing optional portion of the string
                     (   )    #  (which is captured in capture group 3)

$1\"$2\" $3\n                 # === REPLACEMENT ===
$1                            # The match of capture group 1
                              # (the leading portion)
    $2                        # Followed by the match of capture group 2
                              # (the current word in the 'iteration'),
  \"  \"                      # surrounded by quotation marks
                              # Followed by a space character
         $3                   # Followed by the match of capture group 3
                              # (the trailing portion)
           \n                 # Followed by a trailing newline

```
> 4 votes

# Answer
# Ruby, 98 chars.

First submission ever. This can definitely be shortened. I just wanted to get an answer in quickly.

```
a=->s{s.split.each_index{|i|puts s.split.each_with_index.map{|a,j|i==j ? "\"#{a}\"":a}.join(" ")}}

```

Try it online!
> 3 votes

# Answer
# Haskell, 64 bytes

```
map unwords.g.words
g(h:t)=(('"':h++"\""):t):map(h:)(g t)
g _=[]

```

Try it online!

Outputs a list of strings. Based on nimi's answer.
> 3 votes

# Answer
# Perl 6, ~~43~~ 40 bytes

```
{m:ex/^(.*?<<)(\S+)(>>.*)$/>>.join('"')}

```

Try it online!

Matches all possible words, then joins each list by quotes. This could be one byte shorter if we could output lines in reverse order.

### Explanation:

```
{                                      }  # Anonymous code block
 m:ex/^                  $/               # Match all strings
       (.*?)         (.*)                 # Match before and after sections
            <<(\S+)>>                     # And the actual word (with no spaces)
                           >>.join('"')   # And join each line by "s

```
> 3 votes

# Answer
## Reflections, 229 bytes

```
  _1 +\ /\/(3\  /(0\
/+_:   # \#_: v1=2#_ \
\     /_+/:3; / 1/\:1)
/v(3(2/ \3)(3 ;\#@ \ /
   /:#_(0\:_ / (0*  /0  \
 0 >~    <>~   <0 \  *#_/
 \       /     /\/ v/
   \=2#_1/\2#_>  (0~
                 \ ^\
\                   /

```

Test it!

I "quickly" "golfed" this in a "funny" "golfing" language.

Looking at all that whitespace, it could probably be shorter.
> 3 votes

# Answer
# , ~~94~~ 76 bytes

-18 bytes thanks to Giuseppe

```
m=matrix(s<-scan(,a<-'"'),n<-length(s),n);diag(m)=paste0(a,s,a);write(m,1,n)

```

Try it online!

Thanks to digEmAll for setting up the TIO properly. It takes in e.g. `This is codegolf` and outputs correctly

```
"This" is codegolf
 This "is" codegolf
 This is "codegolf"

```

It uses a matrix format with the sentence repeated `n` times; then we only need to change the diagonal entries. Note that usually, in R code-golf, strings are read in with `scan(,"")`, but any string can be used instead of the empty string as the `what` (or `w`) parameter.

Explanation of old ungolfed version:

```
s <- scan(t=scan(,''),w=t)    # read in input and separate by spaces
n <- length(s)                # number of words
m = matrix(s, n, n)           # fill a matrix, one word per entry, each column corresponds to the whole sentence. The sentence is repeated n times.
diag(m) = paste0('"', s, '"') # replace diagonal entries with the corresponding word surrounded by quotes
cat(rbind(m,"\n"))        # add a \n at the end of each column, then print column-wise

```
> 2 votes

# Answer
# Stax, 10 bytes

```
▓¼MY@≈╢∞◙╗

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
jY      split on spaces and store in y register
m       for each word, run the rest of the program and implicitly output
  '"|S  surround with double quotes
  yia&  start with register y, and replace the ith element, where i is the iteration index
  J     join with spaces

```

Run this one
> 2 votes

# Answer
# JavaScript, 62 bytes

Thanks @Shaggy for golfing off 10 bytes

```
f=
x=>x.split` `.map((c,i,a)=>(s=[...a],s[i]=`"${c}"`,s.join` `))

console.log(f("Hello folks and world").join('\n'));
```

### Explanation

* The function splits the string at each space (x.split\` \`)
* For each element in the resulting array perform the following function
* Create a shallow copy of the array (s=\[...a\])
* Replace the nth element in the array with itself surrounded with quotation marks (s\[i\]=\`"${c}"\`)
* return the shallow copy joined with spaces (s.join\` \`)
> 2 votes

# Answer
This is my first code golf. hopefully its not shit.

**EDIT: got it down to 54 bytes with a better regular expression.**

\**EDIT 2: per suggestions, fixed a bug and made it shorter \**

# JavaScript (V8), 46 bytes

```
t=>t.split(' ').map(v=>t.replace(v,'"'+v+'"'))

```

Try it online!
> 2 votes

# Answer
# C (gcc), 136 133 bytes

As C's tokenizing functions would mess up the string on future reads, I instead calculate the number and offsets for each word and then finish when the total number of iterations of the outer loop matches the number of words.

```
i,j=1;f(s,c,t)char*s,*c,*t;{for(i=0;i++<j;puts(""))for(j=0,c=t=s;t;t=c+!!c)printf("%3$s%.*s%s ",(c=index(t,32))-t,t,"\""+!!(i-++j));}

```

Try it online!
> 2 votes

# Answer
# PowerShell, ~~60~~ ~~40~~ 36 bytes

*-20 bytes inspired by Arnauld*

```
$args-replace'(\S+) ?','$`"$1" $''
'

```

Try it online!

The result has one extra space and one empty line in the tail.

---

# Powershell, no regexp, 60 bytes

```
($w=-split$args)|%{$p=++$c
"$($w|%{$q='"'*!--$p
"$q$_$q"})"}

```

Try it online!

Less golfed:

```
$words=-split $args                     # split by whitespaces
$words|%{
    $position=++$counter
    $array=$words|%{
        $quotation='"'*!--$position     # empty string or quotation char
        "$quotation$_$quotation"
    }
    "$($array)"                         # equivalent to $array-join' '
}

```
> 2 votes

# Answer
# Japt, ~~14~~ 12 bytes

```
¸£¸hYQ²i1X)¸

```

Try it

2 bytes saved thanks to Oliver.

```
¸£¸hYQ²i1X)¸     :Implicit input of string
¸                :Split on spaces
 £               :Map each X at index Y
  ¸              :  Split input on spaces
   hY            :  Set the element at index Y to
     Q           :    Quotation mark
      ²          :    Repeat twice
       i1X       :    Insert X at 0-based index 1

```
> 2 votes

# Answer
# Java (JDK), 104 bytes

```
t->{var w=t.split(" ");int i=0;for(var s:w){w[i]='"'+s+'"';System.out.println(s.join(" ",w));w[i++]=s;}}

```

Try it online!
> 2 votes

# Answer
# Elm Using recursion, ~~132,130,121,111,100~~ 99 bytes

Golfed down 9 bytes thanks to Kevin Cruijssen technique and another 22 bytes were cracked by ASCII-only. Turned to non-tail recursion during the golf.

```
f b a=case a of
 c::r->String.join" "(b++("\""++c++"\"")::r)::f(b++[c])r
 _->[]
u=f[]<<String.words

```

Try it online

85 bytes after exposing `String` functions to the current scope

```
f b a=case a of
 c::r->join" "(b++("""++c++""")::r)::f(b++[c])r
 _->[]
u=f[]<<words

```

Ungolfed version (Using tail recursion)

```
push : List a -> a -> List a
push list el =
    list ++ [ el ]

zip : (List a -> a -> List a -> b) -> List a -> List a -> List b -> List b
zip transform before after mapped =
    case after of
        [] ->
            mapped

        current :: rest ->
            transform before current rest
                |> push mapped
                |> zip transform (push before current) rest

wrap : appendable -> appendable -> appendable
wrap v str =
    v ++ str ++ v

cb : List String -> String -> List String -> String
cb before current rest =
    before ++ wrap "\"" current :: rest
        |> String.join " "

result : List String
result =
    zip cb [] (String.words "This is code golf") []

```

Try ungolfed
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler) with `/u:System.Text.RegularExpressions.Regex` flag, ~~59~~ 40 bytes

```
s=>Replace(s,"(\\S+) ?","$`\"$1\" $'\n")

```

~~Port of my Java 8 answer, so look there for an explanation.~~
-19 bytes by porting *@Arnauld*'s regex, since the `$``  and `$'` are supported in C# .NET.

Try it online.
> 2 votes

# Answer
# PowerShell, ~~70~~ 65 bytes

```
param($a)$a.Split()|%{$a-replace[regex]"( |^)$_( |$)"," ""$_"" "}

```

Try it online!

Has test suite in trial. Has 1 leading space on first row, and 1 trailing space on last row. Attempting to refactor.
> 1 votes

# Answer
# Charcoal, 19 bytes

```
Ｅ⪪θ ⪫Ｅ⪪θ ⎇⁼κμ⪫""λλ

```

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

```
  θ                     Input string
 ⪪                      Split on literal space
Ｅ                       Map over words
       θ                Input string
      ⪪                 Split on literal space
     Ｅ                  Map over words
            μ           Inner index
          ⁼             Equals
           κ            Outer index
         ⎇             If true then
               ""       Literal string `""`
              ⪫         Joined i.e. wrapping
                 λ      Current word
                  λ     Otherwise current word
    ⪫                  Joined with literal space
                        Implicitly print each result on its own line

```
> 1 votes

# Answer
# Attache, 34 bytes

```
Join&sp=>{On&_&Repr=>Iota@_}@Split

```

Try it online! Anonymous function returning a list of lines.

## Explanation

```
Join&sp=>{On&_&Repr=>Iota@_}@Split
                             Split      Splits the input on whitespace
         {         =>Iota@_}            Over each number K, 0 to #words - 1
          On  &Repr                     Apply the Repr (quoting) function
            &_                          on the Kth element in the input
Join&sp=>                               then rejoin the words of each inner sentence

```
> 1 votes

# Answer
# Perl 6, 46 bytes

```
{map {.prematch~"\"$_\""~.postmatch},m:g/\S+/}

```

Try it online!
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 123 bytes

I wonder if can this be shortened with regular expressions.

```
s=>(r=s.Split(' ')).Select((a,i)=>(string.Join(" ",r.Take(i))+" \""+a+"\" "+string.Join(" ",r.Skip(i+1))).Trim());string[]r

```

Try it online!
> 1 votes

# Answer
# Jelly, 15 bytes

```
⁾""j$€⁹¦K
ḲçⱮL$

```

Try it online!

Thanks to @JonathanAllan for saving 4 bytes
> 1 votes

# Answer
# Red, 113 bytes

```
func[s][repeat i length? u: split s" "[j: 1
foreach w u[prin rejoin[t: pick[{"}""]i = j w t sp]j: j + 1]prin lf]]

```

Try it online!
> 1 votes

# Answer
# APL+Win, 59 bytes

```
(⌽⍳⍴s)⊖((¯1 0+⍴s)⍴s)⍪(('"',¨s←(+\' '=s)⊂s←' ',⎕),¨'"')~¨' '

```

Prompts for string

Try it online! Courtesy of Dyalog Classic
> 1 votes

# Answer
# J, 45 bytes

```
   f =: ' 'joinstring"1(]`(dquote&.>])@.=($~$@=))@cut
   f 'this is a test string'
"this" is a test string
this "is" a test string
this is "a" test string
this is a "test" string
this is a test "string"

```

If the input can be a list of boxes, then my solution can be 30 bytes:

```
   f =: (]`(dquote&.>])@.=($~$@=))@cut
   f 'this is a test'
┌──────┬────┬───┬──────┐
│"this"│is  │a  │test  │
├──────┼────┼───┼──────┤
│this  │"is"│a  │test  │
├──────┼────┼───┼──────┤
│this  │is  │"a"│test  │
├──────┼────┼───┼──────┤
│this  │is  │a  │"test"│
└──────┴────┴───┴──────┘

```
> 1 votes

# Answer
# Python 3, 107 bytes

```
import re
def f(s):
 for w in re.finditer('[^ ]+',s):p=w.span();print(f'{s[:p[0]]}"{w.group()}"{s[p[1]:]}')

```

Try it online!

I... decided to use regex against my better judgement. This is the result.
> 1 votes

# Answer
# Oracle SQL, 92 bytes

```
select regexp_replace(s,'(\S+)','"\1"',1,level)from t connect by level<regexp_count(s,' ')+2

```

Assuming there is a table in a form

```
create table t as select 'This is a significantly longer, but not the longest testcase' s from dual;

```

Test in SQL\*Plus

```
SQL> select regexp_replace(s,'(\S+)','"\1"',1,level)from t connect by level<regexp_count(s,' ')+2
  2  /

REGEXP_REPLACE(S,'(\S+)','"\1"',1,LEVEL)
--------------------------------------------------------------------------------
"This" is a significantly longer, but not the longest testcase
This "is" a significantly longer, but not the longest testcase
This is "a" significantly longer, but not the longest testcase
This is a "significantly" longer, but not the longest testcase
This is a significantly "longer," but not the longest testcase
This is a significantly longer, "but" not the longest testcase
This is a significantly longer, but "not" the longest testcase
This is a significantly longer, but not "the" longest testcase
This is a significantly longer, but not the "longest" testcase
This is a significantly longer, but not the longest "testcase"

10 rows selected.

```
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 93 bytes

```
	S =' '
	I =INPUT S
S	I ARB . R S REM . I	:F(END)
	OUTPUT =L '"' R '"' S I
	L =L R S	:(S)
END

```

Try it online!

Each line ends with an additional space.
> 1 votes

# Answer
# Python 3.8 (pre-release), ~~92~~, 79 bytes

-13 bytes thanks to @Steffan

```
lambda x:(l:=range(len(x)),[[[x[a],'"%s"'%x[a]][a==i]for a in l]for i in l])[1]

```

Try it online!
> 1 votes

# Answer
# Python 2, 108 bytes

```
def f(s):
 W=s.split();n=len(W)
 for x in range(n*n):print[W[x%n],'"'+W[x%n]+'"'][x%-~n==0]+'\n'*(x%n==n-1),

```

Try it online!
> 0 votes

# Answer
# PHP, 134 bytes

```
<?php $i=explode(' ',file_get_contents('php://stdin'));for($x=0;$x<count($i);$x++){$o=$i;$o[$x]='"'.$i[$x].'"';echo join(' ',$o).'
';}

```

Try it online!
> 0 votes

# Answer
# Thunno 2 `N`, 10 bytes

```
Oı$OṅnṘȧðj

```

Try it online!

#### Explanation

```
Oı$OṅnṘȧðj  # Implicit input
O           # Split it on spaces
 ı          # Map over this list:
  $O        #  Input split on spaces
    ṅ  ȧ    #  Replace the current item with
     nṘ     #  itself surrounded by quotes
        ðj  #  Join this list on spaces
            # Join on newlines
            # Implicit output

```
> 0 votes

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


# Question
Title: Hyperprogramming: N+N, N×N, N^N all in one
Write a program that takes in a number N from 1 to 9 inclusive. In its native form your program should output N+N. E.g. output `2` if N is `1`, `4` if N is `2`, `6` if N is `3`, and so on.

When every character in your program is duplicated in place, then it should be a program that takes in N (still from 1 to 9) and outputs N×N. E.g. output `1` if N is `1`, `4` if N is `2`, `9` if N is `3`, and so on.

When every character in your program is triplicated in place, then it should be a program that takes in N (still from 1 to 9) and outputs N^N. E.g. output `1` if N is `1`, `4` if N is `2`, `27` if N is `3`, `387420489` if N is `9`, etc.

Numbers above 9 aren't required because 10^10 is outside of many language's usual integer range.

# Example

If your initial program was

```
My_Program!
Exit();

```

Then it should be capable of taking in N and outputting N+N.

Additionally, the program

```
MMyy__PPrrooggrraamm!!

EExxiitt(());;

```

should take in N and output N×N.

Finally, the program

```
MMMyyy___PPPrrrooogggrrraaammm!!!

EEExxxiiittt((()));;;

```

should take in N and output N^N.

Quadrupled-character programs and beyond are not required.

# Rules

* Input and output should be plain, normally formatted decimal numbers. You may answer using a different base to show off your code but then your answer is non-competitive.
* Windows users may treat `\r\n` as one character since things like `\r\r\n\n` wouldn't make sense or perhaps even work.
* **The shortest native program (the N+N one) in bytes wins.**

# Answer
> 224 votes
# Jelly, 12 bytes

### N+N

```
“(ẹ+)‘FQṖṪỌv

```

Try it online!

### N×N

```
““((ẹẹ++))‘‘FFQQṖṖṪṪỌỌvv

```

Try it online!

### N^N

```
“““(((ẹẹẹ+++)))‘‘‘FFFQQQṖṖṖṪṪṪỌỌỌvvv

```

Try it online!

## How it works

Jelly has several different types of string literals; all of them start with a . If the literal contains more than one , a string array is returned, and  separates the strings from each other.

For example, `“abc“def”` yields `['abc', 'def']`.

Depending on the last character of the literal (any of `”«»‘’`, where `«` is currently unimplemented), one can choose between the different types of literals. For , we get the code points in Jelly's code page instead of the corresponding Unicode characters.

For example, `“abc“def‘` yields `[[97, 98, 99], [100, 101, 102]]`.

The three literals in the programs correspond to the following code point arrays.

```
“(ẹ+)‘           -> [40, 214, 43, 41]
““((ẹẹ++))‘      -> [[], [40, 40, 214, 214, 43, 43, 41, 41]]
“““(((ẹẹẹ+++)))‘ -> [[], [], [40, 40, 40, 214, 214, 214, 43, 43, 43, 41, 41, 41]]

```

### N+N

```
“(ẹ+)‘FQṖṪỌv                          Main link. Argument: n

“(ẹ+)‘                                As before.
      F                               Flatten the array. Yields an integer array.
       Q                              Unique; deduplicate the integers.
                                      This yields [40, 214, 43, 41].
        Ṗ                             Pop; remove the last element.
         Ṫ                            Tail; extract the last element.
                                      This yields 43, the Unicode code point of +.
          Ọ                           Unordinal; cast to character.
           v                          Eval; execute the character as a Jelly
                                      program with argument n.

```

### N×N

```
““((ẹẹ++))‘‘FFQQṖṖṪṪỌỌvv              Main link. Argument: n

““((ẹẹ++))‘                           As before.
           ‘                          Increment all integers.
            FF                        Flatten the array. Yields an integer array.
              QQ                      Unique; deduplicate the integers.
                                      This yields [41, 215, 44, 42].
                ṖṖ                    Pop twice; remove the last two elements.
                  ṪṪ                  Tail; extract the last element.
                                      This yields 215, the Unicode code point of ×.
                    ỌỌ                Unordinal; cast to character.
                      v               Eval; execute the character as a Jelly
                                      program with argument n.
                       v              Eval; convert the return value (n×n) to a
                                      string and execute that string as a Jelly
                                      program with argument n. Since the string
                                      consists of a single integer literal, that
                                      integer is returned, ignoring the argument.

```

Note that `F`, `Q`, , and  do not alter 1D arrays, arrays without duplicates, integers, and characters (respectively).

### N^N

```
“““(((ẹẹẹ+++)))‘‘‘FFFQQQṖṖṖṪṪṪỌỌỌvvv  Main link. Argument: n

“““(((ẹẹẹ+++)))‘                      As before.
                ‘‘                    Increment all integers twice.
                  FFF                 Flatten the array. Yields an integer array.
                     QQQ              Unique; deduplicate the integers.
                                      This yields [42, 216, 45, 43].
                        ṖṖṖ           Pop thrice; remove the last three elements.
                           ṪṪṪ        Tail; extract the last element.
                                      This yields 42, the Unicode code point of *.
                              ỌỌỌ     Unordinal; cast to character.
                                 v    Eval; execute the character as a Jelly
                                      program with argument n.
                                  vv  Eval twice. See N×N.

```

# Answer
> 93 votes
## \>\<\>, 41 bytes

```
\<
1:: :
&&* +
i*n n
c&
%:
4l
0(
.i
n}
&?

```

Try it online: **N+N**, **N\*N**, **N^N**. Assumes that the STDIN input is exactly one char.

\>\<\> is a 2D language, so we can make use of the fact that code semantics are mostly unchanged if we execute instructions downwards — the extra empty lines that ensue are just no-ops. The exception to this is the conditional trampoline `?` which pops a value and skips the next instruction if the value was nonzero — the extra newlines would mess up `?` due to the inserted no-ops, but we can get around this by putting the `?` at the end of a column and taking advantage of wrapping.

To decide which operation to execute, the key is `40.`, which teleports the IP to position `(4, 0)`. Due to the expansion of the code, the `x = 4` column corresponds to `+` for the base program, `*` for the doubled program and `^` for the tripled program. Unfortunately \>\<\> doesn't have exponentiation built in, making that the bulk of the program.

```
[Setup]
\         Mirror: reflect IP direction to downwards
1&        Put 1 into the register
ic%       Push a code point of input, then take it mod 12. This maps the char '1' to the
          number 1, and so forth for '2' to '9'.
40.       Jump to (4, 0), still heading downwards

[N+N version]
:+        Duplicate then add
n         Output as number
          (Stack is now empty, so the program errors out trying to do the above again)

[N*N version]
:*        Duplicate then multiply
n         Output as number
          (Stack is now empty, so the program errors out trying to do the above again)

[N^N version]
:&*&      Multiply register by N
:l(       Push (N < length of stack + 1)
i         Push input, but since we're now at EOF this pushes -1 (stack length += 1)
}         Move -1 to the back
?<        If (N < length + 1) was 1, execute the < to move leftward. Otherwise, skip it.
          (Continue loop)

\         Mirror: reflect IP direction upwards
&n        Output register
.         Jump to (-1, N), which is invalid so the program errors out

```

# Answer
> 29 votes
# **TovTovTov** (a mutation of **Chicken**): 810147050 bytes

Described below are **two** suggested solutions: One *full* solution to the question requiring lots of bytes, and a second *partial* solution (solving only the *N+N* and *N\*N* parts, requiring only 484 bytes), each taking a different approach and its own set of cool tricks! :)

### 1. Full solution (810147050 bytes)

Using `TovTovTov(TOV='hi',SEP=',')`, the `TOV` elements are immune to duplicating characters in place (both `"hihihi"` and `"hhiihhiihhii"` have three `"hi"`s in them, and all **`TovTovTov`** cares about is how many `TOV`s appear between `SEP`s).

If we used `SEP=', '`, the entire program would be immune to character duplication (which is cool, but won't solve the question). So we use `SEP=','`.

So the program `"hihihi,hi"`, for example, compiles to the ints array `[3,1]`, while `"hhiihhiihhii,,hhii"` compiles to `[3,0,1]` and `"hhiihhiihhii,,hhii"` to `[3,0,0,1]`. This means that the commands themselves don't change their meaning after duplication, but the overall length changes with character duplication. The solution below queries the length of the program and uses this to decide whether to print `N+N`, `N*N` or `N^N`.

The suggested full solution, as ints array, is: `[6, 12, 9, 18, 9, 142, 11, 38, 8, 9, 260, 11, 73, 8, 22, 75, 7, 10, 14, 3, 1, 22, 24, 18, 15, 8, 10, 16, 3, 1, 22, 24, 18, 15, 8, 10, 45, 16, 7, 22, 3, 1, 22, 24, 18, 15, 8, 22, 3, 1, 22, 24, 18, 15, 8, 25, 3, 1, 22, 24, 18, 15, 8, 48, 3, 1, 22, 24, 18, 15, 8, 277, 3, 1, 22, 24, 18, 15, 8, 3146, 3, 1, 22, 24, 18, 15, 8, 46677, 3, 1, 22, 24, 18, 15, 8, 823564, 3, 1, 22, 24, 18, 15, 8, 16777237, 3, 1, 22, 24, 18, 15, 8, 387420510, 3, 1, 22, 24, 18, 15, 8]`

As a string, it's a pretty long program, consisting of 810147050 characters, starting with: `hihihihihihi,hihihihihihihihihihihihi,hihihihihihihihihi,hihihihihihihihihihihihihihihihihihi,hihihihihihihihihi,hihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihih...`

### 2. Solving only the N+N and N\*N parts of the question (484 bytes)

Using `TovTovTov(TOV='1',SEP=', ')`, this time the `SEP`s are immune to duplication (`",, "` still has just one `", "` in it), so the following suggested solution will always have 33 commands in it, even after character duplication:

`1111, 111111111111111111111111111111111111111111111111, 1111111111, 1111111111, 1111111111, 111111, 111111111111, 111111111, 11111111111111, 111, 1, 1111111111111111111111, 111111111111111111111111, 111111111111111111, 111111111111111, 11111111, 111111111111, 1111111111111111, 111111111111111, 1111111111111111111111, 111111111111111111111111111111111111, 11, 1111111111111111111111111111, 111111, 111, 111111, 11111111111, 111111111111111111111111111, 1111, 1, 11111111, 1, 11111111`

The corresponding ints array (the number of `TOV`s (`1`s) in each of the 33 commands above) is as follows: `[4,48,10,10,10,6,12,9,14,3,1,22,24,18,15,8,12,16,15,22,36,2,28,6,3,6,11,27,4,1,8,1,8]`

Duplicating the characters in place results in a list of 33 **totally different commands**: `[8,96,20,20,20,12,24,18,28,6,2,44,48,36,30,16,24,32,30,44,72,4,56,12,6,12,22,54,8,2,16,2,16]`

The original ints array (that calculates *N+N*) was designed *carefully* so that after the commands change their meaning, the program still makes sense, but calculates *N\*N*. For example, the first `4` (that **`TovTovTov`** understands as "treat the next op as an ascii code to convert to a character") changes after character duplication to `8`, which is a *totally different command* ("change the Program Counter to the first popped value from the stack, if the value popped immediately after is true").

# Answer
> 16 votes
# Befunge-98 (FBBI), ~~38~~ 41 bytes

*(+3 bytes to fix bug, thanks Jo King!)*

```
vx:k::1-k*\/.@
20@
j3.
>^*
>:^
>:+.@

```

Try it online: N+N, N\*N, N^N

This program won't work out-of-the-box since it requires input to be on the stack at the start of execution. By replacing the first line with the following code (adding three more bytes) it will take input from stdin:

```
v
&x:k:2-

```

---

## Explanation

### Setup

```
v       Redirect motion downward
02j     Jump over two instructions/spaces, executing the third
        If N=1, it will skip to the 6th line
        If N=2, it will skip to the 5th line
        If N=3, it will skip to the 4th line

```

### N=1

```
>       Move right
:+.@    Duplicate, add, print and exit

```

### N=2

```
>>::^^  Move right, duplicate twice, move up
*.@     Multiply, print and exit

```

### N=3

```
>>>^^^  Redirect motion
30x     Set instruction pointer delta to (3, 0), causing it to
        move right, executing every third instruction
:k::    Duplicate the number (we'll call it M) M+2 times
        The stack is now [M]*(M+3)
1-k*    Multiply things M times (`k' is a quirky instruction)
\/      Divide that result by M (workaround for `k` being quirky)
.@      Print and exit

```

# Answer
> 12 votes
# Gol\>\<\>, ~~20~~ 18 bytes

Unlike \>\<\>, Gol\>\<\> actually has an exponentiation built-in.

```
\hh
I
:
\\
\\\
X*+

```

Try it online!

Try it online (doubled)!

Try it online (tripled)!

## Explanation

For the explanations here, I'll replace un-executed code with spaces.

```
\      Reflect the pointer down
I      Take an input
:      Copy the input
\\     Series of mirrors...
 \\    That reflect to the addition part
  +    Add the two numbers
  h    (Wrapped around) Print, and Halt

```

## Explanation (doubled)

```
\            Reflect down

I            Take input

:            Duplicate the stack

\\           Set of mirrors...

 \\          That redirect to the * section

  *          Multiply two numbers

  h          (Wrapped around) Print + Halt

```

## Explanation (tripled)

```
\            Reflect down

I            Take input

:            Duplicate input

\\           Set of mirrors...

 \\          ... That redirect to the exponentiation section

  X          Exponentiate the two values

  \h         (Wrapped around) Reflect right to the Print + Halt statement

```

# Gol\>\<\>, 19 bytes

A longer (and more boring) version based on the \>\<\> solution.

```
v
IX* +
:hh h
4
0
.

```

Try it online!

Try it online (doubled)!

Try it online (tripled)!

# Answer
> 1 votes
# Itr, 29 bytes

`"L0#+â*;"0 0 0'+$©^#$0ååä0 0^`

online interpreter

doubled

tripled

## Explanation

Relies on Itr's redefinition operator `$` (and the ability to redefine redefinition) to distinguish between the first and third case. Uses string literals to run independent code for the second case.

normal:

```
"L0#+â*;"0 0 0'+$©^#$0ååä0 0^
"L0#+â*;"                     ; string literal
         0 0 0                ; push zero 3 times
              '+$©^           ; redefine ^ to mean +
                   #$0        ; read the input, store it in variable zero
                      ååä     ; stack operations
                         0 0^ ; Input + Input (after redefinition)
                              ; implicit output

```

doubled:

```
""LL00##++ââ**;;""00  00  00''++$$©©^^##$$00ååååää00  00^^
""                ; empty string
  LL              ; push 1 two times (calling 'L' on number)
    00            ; push zero
      ##          ; read input, 2nd # will push zero as stdin is empty
        ++        ; add up the top 3 stack values (results in the input value)
          ââ      ; "under" stack operation twice (1 1 X -> 1 X X 1 X )
            **    ; multiply top three stack values, giving X*1*X=X*X
              ;;  ; comment out the rest of the line

```

tripled:

```
"""LLL000###+++âââ***;;;"""000   000   000'''+++$$$©©©^^^###$$$000ååååååäää000   000^^^

"""LLL000###+++âââ***;;;"""    ; 3 string literals

000   000   000                ; push zero 3 times

'''+++$$                       ; redefine the $ operator to be the string literal "R"

$©                             ; call "R" consuming zero on stack
  ©©                           ; call 3rd zero and empty string on stack
    ^^^                        ; power with basis zero -> will push (vector of) zeros

###$$$000ååååååäää000   000^^^ ; the actual computation
###                            ; read number and two implicit zero from stdin
   $$$                         ; push string "R" 3 times
      000                      ; push zero
         åååååå                ; discard the top 6 values on the stack
               äää             ; duplicate top stack value (Input) 3 times
                  000   000    ; push zero twice
                           ^^^ ; calculates X^(X^(0^0))= X^X

```

---
Tags: code-golf, math, number, arithmetic, source-layout
---