# Question
Title: If a program terminates and there is no one to see it, does it halt?
It's time to face the truth: We will not be here forever, but at least we can write a program that will outlive the human race even if it struggles till the end of time.

Your task is to write a program that has a expected running time greater than the remaining time till the end of the universe.

You may assume that:

* The universe will die from entropy in 101000 years.
* Your computer:
    + Will outlive the universe, because it is made of Unobtainium.
    + Has infinite memory/stack/recursion limit.
    + Its processor has limited speed.

You must show that your program terminates (sorry, no infinite loops) and calculate its expected running time.

The standard loopholes apply.

This is a code golf challenge, so the shortest code satisfying the criteria wins.

**EDIT**:

Unfortunately, it was found (30min later) that the improbability field of Unobtainium interferes with the internal clock of the computer, rendering it useless. So time based programs halt immediately. (Who would leave a program that just waits as its living legacy, anyway?).

The computer processor is similar to the Intel i7-4578U, so one way to measure the running time is to run your program in a similar computer with a smaller input (I hope) and extrapolate its running time.

---

## Podium

| # | Chars | Language | Upvotes | Author |
| --- | --- | --- | --- | --- |
| 1 | 5 | CJam | 20 | Dennis |
| 2 | 5 | J | 5 | algorithmshark |
| 3 | 7 | GolfScript | 30 | Peter Taylor |
| 4 | 9 | Python | 39 | xnor |
| 5 | 10 | Matlab | 5 | SchighSchagh |

* Upvotes on 31/08

# Answer
> 36 votes
# CJam, 5 bytes

```
0{)}h

```

### How it works

```
 0   " Push 0.                                 ";
 {   "                                         ";
   ) " Increment the Big Integer on the stack. ";
 }h  " Repeat if the value is non-zero.        ";

```

This program will halt when the heap cannot store the Big Integer anymore, which won't happen anytime soon on a modern desktop computer.

The default heap size is 4,179,623,936 bytes on my computer (Java 8 on Fedora). It can be increased to an arbitrary value with `-Xmx`, so the only real limit is the available main memory.

### Time of Death

Assuming that the interpreter needs *x* bits of memory to store a non-negative Big Integer less than *2x*, we have to count up to *28 × 4,179,623,936 = 233,436,991,488*. With one increment per clock cycle and my Core i7-3770 (3.9 GHz with turbo), this will take *233,436,991,488 ÷ 3,400,000,000 \> 1010,065,537,393* seconds, which is over *1010,065,537,385* years.

# Answer
> 64 votes
# JavaScript, 39

```
(function f(x){for(;x!=++x;)f(x+1)})(0)

```

### Explanation

Since JavaScript does not precisely represent large integers, the loop `for(;x!=++x;)` terminates once `x` hits `9007199254740992`.

The body of the for loop will be executed `Fib(9007199254740992) - 1` times, where `Fib(n)` is the nth fibonacci number.

From testing, I know my computer will do less than 150,000 iterations per second. In reality, it would run much slower because the stack would grow very large.

Thus, the program will take at least `(Fib(9007199254740992) - 1) / 150000` seconds to run. I have not been able to calculate `Fib(9007199254740992)` because it is so large, but I know that it is much larger than 101000 * 150,000.

EDIT: As noted in the comments, `Fib(9007199254740992)` is approximately 4.4092\*101882393317509686, which is indeed large enough.

# Answer
> 48 votes
# Python (9)

```
9**9**1e9

```

This has more than 10\**10000000 bits, so computing it should take us far past heat death.

I checked that this takes more and more time for larger but still reasonable values, so it's not just being optimized out by the interpreter.

**Edit:** Golfed two chars by removing parens thanks to @user2357112. TIL that Python treats successive exponents as a power tower.

# Answer
> 36 votes
# Marbelous ~~68~~ 66 bytes

```
}0
--@2
@2/\=0MB
}0@1\/
&0/\>0!!
--
@1
00@0
--/\=0
\\@0&0

```

Marbelous is an 8 bit language with values only represented by marbles in a Rube Goldberg-like machine, so this wasn't very easy. This approach is roughly equivalent to the following pseudo-code:

```
function recursiveFunction(int i)
{
    for(int j = i*512; j > 0; j--)
    {
        recursiveFunction(i - 1);
    }
}

```

since the maximum value is 256, (represented by 0 in the Marbleous program, which is handled differently in different places) recursiveFunction(1) will get called a total of `256!*512^256` which equals about `10^1200`, easily enough to outlive the universe.

Marbelous doesn't have a very fast interpreter, it seems like it can run about `10^11` calls of this function per year, which means we're looking at a runtime of `10^1189` years.

**Further explanation of the Marbelous board**

```
00@0
--/\=0
\\@0&0

```

`00` is a language literal (or a marble), represented in hexadecimal (so 0). This marble falls down onto the `--`, which decrements any marble by 1 (00 wraps around and turns into FF or 255 in decimal). The Marble with now the value FF falls down onto the `\\` which shoves it one column to the right, onto the lower `@0`. This is a portal and teleports the marble to the other `@0` device. There, the marble lands on the `/\` device, which is a duplicator, it puts one copy of the marble on the `--` to its left (this marble will keep looping between the portals and get decremented on every loop) and one on the `=0` to its right. `=0` compares the marble to the value zero and lets teh marble fall trough if it's equal and pushes it to the right if not. If the marble has teh value 0, it lands on `&0`, a synchonizer, which I will explain further, later.

All in all, this just starts with a 0 value marble in a loop and decrements it until it reaches 0 again, it then puts this 0 value marble in a synchronizer and keeps looping at the same time.

```
}0@1
&0/\>0!!
--
@1

```

`}0` is an input device, initially the nth (base 0) command line input when calling the program gets placed in every `}n` device. So if you call this program with command line input 2, a 02 value marble will replace this `}0`. This marble then falls down into the `&0` device, another synchronizer, `&n` synchronizers hold marbles until all other corresponding `&n`'s are filed as well. The marble then gets decremented, teleported and duplicated much like in the previously explained loop. The right copy then get checked for inequality with zero (`>0`) if it's not 0, it falls through. If it is 0, it gets pushed to the right and lands on `!!`, which terminates the board.

Okay, so far we have a loop that continuously counts down from 255 to 0 and lets another, similar loop (fed by the command line input) run once every time it hits 0. When this second loop has run n times (maximum being 256) the program terminates. So that's a maximum of 65536 runs of the loop. Not nearly enough to outlive the universe.

```
}0
--@2
@2/\=0MB

```

This should start looking familiar, the input gets decremented once, then this value loops around and get copied (note that the marble only gets decremented once, not on every run of the loop). It then gets checked for equality to 0 and if it's not zero lands on `MB`. This is a function in Marbelous, every file can contain several boards and each board is a function, every function has to be named by preceding the grid by `:[name]`. Every function except for the first function in the file, which has a standard name: MB. So this loop continuously calls the main board again with a value of `n - 1` where n is teh value with which this instance of teh function was called.

**So why `n*512`?**

Well, the first loop runs in 4 ticks (and 256 times) and the second loop runs n times before the board terminates. This means the board runs for about `n*4*256` ticks. The last loop (which does the recursive function calling) is compacter and runs in 2 ticks, which means it manages to call the function `n*4*256/2 = n*512` times.

**What are the symbols you didn't mention?**

`\/` is a trash bin, which removes marbles from the board, this makes sure discarted marbles don't interfere with other marbles that are looping a round and prevent the program from terminating.

**Bonus**

Since marbles that fall off the bottom of a marbelous board get output to STDOUT, this program prints a plethora of ASCII characters while it runs.

# Answer
> 35 votes
## GolfScript (12 7 chars)

```
9,{\?}*

```

This computes and prints 8^7^6^5^4^3^2 ~= 10^10^10^10^183230. To print it (never mind the computation) in 10^1000 years ~= 10^1007.5 seconds, it needs to print about 10^(10^10^10^183230 - 10^3) digits per second.

# Answer
> 21 votes
# Perl, 66 58 characters

```
sub A{($m,$n)=@_;$m?A($m-1,$n?A($m,$n-1):1):$n+1;}A(9,9);

```

The above is an implementation of the Ackermann–Péter function. I have no idea how large A(9,9) is but I am fairly certain it will take an astoundingly long time to evaluate.

# Answer
> 20 votes
# MATLAB, ~~58~~ 52 characters

We need at least one finite-precision arithmetic solution, hence:

```
y=ones(1,999);while y*y',y=mod(y+1,primes(7910));end

```

~~x=ones(1,999);y=x;while any(y),y=mod(y+x,primes(7910));end~~

(*with thanks to @DennisJaheruddin for knocking off 6 chars*)

The number of cycles needed to complete is given by the product of the first 999 primes. Since the vast majority of these are well over 10, the time needed to realize convergence would be hundreds or thousands of orders of magnitude greater than the minimum time limit.

# Answer
> 19 votes
## Mathematica, ~~25~~ 19 bytes

*This solution was posted before time functions were disqualified.*

```
While[TimeUsed[]<10^10^5]

```

`TimeUsed[]` returns the seconds since the session started, and Mathematica uses arbitrary-precision types. There are some 107 seconds in a year, so waiting 1010000 seconds should be enough.

Shorter/simpler(/valid) alternative:

```
For[i=0,++i<9^9^9,]

```

Let's just count instead. We'll have to count a bit further, because we can do a quite a lot of increments in a second, but the higher limit doesn't actually cost characters.

Technically, in both solutions, I could use a much lower limit because the problem doesn't specify a minimum processor speed.

# Answer
> 17 votes
# Python 3 - 49

This does something useful: calculates Pi to unprecedented accuracy using the Gregory-Leibniz infinite series.

Just in case you were wondering, this program loops `10**10**10**2.004302604952323` times.

```
sum([4/(i*2+1)*-1**i for i in range(1e99**1e99)])

```

## Arbitrary precision: 78

```
from decimal import*
sum([Decimal(4/(i*2+1)*-1**i)for i in range(1e99**1e99)])

```

Image source

# The Terminal Breath

Due to the huge calculations taking place, `1e99**1e99` iterations takes just under `1e99**1e99` years. Now, `(1e99**1e99)-1e1000` makes barely any difference. That means that this program will run on far longer than the death of our universe.

# Rebirth

Now, scientists propose that in `10**10**56 years`, the universe will be reborn due to quantum fluctuations or tunnelling. So if each universe is exactly the same, how many universe will my program live through?

```
(1e99**1e99)/(1e10+1e1000+10**10**56)=1e9701

```

Assuming that the universe will always live `1e10+1e1000` years and then take `10**10**56` years to 'reboot', my program will live through `1e9701` universes. This is assuming, of course, that unobtainium can live through the Big Bang.

# Answer
> 12 votes
# Python 59 (works most of the time)

I couldn't resist

```
from random import*
while sum(random()for i in range(99)):0

```

While its true that this could theoritically terminate in under a millisecond, the average runtime is well over `10^400` times the specified lifespan of the universe. Thanks to @BetaDecay, @undergroundmonorail, and @DaboRoss for getting it down a 17 characters or so.

# Answer
> 8 votes
# J - 5 chars, I think

Note that all of the following is in arbitrary precision arithmetic, because the number 9 always has a little `x` beside it.

In **seven** characters, we have `!^:!!9x`, which is kinda like running

```
n = 9!
for i in range(n!):
    n = n!

```

in arbitrary precision arithmetic. This is definitely over the limit because Synthetica said so, so we have an upper bound.

In **six** chars, we can also write `^/i.9x`, which calculates every intermediate result of `0 ^ 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 ^ 7 ^ 8`. Wolfram|Alpha says `2^3^4^5^6^7^8` is approximately `10 ^ 10 ^ 10 ^ 10 ^ 10 ^ 10 ^ 6.65185`, which probably also clears inspection.

We also have the **five** char `!!!9x`, which is just ((9!)!)!. W|A says it's `10 ^ 10 ^ 10 ^ 6.2695`, which should still be big enough... That's like `1.6097e1859933`-ish digits, which is decidedly larger than `3.154e1016`, the number of nanoseconds in the universe, but I'm gonna admit I have no idea how one might figure out the real runtimes of these things.

The printing alone should take long enough to last longer than the universe, though, so it should be fine.

# Answer
> 7 votes
# C, 63 56 chars

```
f(x,y){return x?f(x-1,y?f(x,y-1):1):y+1;}main(){f(9,9);}

```

> This is based on an idea by a guy named Wilhelm. My only contribution is condensing the code down to this short (and unreadable) piece.

Proving that it terminates is done by induction.

* If x is 0, it terminates immediately.
* If it terminates for x-1 and any y, it also terminates for x, this itself can be shown by induction.

Proving the induction step by induction:

* If y is 0 there is only one recursive call with x-1, which terminates by induction assumption.
* If f(x, y-1) terminates then f(x, y) also terminates because the innermost call of f is exactly f(x, y-1) and the outermost call terminates according to the induction hypthesis.

> The expected running time is A(9,9) / 11837 seconds. This number has more digits than the number of quarks in the observable universe.

# Answer
> 6 votes
# Matlab (~~10~~ 8 chars)

```
1:9e1016

```

IMHO, most entries are trying too hard by computing large, complicated things. This code will simply initialize an array of 9x101016 `double`s counting up from 1, which takes 7.2x10^1017 bytes. On a modern CPU with a maximum memory bandwidth of 21 GB/s or 6.63x10^17 bytes/year, it will take *at least* 1.09x101000 years to even initialize the array, let alone try to print it since I didn't bother suppressing the output with a trailing semicolon. (;

---

old solution(s)

```
nan(3e508)

```

Alternatively

```
inf(3e508)

```

This code will simply create a square matrix of `NaN`s/infinities of size `3e508`x`3e508 = 9e1016` 8-byte doubles or `7.2e1017` bytes.

# Answer
> 5 votes
# Perl, 16 chars

```
/$_^/for'.*'x1e9

```

This builds a string repeating ".\*" a billion times, then uses it as both the needle and the haystack in a regex match. This, in turn, causes the regex engine to attempt every possible partition of a string two billion characters long. According to this formula from Wikipedia, there are about 1035218 such partitions.

The above solution is 16 characters long, but only requires about 2Gb of memory, which means it can be run on a real computer. If we assume infinite memory and finite register size (which probably doesn’t make sense), it can be shortened to 15 characters while dramatically increasing the runtime:

```
/$_^/for'.*'x~0

```

(I haven’t tested it, but I think it could work with a 32-bit Perl built on a 64-bit machine with at least 6Gb of RAM.)

Notes:

* `x` is the string repeat operator.
* the `for` isn’t an actual loop; it is only used to save one character (compared to `$_=".*"x1e9;/$_^/`).
* the final `^` in the regex ensures that only the empty string can match; since regex quantifiers are greedy by default, this is the last thing the engine will try.
* benchmarks on my computer for values (1..13) suggest that the running time is actually O(exp(n)), which is even more than the O(exp(sqrt(n))) in the Wikipedia formula.

# Answer
> 4 votes
# J (12)

```
(!^:(!!9))9x

```

What this comes down to in Python (assuming `!` works):

```
a = 9
for i in range((9!)!):
    a = a!

```

EDIT:

Well, the program can take, at most, `2 × 10^-1858926` seconds per cycle, to complete within the required time. Tip: this won't even work for the first cycle, never mind the last one ;).

Also: this program might need more memory than there is entropy in the universe...

# Answer
> 4 votes
First attempt at code golf but here goes.

VBA - ~~57~~ 45

```
x=0
do
if rnd()*rnd()<>0 then x=0
x=x+1
while 1=1

```

So X will go up by one if a 1 in 2^128 event occurs and reset if it does not occur. The code ends when this event happens 2^64+1 times in a row. I don't know how to begin calculating the time but I'm guessing it is huge.

EDIT: I worked out the math and the probability of this happening in each loop is 1 in 2^128^(1+2^64) which is about 20000 digits long. Assuming 1000000 loops/sec (ballpark out of thin air number) and 30000000 s/yr that's 3\*10^13 cycles per year time 10^1000 years left is 3\*10^1013 cycles, so this would likely last around 20 times the remaining time left in the universe. I'm glad my math backs up my intuition.

# Answer
> 4 votes
# C# 217

I'm not much of a golfer, but I couldn't resist Ackerman's function. I also don't really know how to calculate the runtime, but it will definitely halt, and it will definitely run longer than this version.

```
class P{
static void Main(){for(int i=0;i<100;i++){for(int j=0;j<100;j++){Console.WriteLine(ack(i,j));}}}
static int ack(int m,int n){if (m==0) return n+1;if (n ==0) return ack(m-1,1);return ack(m-1,ack(m,n-1));}
}

```

# Answer
> 4 votes
# C, 30 characters

```
main(i){++i&&main(i)+main(i);}

```

Assuming two's compliment signed overflow and 32-bit ints, this will run for about 2232 function calls, which should be plenty of time for the universe to end.

# Answer
> 4 votes
# R, 45 bytes

```
(f=function(x)if(x)f(x-1)+f(x-1)else 0)(9999)

```

It's an old thread but I see no R answer, and we can't be having that!

The runtime for me was about 1s when x was 20, suggesting a runtime of 2^9979 seconds.

If you replace the zero with a one, then the output would be 2^x, but as it stands the output is zero whatever x was (avoids overflow problems).

# Answer
> 3 votes
# GolfScript, 13 chars

```
0{).`,9.?<}do

```

This program just counts up from 0 to 1099−1 = 10387420488. Assuming, optimistically, that the computer runs at 100 GHz and can execute each iteration of the program in a single cycle, the program will run for 1099−12 seconds, or about 3 × 1099−20 = 3 × 10387420469 years.

To test the program, you can replace the `9` with a `2`, which will make it stop at 1022−1 = 103 = 1000. (Using a `3` instead of a `2` will make it stop at 1033−1 = 1026, which, even with the optimistic assumptions above, it will not reach for at least a few million years.)

# Answer
> 3 votes
# Autohotkey 37

```
loop {
if (x+=1)>10^100000000
break
}

```

# Answer
> 3 votes
# Haskell, 23

```
main=interact$take$2^30

```

This program terminates after reading 1073741824 characters from `stdin`. If it's run without piping any data to `stdin`, you will have to type this number of characters on your keyboard. Assuming your keyboard has 105 keys, each rated for 100k mechanical cycles and programmed to generate non-dead keystrokes, autorepeat is off, and your keyboard socket allows 100 connection cycles, this gives the maximum number of keystrokes per computer uptime of 1050000000, which is not enough for the program to terminate.

Therefore, the program will only terminate when better hardware becomes available in terms of number of cycles, which is effectively never in this running universe. Maybe next time, when quality has higher priority than quantity. Until then, this program terminates in principle but not in practice.

# Answer
> 3 votes
# ~ATH, 56

In the fictional language ~ATH:

```
import universe U;
~ATH(U) {
} EXECUTE(NULL);
THIS.DIE()

```

> ~ATH is an insufferable language to work with. Its logic is composed of nothing but infinite loops, or at best, loops of effectively interminable construction.
>
> What many ~ATH coders do is import finite constructs and bind the loops to their lifespan. For instance the main loop here will terminate on the death of the universe, labeled U. That way you only have to wait billions of years for it to end instead of forever.

*I apologize for the borderline loophole violations; I thought it was too relevant to pass up.*

If anyone was actually amused by this, more details: (1), (2), (3), (4)

# Answer
> 3 votes
## APL, 10

I don't think this is a valid answer (as it is non-deterministic), but anyway......

```
{?⍨1e9}⍣≡1

```

This program calculates a random permutation of 1e9 numbers (`?⍨1e9`) and repeats until two consecutive outputs are equal (`⍣≡`)

So, every time a permutation is calculated, it has a 1 in 1000000000! chance of terminating. And 1000000000! is at least 10108.

The time it takes to calculate a permutation is rendered irrelevant by the massiveness of 1000000000!. But some testing show this is `O(n)` and extrapolating gives about 30 seconds.

However, my interpreter refuses to take inputs to the random function larger than 231-1 (so I used 1e9), and generating permutations of 1000000000 numbers gave a workspace full error. However, conceptually it can be done with a ideal APL interpreter with infinite memory.

This leads us to the possibility of using 263-1 in place of 1e9 to bump the running time up to at least 101020, assuming a 64-bit architecture.

But wait, is architecture relevant in an ideal interpreter? Hell no so there is actually no upper bound on running time!!

# Answer
> 2 votes
# Ruby(34)

The line `([0]*9).permutation.each{print}` takes about 2.47 seconds for 9! prints on my machine, while the line `([0]*10).permutation.each{print}` takes about 24.7 seconds for 10! prints, so I guess I can extrapolate here and calculate `(24.7/10!)*470! seconds in years` which is 6.87 * 10^1040, which should be the run time of:

```
([0]*470).permutation.each{print}

```

# Answer
> 2 votes
# JavaScript 68 62 chars

```
(function a(m,n){return m==0?n+1:a(m-1,n==0?1:a(m,n-1))})(5,1)

```

This uses the Ackermann-function which can be written as

```
function ackermann(a, b) {
  if (a == 0) return b + 1;
  if (b == 0) return ackermann(a-1, 1);
  else return ackermann(a-1, ackermann(a, b-1));
}

```

Its runtime time increases over exponentially and takes therefore very long to calculate. Even though it is not english here you can get an overview of its return values. According to the table `ackermann(5,1)` equals `2↑↑(65533)-3` which is, you know, very big.

# Answer
> 2 votes
# Befunge '93 - 40 bytes

(20x2 program)

```
v<<<<<<<<<<<<<<<<<<<
>??????????????????@

```

This program relies on random numbers to give it delay. Since Befunge interpreters are quite slow, this program should fit the bill. And if it doesn't, we can always expand it horizontally. Im not exactly sure how to go about calculating the expected running time of this program, but I know that each ? has a 50/50 chance of either starting over or changing its horizontal position by 1. There are 18 ?'s. I think it should be something along the lines of (18^2)!, which google calculator says is "Infinity"

EDIT: Whoops I did not notice the other Befunge answer, this is my first post here. Sorry.

# Answer
> 2 votes
## Python 3, 191 Bytes

```
from random import*
r=randint
f=lambda n:2if n<2else f(n-1)
x=9E999
s=x**x
for i in range(f(x)**f(s)):
 while exec(("r(0,f(x**i))+"*int(f(x)))+"r(0,f(x**i))")!=0:
  s=f(x**s)
  print(s)

```

First, f is a recursive factorial function and ultra slow. Then, there is 9\*10⁹⁹⁹ powed with itself, which generates an OverflowError, but this doesn't happen on this Unobtanium computer. The For-Loop iterates 9E999! ^ (9E999^9E999)! times and it only goes to the next iteration, if 9E999!+1 random ints between 0 and 9E99\*^i! are all 0 and in every iteration of the while-loop s gets set to (9E999^s)!. Uh, I forgot that the printing of s takes muuuuccchhhh time...
I know it's not the shortest soloution, but I think it's really effective. Can someone help me calculating the running time?

# Answer
> 1 votes
# Javascript, 120 bytes

```
a=[0];while(a.length<1e4)(function(){var b=0;while(b<a.length){a[b]=(a[b]+1)%9;if(a[b])return;b++}a.push(1)})();alert(a)

```

Can be done with minimal memory (probably less than half a megabyte) but takes (probably) about 108,750 years to halt.

Repeatedly increments a little-endian base-9 BigInteger until it reaches 9104-1.

# Answer
> 1 votes
# Turing Machine But Way Worse, 167 bytes

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

```

Try it online!

Should run the 6-state 2-symbol Busy Beaver from the Wikipedia page.

As said in the Wikipedia page, it runs in \\$7.412 \times 10^{36534}\\$ steps. This is way more than the heat death, assuming it executes each command in more than or equal to a nanosecond.

# Answer
> 1 votes
# 8086 .COM, 10(11?) bytes

```
0100 31DB          XOR     BX,BX
0102 4B            DEC     BX
0103 FE0F          DEC     BYTE PTR [BX]
0105 74FB          JZ      0102
0107 E9F6FF        JMP     0100

```

Run for \\$256^{65270}\\$ steps (assuming all left space are zero) then change `JMP 0100` into `JMP 0000`, aka. `INT 20H`. If the left space is possibly full of `01`, then an extra `00` can be followed after `JMP`, having at least \\$255 \times 256^{65269}\\$ steps.

# Answer
> 0 votes
# Runic Enchantments, ~1823 bytes

```
\DB͍R"000000000000000000000000000000000000001"$
.{ww;'''''''''''''''''''''''''''''''''''''''
.10{BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
a+'0000000000000000000000000000000000000000
kk0~111111111111111111111111111111111111111
$:{~+++++++++++++++++++++++++++++++++++++++
1'~}567890123456789012345678901234567890123
J://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
.=? 000001111111112222222222333333333344444
/\/v\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

```

Try it online!

Or rather, some arbitrarily large variation thereof. Taken from this answer where an explanation on how it works can be found. Additionally, running this "in perpetuity" would require a version of the interpreter which does not self-halt after 1,000,000 execution steps, but I will assume this as true as the unobtaining machine the code is running on as it only requires an adjustment to one line of code.

According to TIO this can print numbers out to 100 in about 0.141s (the flux here is almost irrelevant in terms of the final result: +/- ~10 bytes for being 10 times faster or slower for needing an extra digit of precision). So reaching 99999999999999999999999999999 should take about 4,471,080,669,710,806,697 (1018) years...and ten of its most significant decimals would still be `0`, which bumps things to 1028 years. Depicted code only has 39 digits worth of precision in base-10 and we can go bigger.

Only one byte different takes it to an effective base 78 (with a maximum value around 6x1073). Tweaking the "0" down to the lowest allowable character ("#") brings that to base 92 (with a maximum value around 4x1076).

That brings us to needing a 515 digit base 92 number, which is also doable using the `´` command to need only n+1 cells to represent a base 10 number with n digits (for the purposes of `w`rite location offsets), e.g. this program changes the `4X3+` to `4´3`, and as long as an empty row of cells is supplied between the column value (~1 byte per digit for all the spaces in order to allow for 3 digit numbers) and the `10B` command any value can be expressed and needing approximately 5722 bytes.

However, we can still raise the integer base a bit more. `˿` is the last non-combining Unicode value accessible without performing any additional logic checks, allowing for a base 733 number which means that we only need 353 digits of precision, reducing the program size of about 3940 bytes.

But we can still go smaller still.

35-767 is not the largest unicode block usable without needing additional logic. If we instead use Unicode values 880 to 6831 (inclusive) we have an effective base of 5953, requiring only 268 digits of precision. Accounting for the two bytes needed to represent the initial characters, that gives a program size of approximately 3275 bytes.

Adding in the additional logic would allow for a maximum base of 64654, requiring only 211 digits of precision and costing only another 79 bytes or so based on this answer.

But we can still golf a few bytes. Remember the `´` command? We don't really need it. Now that we're down to only a 211 digit number, all the values needed (up to 216) can be represented with only 2-3 bytes (instead of 5): char values implicitly convert to integers when required in any command that expects integers and nearly all the chars needed (from 5 to 216) can be utilized in this manner. Only 10, 60, 62, 94 and 118 are problematic. And all of them can still be expressed in 4 bytes or less:

```
10  -> a
60  -> 6X
62  -> 6X2+
94  -> 9x4+
118 -> bX8+

```

For 62, 94, and 118 it ends up being easier to just not use those columns. Increases program size by 8 bytes each (24 bytes) in order to not need the spaces to align the commands out to 118 (236 bytes).

## Final score: 1823 bytes.

```
211 digit number      -  1 byte per digit of initial value
Programmatic overhead -  56 bytes (roughly, the left 4 columns and right 3 columns)
Digit processing      -  7 bytes * digits (1477 bytes)
Bad Character logic   -  ~79 bytes (some additional control flow is likely required)

```

(Intermediate values were approximated at 10 bytes (original program height) per digit of initial value +57 +unicode penalty where appropriate: eg. 1 byte per digit of initial value +1 or +2 for representation in programmatic overhead).

### Final thoughts:

It may be possible to turn this answer into a self-repeating execution instead of a quine, but I have so far not had success getting it to `E`val properly. I suspect that it attempts to Eval the string and the parser throws an error for some reason. If that were fixed, a shorter solution to the "take forever" problem would be possible: push the quine, duplicate, Eval, compare with original (lossless). If not the same: loop, else terminate. The number of Eval attempts (i.e. the original period count) is already near the number of years required by this challenge, so increasing the number of loops by a factor of ~32 billion (iteration -\> years) seems relatively doable in less than 1300 bytes. Increasing the program length from 387 "digits" to 485 "digits" looks like it would be enough.

# Answer
> 0 votes
# Pyt, 4 bytes

```
9ṖṖṖ

```

Try it online!

Inspired by xnor's Python answer, this calculates:

x=9^9

y=x^x

z=y^y

and then returns z. according to WolframAlpha, this is around 10^(10^9.52208) bits, which is more bits than his program has, and therefore will require more time.

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


# Question
Title: Determine whether a number is 2017-friable without primes in your source code
Out of all the years I've been making this challenge, 2017 is the first year that's been a prime number. So the question will be about prime numbers and their properties.

Your task is to produce a program or function that will take an arbitrarily large positive integer as input, and output or return whether or not the number is *2,017-friable* — that is, whether the largest prime factor in that number is 2,017 or less.

---

Some example inputs and their outputs:

```
1 (has no prime factors)
true

2 (= 2)
true

80 (= 2 x 2 x 2 x 2 x 5)
true

2017 (= 2017)
true

2019 (= 3 x 673)
true

2027 (= 2027)
false

11111 (= 41 x 271)
true

45183 (= 3 x 15061)
false

102349 (= 13 x 7873)
false

999999 (= 3 x 3 x 3 x 7 x 11 x 13 x 37)
true

1234567 (= 127 x 9721)
false

4068289 (= 2017 x 2017)
true

```

Your program does not have to literally output `true` and `false` — any truthy or falsy values, and in fact any two different outputs that are consistent across true and false cases are fine.

---

However, you may not use any *primes* in your source code. Primes come in two types:

* Characters, or sequences of characters, that represent prime number literals.

+ The characters `2`, `3`, `5`, and `7` are illegal in languages where numbers are valid tokens.
    + The number `141` is illegal because it contains `41`, even though `1` and `4` are otherwise valid.
    + The characters `B` and `D` (or `b` and `d`) are illegal in languages where they are typically used as 11 and 13, such as CJam or Befunge.
* Characters that have prime-valued Unicode values, or contain prime-valued bytes in their encoding.

+ The characters `%)+/5;=CGIOSYaegkmq` are illegal in ASCII, as well as the carriage return character.
    + The character `ó` is illegal in UTF-8 because its encoding has `0xb3` in it. However, in ISO-8859-1, its encoding is simply `0xf3`, which is composite and therefore okay.

The shortest code to do the above in any language wins.

# Answer
# Jelly, 8 bytes

```
44‘²!*ḍ@

```

Try it online! Note that test cases **11111** and above are a bit too much for TIO.

### Verification

```
$ source="34,34,fc,82,21,2a,d5,40"
$ xxd -ps -r > 2017.jelly <<< $source
$ xxd -g 1 2017.jelly
0000000: 34 34 fc 82 21 2a d5 40                          44..!*.@
$ eval printf '"%d "' 0x{$source}; echo # Code points in decimal
52 52 252 130 33 42 213 64
$ test_cases="1 2 80 2017 2019 2027 11111 45183 102349 999999 1234567 4068289"
$ for n in $test_cases; do printf "%11d: %d\n" $n $(jelly f 2017.jelly $n); done
      1: 1
      2: 1
     80: 1
   2017: 1
   2019: 1
   2027: 0
  11111: 1
  45183: 0
 102349: 0

```

Test case **999999** has been running for 13 hours. I'm pessimistic about computing **2025!4068289**...

### How it works

```
44‘²!*ḍ@  Main link. Argument: n

44        Yield 44.
  ‘       Increment to yield 45.
   ²      Square to yield 2025.
          Note that no integers in [2018, ..., 2025] are prime numbers.
    !     Take the factorial of 2025.
     *    Raise it to the n-th power.
          This repeats all prime factors in 2025! at least n times, so the result
          will be divisible by n if (and only if) all of its prime factors fall
          in the range [1, ..., 2025].
      ḍ@  Test the result for divisibility by n.

```
> 39 votes

# Answer
# Jelly, 8 characters, 14 bytes of UTF-8

```
Æf½ṀḤ<90

```

Try it online!

Jelly normally uses its own codepage for programs. However, most of its prime-related builtins start with `Æ`, which is codepoint 13; not very helpful. Luckily, the interpreter also supports UTF-8, which has a friendlier encoding.

## Verification

This program, in UTF-8, hexdumps like this:

```
00000000: c386 66c2 bde1 b980 e1b8 a43c 3930  ..f........<90

```

Verification that all the bytes are composite:

```
$ for x in c3 86 66 c2 bd e1 b9 80 e1 b8 a4 3c 39 30; do factor $((0x$x)); done
195: 3 5 13
134: 2 67
102: 2 3 17
194: 2 97
189: 3 3 3 7
225: 3 3 5 5
185: 5 37
128: 2 2 2 2 2 2 2
225: 3 3 5 5
184: 2 2 2 23
164: 2 2 41
60: 2 2 3 5
57: 3 19
48: 2 2 2 2 3

```

Verification that all the Unicode codepoints are composite:

```
$ perl -Mutf8 -E '$a = ord, print `factor $a` for split //, "Æf½ṀḤ<90"'
198: 2 3 3 11
102: 2 3 17
189: 3 3 3 7
7744: 2 2 2 2 2 2 11 11
7716: 2 2 3 643
60: 2 2 3 5
57: 3 19
48: 2 2 2 2 3

```

The only token parsed as a number is `90`. None of `9`, `0`, and `90` are prime.

## Explanation

The main mathematical insight here is that 45² is 2025, which neatly falls between 2017 (the current year) and 2027 (the next prime). Thus, we can take the square root of every prime factor of the number, and see if any exceeds 45. Unfortunately, we can't write `45` due to the literal `5`, so we have to double it and compare to 90 instead.

```
Æf½ṀḤ<90
Æf        In the list of prime factors,
  ½       taking the square root of each element
   Ṁ      then taking the largest element
    Ḥ     and doubling it
     <90  produces a result less than 90.

```
> 12 votes

# Answer
# Mathematica, ~~62~~ ~~58~~ 55 bytes

*The last three bytes saved are totally due to Martin Ender!*

```
#4<4||#<44*46&&#6[#^-1#4]&[Divisors[#][[6-4]],,,#,,#0]&

```

Unnamed function taking a positive integer argument and returning `True` or `False`.

Recursive algorithm, with `#4<4` being the truthy base case (we only need it to return `True` on the imput 1, but the extra base cases are fine). Otherwise, we compute the second-smallest divisor (which is necessarily prime) of the input with `Divisors[#][[6-4]]`; if it's greater than 2024 (`44*46`) then we exit with `False`, otherwise we call the function recursively (using `#6` set to `#0`) on the input divided by this small prime factor `#` (which we have to express as `#^-1` times the input `#4`, since `/` is disallowed).

Structurally, the first half `#4<4||#<44*46&&#6[#^-1#4]&` is an anonymous function of six arguments, being called with arguments `Divisors[#][[6-4]]`, `Null`, `Null`, `#`, `Null`, and `#0`; this is to get around the prohibition on the characters `2`, `3`, and `5`.

Previous version, which saved four bytes by replacing `8018-6000` with `44*46`, inspired by ais523's Jelly answer (Martin Ender also seemed inspired by an ais523 comment):

```
#<4||Divisors[#][[6-4]]<44*46&&#0[Divisors[#][[6-4]]^-1#]&

```

This was pretty nasty: I still don't know a way to actually set a variable in Mathematica under these restrictions! Both `=` and the `e` in `Set` are disallowed. Avoiding `+` and `)` was also an issue, but not too hard to work around at the expense of more bytes.
> 11 votes

# Answer
# Haskell, ~~48~~ 47 bytes

```
\n->[snd$[product[1..44*46]^n]!!0`divMod`n]<[1]

```

Basically a translation of Dennis’ Jelly answer. xnor saved a byte.

Uses `[…]!!0` as parentheses because `)` is banned, and `snd` \+ `divMod` because the `m` in `mod` and `rem` is banned.
> 7 votes

# Answer
## Pyke, ~~10~~ ~~8~~ ~~7~~ 9 bytes

```
P_Z|hwMX<

```

Try it here!

Saved 1 byte by using Dennis's way of generating 2025

```
P         -     factors(input)
 _        -    reversed(^)
  Z|      -   ^ or 0
    h     -  ^[0] or 1
        < - ^ < V
     wM   -  ⁴45 (ord("M")-32)
       X  -  ^**2

```
> 6 votes

# Answer
# Actually, 9 bytes

```
τyM:44u²≥

```

Thanks to Dennis for lots of bytes!

Try it online!

Explanation:

```
τyM:44u²≥
τyM        largest prime factor of 2*input (doubled to deal with edge case of n = 1)
   :44u²   2025 (2027 is the next prime after 2017, so any number in [2017, 2026] can be used here - 2025 is very convenient)
        ≥  is 2025 greater than or equal to largest prime factor?

```
> 5 votes

# Answer
## Mathematica, 66 74 bytes

*Thanks to Dennis for pointing out that `U+F4A1` is prohibited.*

```
Fold[Function[{x,d},And[x,Tr[Divisors@d^0]>6-4||d<44*46]],0<1,Divisors@#]&

```

Explanation:

`Divisors@#`: List of integer divisors of the first argument `#`.

`0<1`: Golf for `True` (also avoids the use of the letter `e`).

`Divisors@d^0`: List of the form `{1, 1, ..., 1}` with length equal to the number of divisors of `d`.

`Tr`: For a flat list, `Tr` returns the sum of that list. Thus `Tr[Divisors@d^0]` returns the number of divisors of `d`.

`Function[{x,d},And[x,Tr[Divisors@d^0]>6-4||d<44*46]]`: Anonymous function with two arguments `x` and `d`. The idea is that `d` is a divisor of `#` and we test to see if it is either composite or less than or equal to `2017` (inclusive). `2017`-friability is equivalent to all the divisors satisfying this condition. As ais523 discovered, being a prime less than or equal to `2017` is equivalent to being a prime less than `2025`. As Greg Martin pointed out, it suffices to test whether it is less than `2024=44*46`. The argument `x` acts as an accumulator for whether all of the divisors encountered so far satisfy this property. We then left `Fold` this function through all of the divisors of `#` with starting value `True`, since we have access to neither `Map` nor `/@`.
> 5 votes

# Answer
# Brachylog, ~~9~~ 10 bytes

```
*$ph$r*<90

```

Try it online!

Basically using the same algorithm as my other answer. `$ph` finds the first (`h`) prime factor (`$p`); this is the largest prime factor, as Brachylog's prime factor lists go from largest to smallest. Then I take the square root (`$r`), double (`*`), and test to see if it's less than 90 (`<90`).

I had to double the input first because 1 has no prime factors (and thus no first prime factor). This adds an extra prime factor of 2, which can't affect whether a number is 2017-friable, but prevents a failure when handling 1.
> 5 votes

# Answer
# 05AB1E, 10 bytes

```
fθ46n99-›È

```

Returns 1 if true, 0 otherwise.

Try it online!

**Explanation**

```
f          # Push the list of prime factors (ordered)
 θ         # Get the last element
  46n99-   # Push 2017 (46² - 99)
        >  # Push 1 if the last prime factor is greater than 2017, 0 otherwise
         È # Is the resulting number even ? Transforms 1 to 0 and 0 to 1.
           # Implicit display

```
> 4 votes

# Answer
# MATL, 15 bytes

```
t:\~ftZp*44QU<A

```

Outputs `0` for non-2017-friable or `1` for 2017-friable.

Try it online! Or verify all test cases.

This program checks that all bytes are composite.

### Explanation

```
t       % Implicit input n. Duplicate
:       % Range [1 2 ... n]
\       % Modulo. Gives 0 for divisors of n
~f      % Indices of zero values
t       % Duplicate
Zp      % Is-prime. Gives 1 for primes, 0 for composites
*       % Multiply
44QU    % 44, add 1, square: 2025
<       % Less than, element-wise
A       % True (1) if all entries are nonzero

```
> 1 votes

# Answer
# Bash, 144 bytes

ASCII encoding:

```
{
printf '[ '
`tr D-Z _-z <<<KFH`tor $1|tr -d :|`tr B-Z _-z <<<JUH`p -o '[0-9]*$'
printf ' -lt $[24*86-46] ]'
}|tr \\n \ |`tr B-Z _-z <<<EDVK`

```

As usual for shell, the exit code indicates success (0) or failure (non-0).

This is effectively a different spelling of

```
[ factor $1|tr -d :|grep -o '[0-9]*$' -lt 2018 ]

```

We get the largest factor with `factor $1|grep -o '[0-9]*$'`; the `tr -d :` is to special-case for input = `1`.

The expression `$[6*6*69-466]` evaluates to 2018.

It was tricky to use `tr` for the command names and still use command substitution - I couldn't use the nesting form `$( )`, so I ended up piping into another Bash to evaluate the result.

Test results:

```
$ for i in 1 2 80 2017 2019 2027 11111 45183 102349 999999 1234567 4068289; do printf '%d %s\n' $i `./105241.sh $i  && echo true || echo false`; done
1 true
2 true
80 true
2017 true
2019 true
2027 false
11111 true
45183 false
102349 false
999999 true
1234567 false
4068289 true

```

Confirmation of character codes:

```
$ grep -v '^#' ./105241.sh | perl -n -Mutf8 -E '$a = ord, print `factor $a` for split //, $_' | grep -v ': .* ' | wc -l
0

```
> 1 votes

# Answer
# Pyt, ~~21~~ 19 bytes

```
ϼ↕1⦋91+₂⬠1+Đ1+⬠⇹₂->

```

Try it online!

This uses Pyt's custom encoding, in which all of the characters used are non-prime bytes. It returns `false` if the number IS 2017-friable, and `true` if it is not.

| code | action |
| --- | --- |
| `ϼ` | gets the unique prime factors of the input |
| `↕1⦋` | gets the largest of those |
| `91+₂⬠1+Đ1+⬠⇹₂-` | pushes 2017 |
| `>` | is the largest prime factor greater than 2017?; implicit print |
> 1 votes

# Answer
# Pyth, 11 bytes

```
!s>R^h44h1P

```

Try it online. Test suite.

Uses Dennis's trick to get 2025, then checks if no prime factors of input are greater.
> 0 votes

# Answer
# Julia 0.4, ~~84~~ ~~38~~ 37 bytes

```
n->1^n:44*46|>prod|>t->t^n-t^n÷n*n<1

```

Expects a *BigInt* as argument.

Try it online! or verify that no byte is prime.
> 0 votes

# Answer
# Japt, 14 bytes

```
k æ¨44*46 ?0:1

```

Returns 1 if true, 0 if false.

Try it here.
> 0 votes

# Answer
# Braingolf, 11 bytes \[very non-competing\]

```
VRp#ߢ-?0:1

```

Try it online!

Unreadable due to the `ߢ` which screws with the numbers, however still works in an interpreter.

I didn't even notice the character restrictions when I wrote this, but all I had to do was change the weird unicode character from 2017 to 2018.

Given 2018 is not a prime, any prime `<= 2018` is also `<= 2017`

### Explanation

```
VRp#ߢ-?0:1  Implicit input from command-line args
VR            Create stack2, return to stack1
  p           Split last item into prime factors, push each one to stack in asc order
   #ߢ         Push 2018
     -      Subtract last 2 items (highest prime factor - 2017)
      ?     If last item > 0..
       0    ..push 1
        :   Else..
         1  ..Push 1
            Implicit output of last item on stack

```
> 0 votes

# Answer
# Japt `-!`, 12 bytes

Japt gets jipped here 'cause `k` is our built-in for prime factors, and `#` converts characters to their codepoints.

```
â fj d¨44*46

```

Try it
> 0 votes

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


title: Adaptive randomisation

text:
# Question
Title: Adaptive randomisation
Given a number \\$n ≥ 2\\$, a blackbox function \\$f\\$ that takes no arguments and returns a random integer in the range 0...n-1 inclusive, and a number \\$m ≥ n\\$, your challenge is to generate a random integer in the range 0...m-1 inclusive. You may not use any nondeterministic builtins or behaviour, your only source of randomisation is \\$f\\$.

The number you produce must be uniformly random. \\$m\\$ is not limited to powers of \\$n\\$.

One way to do this could be to generate \\$\operatorname{ceil}(\log\_n(m))\\$ random numbers, convert these from base \\$n\\$ to an integer, and reject-and-try-again if the result's greater than or equal to \\$m\\$. For example, the following JS could do this:

```
function generate(n,m,f){
  let amountToGenerate = Math.ceil(Math.log(m)/Math.log(n)) // Calculating the amount of times we need to call f
  let sumSoFar = 0;
  for(let i = 0; i < amountToGenerate; i++){  // Repeat that many times...
    sumSoFar *= n;            // Multiply the cumulative sum by n
    sumSoFar += f()           // And add a random number
  }
  if(sumSoFar >= m){          // If it's too big, try again
    return generate(n,m,f);
  } else {                    // Else return the number regenerated
    return sumSoFar
  }
}

```

An *invalid* solution could look something like this:

```
function generate(n,m,f){
  let sumSoFar = 0;
  for(let i = 0; i < m/n; i++){ // m/n times...
    sumSoFar += f()             // add a random number to the cumulative sum
  }
  return sumSoFar
}

```

This is invalid because it takes the sum of \\$\frac{m}{n}\\$ calls of f, so the randomness is not uniform, as higher/lower numbers have a smaller chance of being returned.

\\$f\\$ is guranteed to produce uniformly random integers, and can be independently sampled as many times as you want.

Instead of taking \\$f\\$ as a function, you may also take it as a stream or iterator of values, or an arbitrarily long list of values. The ranges may be 1...n instead of 0...n-1.

## Scoring

This is , shortest wins!

# Answer
# Jelly, ~~6~~ 5 bytes

```
ÇÐṀḊ¿

```

Try it online!

A monadic link taking `m` as its argument and expecting the blackbox function to be in the previous link (e.g. header on TIO). Thanks to @JonathanAllan for pointing this out as per this meta post and also for saving a byte with a suggested switch to 1 indexing!

## Explanation

```
      | Implicit range 1..m
   Ḋ¿ | While list length > 1 (literally while the list with its first member removed is non-empty):
 ÐṀ   | - Take the list member(s) that are maximal when:
Ç     |   - The supplied function is run for each list member

```

---

If the function had to be provided as an argument, here is an alternative:

# Jelly, 8 bytes

```
ṛ⁴V$ÐṀḊ¿

```

Try it online!

A full program taking `m` and the Jelly code for `f` as its two arguments. If it’s mandatory to also take `n`, this can be provided as an (unused) third argument.

## Explanation

```
          | Implicit range 1..m
       Ḋ¿ | While list length > 1 (literally while the list with its first member removed is non-empty):
    $ÐṀ   | - Take the list member(s) that are maximal when:
 ṛ⁴V      |   - The supplied function is run for each list member

```

---

# Previous answer: Jelly, 16 bytes

```
³lĊ⁵V¤€ḅʋ⁴¤<³¬$¿

```

Try it online!

A full program that takes `n`, `m` and the Jelly code for `f` as its arguments and prints the resulting random number to STDOUT.

## Explanation

```
           <³¬$¿ | While not < m:
³       ʋ⁴¤      | - Do the following, taking m as the left argument and n as the right:
 l               |   - m log n
  Ċ              |   - Ceiling
   ⁵V¤€          |   - Execute f that many times
       ḅ         |   - Convert from base n

```
> 7 votes

# Answer
# , 37 32 26 bytes

```
1 :'$:@[`]@.(=&#)I.@:u@$~'

```

Try it online!

-6 bytes thanks to xnor's suggested method.

Will overflow the stack for larger inputs since it recurses, but works in theory.

# base-n method, modified, 37 32 bytes

```
1 :'([#.u@#~)/@[^:(]>:1{[)^:_&_'

```

Try it online!

Uses suggested method, except instead of taking the log first just generates m random base-n digits. This makes it *much* slower, but saves 5 bytes.

The solution is a J adverb, which modifies the black box function, and takes `n` as the left arg and `m` as the right arg.

# base n method, fast, 37 bytes

```
1 :'([#.>.@^.u@#[)/@[^:(]>:1{[)^:_&_'

```

Try it online!
> 5 votes

# Answer
# Wolfram Language (Mathematica), ~~40~~ 39 bytes

```
r&@While@!(r=Nest[nn#3+#2[],0,#])<#&

```

Try it online!

Input `[m, f, n]`. Interprets `m` random digits in base `n` until the result is in `[0, m)`.
> 5 votes

# Answer
# Japt, ~~12~~ 10 bytes

Based on xnor's suggested method in the challenge comments. Takes `m` as the first input `n` as the second and assigns `f` to variable `W`. Outputs a singleton array

```
ÈÊÉ}f@oW ð

```

Try it or check the distribution over 1000 runs (warning: may take a while to complete)
*(All 3 inputs are taken in the header, where each line is assigned to one of Japt's input variables in order. The first line is `m`, the second `n` and the 3rd `f`. Doing this makes no difference to the main programme, saving no bytes; it's done purely to keep everything in one place for easier testing as functions cannot be taken as direct input by Japt.)*

## Black box function W

```
{Vö     :Implicit input of integer V=n
{       :Function
 Vö     :  Random int in [0,V)

```

## Main programme

```
ÈÊÉ}f@oW ð     :Implicit input of integer U=m
È              :Left function, taking an array as argument
 Ê             :  Length
  É            :  Subtract 1
   }           :End left function
    f          :Run the right function continuously, returning the first result that returns falsey (0) when passed through the left function
     @         :Right function
      o        :  Range [0,U)
       W       :  Run each through W
         ð     :  0-based indices of truthy (non-zero) elements

```
> 4 votes

# Answer
# Husk, ~~17~~ ~~15~~ 13 bytes

*Thanks to xnor for the inspiration for the method: here it's taken to an even-more-inefficient extreme by repeatedly generating `m` random numbers until all except one are zero, and the only non-zero one is 1*

```
€1ḟo=1ΣCm`%₁∞

```

Try it online!

Husk is usually rather badly-suited for challenges involving randomness, since it has no built-in random number generator. So it's very welcome to have a challenge where a random number generator is assumed as a black-box function!

In this case, the black-box random number function is assumed to be located on line 2 (called using the Husk command "").
However, obviously, without actually having this function it's tricky to test the code, so the TIO link substitutes the last few bytes `m`%₁∞` and input `n` for a pre-generated-by-me list of random integers between zero and one (so `n` equals 2).

```
             ∞       # infinitely repeat arg1;
         m           # now, for each element n of this list
          `%₁        # call black-box function ₁, and return the result modulo n;
        C            # now cut this infinite list into sublists of length m = arg2
  ḟo                 # Return the first sublist for which
      Σ              # the sum
    =1               # is  equal to 1;
€1                   # what's the index of 1 in this sublist?

```

Note: the `m`%₁∞` construction to get the infinite list of random numbers might seem (and is) a bit clunky. This is because (I think), not having any non-deterministic functinos, Husk doesn't have or normally need a higher-order function that will repeat a particular function *that takes no arguments*.
Luckily in this case, we know that the output of our black-box function is unchanged modulo `n`, so we can 'use-up' an argument without changing the output.
Here's a Try it online link to the `m`%₁∞` bit on its own, here with a function on line 2 that simply returns the number `7` each time it's called. Try to pretend that this is a random number...
> 4 votes

# Answer
# , ~~70~~ ~~69~~ 62 bytes

**(or \>4.1, ~~56~~ 55 bytes)**

*Edit: -7 bytes thanks to pajonk*

```
function(m,f){while(sum(F)!=1)for(i in 1:m)F[i]=!f();which(F)}

```

Try it online!

Port of ~~my Husk answer~~ xnor's approach. Keeps generating sequences of `m` random numbers until we get one that contains a single `0`: then we output the position of the `0`. Obviously this is not very efficient, but at least its significantly better than waiting for sequences of all zeros with a single `1` (previous version)...

As explained by Nick Kennedy in his R answer, R\] version \>4.1 lets us exchange "`function`" for "`\`" to save 7 bytes, but unfortunately we can't link to it on TIO or rdrr.io (yet).
> 4 votes

# Answer
# Python 3.8 (pre-release), 72 bytes

```
f=lambda m,g:(l:=[g()for x in"1"*m]).count(1)==1and-~l.index(1)or f(m,g)

```

Try it online!

Uses @xnor's method

-6 and fix thanks to @ovs

Generates the blackbox function for m times, and try to pick the index of 0 from it, if not present recurse.

Looks like the relevant function Dosen't need to take n at all, because it is hardcoded inside g()

Also it is needed to check if list has only one zero, so the choosing remains uniform
> 3 votes

# Answer
# Haskell, ~~49~~ 47 bytes

```
m!l|[x]<-[x|(x,1)<-zip[1..m]l]=x|1>0=m!drop m l

```

Try it online!

Implements xnor's algorithm

> Make a list of \\$m\\$ outputs from \\$f\\$, if it has a single \\$0\\$ output its position, otherwise retry.

However we don't need to make a list since we take a list as the input.

We also use \\$1\dots n\\$ ranges because it saves us 2 bytes.
> 3 votes

# Answer
# \>= 4.1, ~~67~~ 64 bytes

```
\(m,f,x=1:m){while(x-max(x))x=x[max(y<-sapply(x,\(z)f()))==y];x}

```

Try it online!

An R translation of my Jelly answer. TIO link uses `function` in place of `\` since TIO isn’t on R 4.1 yet.

Thanks to @DominicVanEssen for saving 3 bytes!

If it were permissible to require that the Blackbox function take a single unused argument, this would do for 61:

# \>= 4.1, ~~64~~ 61 bytes

```
\(m,f,x=1:m){while(x-max(x))x=x[max(y<-sapply(x,f))==y];x}

```

Try it online!
> 3 votes

# Answer
# JavaScript (V8), ~~63~~ ~~61~~ 60 bytes

```
(m,f,r=(i=m,p)=>i?f()?r(i-1,p):p?r():r(i-1,i):p||r())=>r()-1

```

Try it online!

Using xnor's method. The recursive function `r(i,p)` counts down from `i = m` while `i > 0`. If finds a zero `f()` it records position `i` as `p` except if there is already a `p` it restarts by calling `r()`. If `i` gets to zero and there is a `p` it returns `p-1` as the result otherwise it restarts.
> 3 votes

# Answer
# Python 3.8 (pre-release), 70 bytes

```
h=lambda m,n,f:h(m,n,f)if(s:=sum(n**k*f()for k in range(m)))>=m else s

```

Try it online!

Generates a random number up to n^m (always larger than m) with n invocations of f, then retries if the result is \>=m.

Blows up the stack for large n and m, because n^m is *much* larger than m.
> 3 votes

# Answer
# Charcoal, 16 bytes

```
ＮθＷ⊖№υ⁰≔ＥθＮυＩ⌕υ⁰

```

Try it online! Link is to verbose version of code. Uses the method @xor suggested in a comment to the question. Takes `m` and a stream of random integers as input. Explanation:

```
Ｎθ

```

Input `m`.

```
Ｗ⊖№υ⁰

```

Repeat until the predefined empty list contains exactly one zero.

```
≔ＥθＮυ

```

Input `m` random integers to the predefined empty list.

```
Ｉ⌕υ⁰

```

Output the position of the zero.

24 bytes for fastest code:

```
ＮθＮη≔ηζＷ¬‹ζη≔↨Ｅ↨⊖ηθＮθζＩζ

```

Try it online! Link is to verbose version of code. Takes input as a stream of random integers. Explanation:

```
ＮθＮη

```

Input `n` and `m`.

```
≔ηζ

```

Start with `m` as the trial result (because we know it is too big).

```
Ｗ¬‹ζη

```

Repeat until a usable result is achieved.

```
≔↨Ｅ↨⊖ηθＮθζ

```

Input the minimum number of random digits (obtained by converting `m-1` to base `n`) and convert that to base `n`.

```
Ｉζ

```

Output the final random integer.
> 2 votes

# Answer
# C (gcc), ~~76~~ \\$\cdots\\$ ~~70~~ 67 bytes

```
i;c;g(n,m,f)int(*f)();{for(;n;)for(n=i=m;i--;)!f()?n-=m,c=i:0;n=c;}

```

Try it online!

Saved 3 bytes thanks to att!!!

Uses xnor's idea by repeatedly calling \\$f()\\$ \\$m\\$-times and if \\$f()\\$ returns \\$0\\$ once and only once, then returns the time (with \\$0\\$ being the last time and \\$m-1\\$ being the first) that \\$f()\\$ was \\$0\\$.
> 2 votes

# Answer
# APL(Dyalog Unicode), 19 bytes SBCS

Implements the algorithm suggested by xnor.

```
{⍸1=∘⍺⍺¨⍣{1=+/⍺}⍳⍵}

```

Try it on APLgolf!

The blackbox function is called with dummy arguments it ignores, which I think should be fine as there is no way to pass a niladic function to an operator.

`⍳⍵` create a range from 1 to n

`¨` for each value in the current list ...
`⍺⍺` call the blackbox function ...
`1=` and compare the result to 1 ...
`⍣{1=+/⍺}` until the result sums to 1

get all indices of 1's in the resulting boolean mask. This returns a singleton value

3 bytes can be saved by using a full program instead of a *dop*, but this is quite inconvenient to use:

```
⍸1=∘⎕¨⍣{1=+/⍺}⍳⎕

```

Try it on APLgolf!
> 2 votes

# Answer
# Ruby, 60 bytes

```
f=->n,g,m,r=0,z=1{z>m ?r<m ?r:f[n,g,m]:f[n,g,m,r*n+g[],z*n]}

```

Try it online!

Use the log() approach, with a recursive function: `z` is the maximum possible random number for a given iteration, `r` is the current accumulated value.
> 2 votes

# Answer
# JavaScript (Node.js), 60 bytes

```
(n,f,m)=>(g=p=>p*m/d^-~p*m/d?g(p*n+f(),d*=n):p*m/d)(0n,d=1n)

```

Try it online!

Signature: `(n: BigInt, f: () => BigInt, m: BigInt) => BigInt`

Input / Output `BigInt` values.

---

And it would be 47 bytes if we can assume infinite precision of floating point numbers:

```
n=>f=>g=(m,p=0)=>p*m^-~p*m?g(m/n,p*n+f()):p*m|0

```

Try it online!
> 2 votes

# Answer
# JavaScript, ~~55~~ 53 bytes

Takes arguments by currying, i.e. `f(r)(m)`, where `r` is the black-box randomisation function. The first 3 bytes could be removed by stipulating that the function be pre-assigned to `r`.

```
r=>g=(m,y=x=m)=>y?g(m,--y,r()||(--x,z=y)):m+~x?g(m):z

```

Try it online! (change the values of `n` & `m` in the header)
> 2 votes

# Answer
# Vyxal, 29 bytes

```
{|n÷£$•⌈(¥†⅛)¾nhβ:nṪt>nh(¼_)}

```

Try it Online!

This is a whole bunch of yucky stuff that is lowkey disturbing. I really need to make functions nicer to deal with in the rewrite.

A lambda submission, that takes a single argument, `[n, m, f]`.

## Explained

```
{|n÷£$•⌈(¥†⅛)¾nhβ:nṪt>nh(¼_)}
{|                             # while the top of the lambda stack is truthy:
  n÷                           #   push all the contents of the input onto the stack
    £                          #   and place "f" into the register.
     $•⌈                       #   push ceil(log_n(m))
        (¥†⅛)                  #   and that many times, push the result of f() onto the global array
             ¾                 #   push the global array, containing ceil(log_n(m)) numbers
              nhβ              #   and convert from base n
                 :nṪt>         #   push ^ > m
                      nh(¼_)   #   and clear the global array
                            }  # close the while loop (we need this because lambda submission)

```
> 1 votes

# Answer
# JavaScript (Node.js), 50 bytes

```
(r,n,m)=>g=(i=1,j=0)=>i<m?g(i*n,j*n+r()):j<m?j:g()

```

Try it online!

generate ceil(logn(m)) random numbers, convert these from base n to an integer, and reject-and-try-again if the result's greater than or equal to m.

# JavaScript (Node.js), 49 bytes

```
r=>g=(m,y=x=m)=>y?g(m,--y,r()?z=y:--x):1-x?g(m):z

```

Try it online!

From Shaggy's
> 1 votes

# Answer
# C (gcc), 59 bytes

```
r;c;g(n,m,f)int(*f)();{for(r=0,c=m;c--;r%=m)r=r*n+f();r=r;}

```

Try it online!
> 1 votes

# Answer
# JavaScript, 36 bytes

```
(n,m,f)=>(g=p=>p&&g(p-1)*n+f())(m)%m

```

Try it online!

This answer works in all JS versions after 2015

**Edit #1:** -3 bytes thanks to Shaggy
> 1 votes

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


title: Place a glider!

text:
# Question
Title: Place a glider!
This:

is a *Glider*.

In Conway's Game of Life, the glider is a famous pattern that rapidly traverses across the board. For today's challenge, we are going to draw an ASCII art Game of Life Board, and place a glider on it.

The board we are starting with is this:

```
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|

```

This board is made up entirely of pipes `|` and underscores `_`, and is 10x10. You must write a program or function that takes in two integers, 'x' and 'y', and outputs this same board with a glider at those coordinates. For example, if you had a glider at position `(1, 1)` (0-indexed), you must output the following:

```
|_|_|_|_|_|_|_|_|_|_|
|_|_|*|_|_|_|_|_|_|_|
|_|_|_|*|_|_|_|_|_|_|
|_|*|*|*|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|

```

You can assume that the glider will never be placed out of bounds, so both x and y will always be in the `[0-7]` range. You may also choose to take the coordinates 1-indexed, but you must specify this in your answer. In this, case the inputs will always be in the `[1-8]` range. Here are some examples (all 0-indexed):

```
0, 0:
|_|*|_|_|_|_|_|_|_|_|
|_|_|*|_|_|_|_|_|_|_|
|*|*|*|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|

7, 7:
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|*|_|
|_|_|_|_|_|_|_|_|_|*|
|_|_|_|_|_|_|_|*|*|*|

7, 4:
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|*|_|
|_|_|_|_|_|_|_|_|_|*|
|_|_|_|_|_|_|_|*|*|*|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|

5, 2:
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|*|_|_|_|
|_|_|_|_|_|_|_|*|_|_|
|_|_|_|_|_|*|*|*|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|_|_|_|

```

As usual, you may take your IO in any reasonable format. This includes, but is not limited to a string with newlines, an array of strings, a 2d array of strings, or writing to a file/STDOUT. You may also choose what order to take *x* and *y* in.

Since this is , standard loopholes are banned, and make the shortest code that you can!

# Answer
> 7 votes
# MATL, ~~35~~ ~~32~~ 30 bytes

```
20*+'|_'5E:21:I$)42b' 34'Q+(

```

The code contains unprintable chars. Input is 0-based. **Try it online!**

# Answer
> 6 votes
# , ~~31~~, 30 bytes

```
10O±°_|ÀGjjÀ|3r*kr*kh.Í*ü_/|&

```

Try it online!

Hexdump:

```
00000000: 3130 4fb1 b05f 7c1b c047 6a6a c07c 3372  10O.._|..Gjj.|3r
00000010: 2a6b 722a 6b68 2ecd 2afc 5f2f 7c26       *kr*kh..*._/|&

```

This takes input as program arguments, and 1-indexed.

Explanation:

```
10O                         " On the following 10 lines, insert:
   ±°_                      "   10 '_' characters
      |                     "   And a '|'
       <esc>                " Return to normal mode
            ÀG              " Go to the a'th line
              jj            " Move down two lines
                À|          " Go to the b'th column
                  3r*       " and replace the next 3 characters with asterisks
                     k      " Move up a line
                      r*    " And replace this char with an asterisk
                        kh  " Move up a line and to the left
                          . " And repeat the last change we performed (replace with asterisk)
                            "
Í                           " On every line, substitute:
 *                          "   An asterisk
  ü                         "   OR
   _                        "   An underscore
    /                       " With:
     |&                     "   A bar followed by the matched pattern

```

# Answer
> 4 votes
# Java 10, ~~165~~ ~~144~~ ~~138~~ ~~135~~ ~~129~~ ~~127~~ 125 bytes

```
x->y->{var r="";for(int i=0,j;++i<11;r+="|\n")for(j=0;j<10;)r+=i==x&j==y|i==x+1&++j==y|i==x+2&j<y+3&j>=y?"|*":"|_";return r;}

```

1-indexed.

-14 bytes thanks to *@ceilingcat*.

**Explanation:**

Try it here.

```
x->y->{               // Method with two integer parameters and String return-type
  var r="";           //  Result-String, starting empty
  for(int i=0,j;i<10  //  Loop over the rows:
      ;               //    After every iteration:
       r+="|\n")      //     Append a "|" and newline to the result-String
    for(j=0;++j<11;)  //   Inner loop over the columns:
      r+=i==x&j==y|i==x+1&++j==y|i==x+2&j<y+3&j>=y?
                      //    If this coordinate should contain a '*'
        "|*"          //     Append "|*" to the result-String
       :              //    Else:
        "|_");        //     Append "|_" to the result-String
  return r;}          //  Return the result-String

```

# Answer
> 3 votes
# Perl 5, 67 bytes

```
sub{map{($_-join('',@_)~~[1,12,20..22]?"|*":"|_")."|\n"x/9$/}0..99}

```

Try it online!

Input Parameters: y, x

# Answer
> 2 votes
# Jelly, ~~37~~ 35 bytes

```
ȷ2b1
Ḍ+“£Æßæç‘Ṭ+¢s⁵j3;0$€Fṭ0ị“_*¶|”

```

Try it online!

**How it works**

```
ȷ2b1                             - the literal [1,1,1,1,...,1,1,1] with 100 elements
Ḍ+“£Æßæç‘Ṭ+¢s⁵j3;0$€Fṭ0ị“_*¶|”   - input (x,y)
Ḍ                                - convert (x,y) to 10*x+y
 +                               - add, to get the five "*" positions,
  “£Æßæç‘                        - the literal [2,13,21,22,23]
         Ṭ                       - return an array with those positions as truthy elements
          +¢                    - Now we format: pad to length 100 with the above literal
            s⁵j3                 - add newlines (represented by 3) to each set of 10
                ;0$€F            - add pipes (represented by 0) to each
                     ṭ0          - add a 0 to the beginning
                       ị“_*¶|”   - index into the string “_*¶|”

```

# Answer
> 2 votes
# Python 2, 151 bytes

Will golf more.

```
def f(x,y):r,x=[list('|_'*10+'|')for i in[1]*10],x*2;r[y][x+3]=r[y+1][x+5]=r[y+2][x+1]=r[y+2][x+3]=r[y+2][x+5]='*';print'\n'.join(''.join(i)for i in r)

```

Try it online!

# Answer
> 2 votes
# Perl 6, 88 bytes

```
->\x,\y{(^10 »*»i X+ ^10).map:{<|* |_>[$_!=
(1-2i|2-i|0|1|2)+x+y*i+2i]~"|
"x(.re==9)}}

```
* Complex numbers are used to represent the coordinates.
* `^10 »*» i X+ ^10` generates the grid of all complex numbers with integer components from zero through nine.
* Returns a list of strings, each one holding one line.

# Answer
> 2 votes
# Ruby, 87 bytes

```
->x,y{[a=(b='|_')*10+?|]*y+%w(|_|*|_ |_|_|* |*|*|*).map{|r|b*x+r+b*(7-x)+?|}+[a]*(7-y)}

```

Try it online!

# Answer
> 2 votes
# JavaScript (ES6), 99 bytes

```
x=>y=>eval('for(i=0,o="";i<101;o+=((d=i-x-y*10)==1|d==12|d>19&d<23?"|*":"|_")+(++i%10?"":`|\n`))o')

```

Takes input via currying: `f(5)(2)` for x=5, y=2. Coordinates are zero-indexed.

## Test Snippet

```
f=
x=>y=>eval('for(i=0,o="";i<101;o+=((d=i-x-y*10)==1|d==12|d>19&d<23?"|*":"|_")+(++i%10?"":`|\n`))o')

xi.oninput=yi.oninput=_=>O.innerHTML=f(xi.value)(yi.value)
O.innerHTML=f(xi.value=5)(yi.value=2)
```

```
<style>*{font-family:Consolas;}input{width:2.5em;}</style>
x: <input id="xi" type="number" min="0" max="7">,
y: <input id="yi" type="number" min="0" max="7">
<pre id="O">
```

# Answer
> 2 votes
# APL (Dyalog Extended), 40 bytes

```
'*'@((⍳2)∘×¨⎕∘+¨⍸⊤1 5 3)⊢'|',⍨10 20⍴'|_'

```

Try it online!

A full program, accepting x and y as input.

Calculate coordinates, and uses `@` to modify them.

# Answer
> 2 votes
# Python 3, 97 bytes

```
def f(x,y):
 b=(["|_"]*10+["|\n"])*10
 for c in[1,13,22,23,24]:b[c+11*y+x]="|*"
 return"".join(b)

```

Try it online!

# Answer
> 1 votes
## Mathematica, ~~115~~ 113 bytes

```
x(a="|_"~Table~10~Table~10;(a[[##]]="|*")&@@(#+x)&/@({{0,1,2,2,2},{1,2,0,1,2}});""<>Riffle[#<>"|"&/@a,"\n"])

```

where

This takes input in `{row, col}` format, and is 1-indexed, but can be turned into 0-indexed without adding bytes.

Some notes:

1. `\n` is a newline character, takes 1 byte.
2. is `\[Function]`, takes 3 bytes.
3. is `\[Transpose]`, takes 3 bytes.

Note that "array of string" is allowed, so I can just remove `Riffle`, gives

## Mathematica, ~~98~~ 97 bytes

```
x(a="|_"~Table~10~Table~10;(a[[##]]="|*")&@@(#+x)&/@({{0,1,2,2,2},{1,2,0,1,2}});#<>"|"&/@a)

```

# Answer
> 1 votes
# Haskell, 96 bytes

```
r=[0..9]
x#y=['|':(r>>=(\i->[last$'_':['*'|elem(i-x,j-y)$zip[1,2,0,1,2][0,1,2,2,2]],'|']))|j<-r]

```

Takes in two integers (`x` and `y`) and returns a list of `String`s, i.e. a 2D list of type `[[Char]]`.

---

**Test suite:**

```
import System.Environment

main :: IO ()
main = do
    args <- getArgs
    let (x, y) = (read $ args !! 0, read $ args !! 1)
    mapM_ putStrLn (x#y)

```

# Answer
> 1 votes
# Python 2, 133 bytes

```
x,y=input()
a=[[z for z in'_'*10]for o in'|'*10]
b=a[y+2]
a[y][x+1]=a[y+1][x+2]=b[x]=b[x+1]=b[x+2]="*"
for b in a:print o+o.join(b)+o

```

Try it online!

# Answer
> 1 votes
# Zsh, 85 bytes

try it online!

```
for i (2 13 21 22 23)G[i+$1$2]=*
for i ({1..100})printf \|${G[i]:-_}&&((i%10))||<<<\|

```

<sub>*Saved 12 bytes by moving the glider char `*` assignments to a function. Saved another 4 bytes by removing the function and adding a ternary to the `printf` stuff (at the expense of readability!). Saved another 7 by inlining some data instead of constructing an array. Saved another 10 by simplifying some expressions. Removed `{}` for another -1. Saved 11 by using parameter expansion `${name:-word}` instead of convoluted ascii logic.*
~~130 bytes~~ ~~118 bytes~~ ~~114 bytes~~ ~~107 bytes~~ ~~97 bytes~~ ~~96 bytes~~</sub>

# Answer
> 1 votes
# JavaScript, 98 bytes

Based on this answer

```
x=>y=>eval('for(i=0,o="";i<101;o+=(d=i-x-y*10)==1|d==12|d>19&d<23?"|*":"|_",o+=++i%10?"":`|\n`)o')

```

We can save 1 byte if use `o+=a,o+=b` instead of `o+=(a)+(b)`

Try it:

```
f=
x=>y=>eval('for(i=0,o="";i<101;o+=(d=i-x-y*10)==1|d==12|d>19&d<23?"|*":"|_",o+=++i%10?"":`|\n`)o')

xi.oninput=yi.oninput=_=>O.innerHTML=f(xi.value)(yi.value)
O.innerHTML=f(xi.value=5)(yi.value=2)
```

```
<style>*{font-family:Consolas;}input{width:2.5em;}</style>
x: <input id="xi" type="number" min="0" max="7">,
y: <input id="yi" type="number" min="0" max="7">
<pre id="O">
```

# JavaScript, 101 bytes

This answer may be more efficient with another pattern

```
x=>y=>eval("for(i=0,s='';i<101;s+=[1,12,20,21,22].includes(i-x-y*10)?'|*':'|_',s+=++i%10?'':`|\n`)s")

```

Try it:

```
f=
x=>y=>eval("for(i=0,s='';i<101;s+=[1,12,20,21,22].includes(i-x-y*10)?'|*':'|_',s+=++i%10?'':`|\n`)s")

xi.oninput=yi.oninput=_=>O.innerHTML=f(xi.value)(yi.value)
O.innerHTML=f(xi.value=5)(yi.value=2)
```

```
<style>*{font-family:Consolas;}input{width:2.5em;}</style>
x: <input id="xi" type="number" min="0" max="7">,
y: <input id="yi" type="number" min="0" max="7">
<pre id="O">
```

# Answer
> 0 votes
# SOGL, 23 bytes

```
LIΖ|_ΟL∙.«."¾'┼ΞΧ⌠²‘5nž

```

note: this expects input to be 1-indexed

Explanation:

```
LI                       push 11
  Ζ|_                    push "|" and "_"
     Ο                   make an altrenates string [with 11 separators, which are "|" and parts "_"]
      L∙                 get an array of 10 of those
        .«               take input and multiply by 2 (x pos)
          .              take input (y pos)
           "¾'┼ΞΧ⌠²‘     push "_|*|__|_|**|*|*" - the glider in the map
                    5n   split into an array with items of length 5
                      ž  replace in the 1st [grid] array at positions [inp1*2, inp2] to 2nd array [glider]

```

# Answer
> 0 votes
# Charcoal, 28 bytes

```
ＵＯ²¹χ|_Ｊ×Ｎ²Ｎ“ "}ＩyE%%mＬＢＭφ/”

```

Try it online! Link to verbose mode for description.

# Answer
> 0 votes
# Python 2, 97 bytes

```
def f(x,y):
 b=(["|_"]*10+["|\n"])*10
 for c in[1,13,22,23,24]:b[c+11*y+x]="|*"
 return"".join(b)

```

Try it online!

# Answer
> 0 votes
# QBasic, ~~113~~ 107 bytes

Uses 0-indexing.

```
INPUT x,y
s=11*y+x
FOR i=1TO 110
?"|"+CHR$(95+53*((i=s+2)+(i=s+14)-(i>s+22)*(i<s+26))+85*(i/11=i\11));
NEXT

```

We model the grid as 110 `|`s each followed by some character, for which we calculate the ASCII code:

* Every 11th character is a newline (character code 95 - 85 = 10)
* If we calculate the start index of the glider as `s = 11 * y + x`, then indices `s + 2`, `s + 14`, `s + 23`, `s + 24`, and `s + 25` are asterisks (character code 95 - 53 = 42)
* The rest are underscores (character code 95)

---

Original version using `LOCATE` (1-indexed):

```
INPUT x,y
CLS
FOR i=0TO 9
FOR j=0TO 9
?"|_";
NEXT
?"|
NEXT
LOCATE y,2*x+2
?"*
LOCATE,2*x+4
?"*
LOCATE,2*x
?"*|*|*

```

# Answer
> 0 votes
# Canvas, 24 bytes

```
|_Ａ×|＋Ａ＊ *¶  *¶***∙＊┘«╶╋

```

Try it here!

Takes 1-indexed position in form

```
x
y

```

as input.

Only beaten by dzaima's SOGL answer at time of writing.

# Answer
> 0 votes
# 05AB1E, 25 (or 24?) bytes

```
„|_ти„|*•A|,•₂вI+ǝTôJ€Ć»

```

0-based indexing.

Try it online or verify all test cases.

Could be 1 byte less (the `J`) if we could take the input-coordinates joined together as single integer:
Try it online or verify all test cases.

**Explanation:**

```
„|_            # Push string "|_"
   ти          # Repeat it 100 times as list of strings
„|*            # Push string "|*"
   •A|,•       # Push compressed integer 681976
        ₂в     # Convert it to base-26 as list: [1,12,20,21,22]
          IJ   # Push the input-pair, and join it together to an integer
            +  # Add it to each value in the list [1,12,20,21,22]
„|*          ǝ # Insert the "|*" string at those (0-based) indices to the list of "|_"
Tô             # Split the list into 10 parts of 10 strings each
  J            # Join each inner list together to a string
   €           # Map over each line:
    Ć          # Enclose; append its own head (the "|")
     »         # Join the list of strings by newlines
               # (After which the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•A|,•` is `681976` and `•A|,•₂в` is `[1,12,20,21,22]`.

---
Tags: code-golf, string, ascii-art, grid, game-of-life
---


title: Calculate The Digit Sum

text:
# Question
Title: Calculate The Digit Sum
Your task is to get two numbers, and output the digit sum of them. We'll define digit sum as the following:

* take the **decimal** (base 10) digits of each of them, and pad with 0s the shortest number (e.g. \[1,9\], \[0, 7\])
* sum the digits as vectors (e.g. \[1, 16\])
* convert the number back from base 19, and output it (e.g. 1\*19+16=35)

# Input

You can take the input as two numbers, as a list containing both of them or in any other reasonable format (like an array of digits). You can assume the shortest number is padded with zeros so it fits the length of the longer one

# Output

You can output the digit sum in any reasonable format.

# Test cases

```
1, 2 -> 3
5, 10 -> 24
42, 32 -> 137
15717, 51358 -> 826819
1000, 1 -> 6860

```

explanation of 5, 10: the digits of these are \[0, 5\] and \[1, 0\]. Their sum is \[1, 5\], which when converted from base 19 results in 24.

# Scoring

This is code golf, so the shortest answer wins, good luck!

# Answer
# , 6 bytes

```
19#.+/

```

Try it online!

* `19#.` convert the following to base 19...
* `+/` elementwise sum of the input digit lists.
> 8 votes

# Answer
# Jelly, 4 bytes

```
ḅ19S

```

A monadic Link accepting a list of lists of digits which yields an integer.

**Try it online!**
> 6 votes

# Answer
# Python, 30 bytes

```
lambda a,b:int(a,19)+int(b,19)

```

An unnamed function accepting two strings of (base ten) digit characters which returns an integer.

**Try it online!**
> 5 votes

# Answer
# 05AB1E, 4 bytes

-1 thanks to Command Master.

```
+19β

```

Try it online!
> 4 votes

# Answer
# Japt `-mx`, ~~6~~ 3 bytes

Takes input as an array of digit arrays.

```
ì19

```

Try it
> 4 votes

# Answer
# Python 2, 46 bytes

```
f=lambda a,b:a+b and a%10+b%10+19*f(a/10,b/10)

```

Try it online!

Recursive function that sums each digit pair and convert them to base 19.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 24 bytes

```
Tr[#~FromDigits~19&/@#]&

```

Unnamed function taking as input a list that contains two lists of digits. The main point here is that converting to base 19 first and then adding means that padding on the left is unnecessary.

Try it online!
> 3 votes

# Answer
# Wolfram Language (Mathematica), 30 bytes

```
Total@PadLeft@#~FromDigits~19&

```

Try it online!

Takes input as list of digits as @my pronoun is monicareinstate suggested and saved 13 bytes (IntegerDigits)

-1 byte @LegionMammal978
> 2 votes

# Answer
# C (gcc), ~~67~~ 65 bytes

Saved 2 bytes thanks to Mitchell Spector!!!

```
s;m;f(a,b){for(s=m=1;a+b;a/=10,b/=10,m*=19)s+=(a%10+b%10)*m;s--;}

```

Try it online!
> 2 votes

# Answer
# Bash, ~~54~~ ~~53~~ 19 bytes

```
echo $[19#$1+19#$2]

```

Try the test cases online!

---

The input numbers are passed as two arguments.

Output is on stdout.
> 2 votes

# Answer
# K (oK), 5 bytes

**Solution:**

```
19/+/

```

Try it online!

**Explanation:**

Takes input as two lists of digits. Assumes the shorter number is padded with 0s.

```
19/+/ / the solution
   +/ / sum
19/   / decode from base 19

```
> 2 votes

# Answer
# Charcoal, 8 bytes

```
ＩΣＥ²⍘Ｓ¹⁹

```

Try it online! Link is to verbose version of code. Takes input as two strings. Explanation:

```
    ⍘Ｓ¹⁹    Convert the input from base 19
  Ｅ²        Repeated twice
ＩΣ          Summed and output in decimal

```
> 1 votes

# Answer
# Pyth, ~~7~~ ~~6~~ 5 bytes

Takes input as two lists of digits. Assumes the shorter number is padded with 0's.

```
siR19

```

Try it online!

```
siR19
  R       (Right-) Map each digit array of the input to:
 i 19     The digit array converted from base 19
s         Take the sum

```
> 1 votes

# Answer
# dc, 47 bytes

```
?[0q]sZ[sydsxly+0=ZlxA~rlyA~4R+_3Rlfx19*+]dsfxp

```

Try it online!

Or verify all the test cases online.

Input is on stdin (the two numbers on one line, separated by a space).

Output is on stdout.

---

This program makes use of a nice facility in `dc`, where the single-character command `~` will compute **both** the quotient and the remainder in a division operation.
> 1 votes

# Answer
# JavaScript (Babel Node), 43 bytes

```
f=(a,b)=>a+b&&a%10+b%10+19*f(a/10|0,b/10|0)

```

Try it online!
> 1 votes

# Answer
# Java (JDK), 40 bytes

```
a->b->a.valueOf(""+a,19)+a.valueOf(b,19)

```

Try it online!

Takes input as `a:Integer` and `b:String`.
> 1 votes

# Answer
# PHP, 75 bytes

```
for($n=strlen($a=$argv[1]);$n--;)$r+=($a[$i]+$argv[2][$i++])*19**$n;echo$r;

```

Try it online!

As often, getting arguments and dollars makes PHP the longest answer so far :D still i'm content with this

Takes input as strings already padded with zeroes
> 1 votes

# Answer
# Ruby, 24 bytes

```
->a{a.sum{|x|x.to_i 19}}

```

Accepts an array of two strings.

Try it online!
> 1 votes

# Answer
# Brachylog, 6 bytes

```
~ḃ₁₉ᵐ+

```

Try it online!

Takes input as a digit list, but the testing header converts from single integers for convenience.
> 1 votes

# Answer
# Thunno, \\$ 6 \log\_{256}(96) \approx \\$ 4.94 bytes

```
z+19Ad

```

Attempt This Online!

Takes in the numbers as digit arrays.

## Thunno, \\$ 7 \log\_{256}(96) \approx \\$ 5.76 bytes

```
e19AdES

```

Attempt This Online!

Takes in the numbers as digit arrays.

#### Explanations

```
z+19Ad  # Implicit input
z+      # Add the digits in the same positions together
    Ad  # Convert from
  19    # base-19

```

```
e19AdES  # Implicit input
e    E   # Map over the input:
   Ad    #  Convert from
 19      #  base-19
      S  # Sum the list
         # Implicit output

```
> 1 votes

# Answer
# Nibbles, 4.5 bytes

```
`@19!$_+

```

Attempt This Online!

```
`@ Convert from base
19  19
!   zip
$    first input
_    second input
+    addition

```
> 1 votes

# Answer
# Python 3, ~~77~~ 72 bytes

```
lambda x,y:sum(n*19**x for x,n in enumerate([*map(sum,zip(x,y))][::-1]))

```

Try it online!

Not one of the shortest approaches, but it works.

*-5 bytes thanks to @ovs*
> 0 votes

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