title: Run through an array

text:
# Question
Title: Run through an array
We all often hear the idiom "walk through the array" to mean "map the function over the following array". However, I need it done (now!), so I want you to *run* through the array.

## How do I run?

Imagine there's a wild pack of wolves behind you

Running through an array is like walking through one, except you can skip over elements. Yes, it's sometimes messy, but it (generally) works. "Which elements are skipped?", you may ask. Well, this is done at random. Let's walk through running through the array!

1. Let `e` be the current element.
2. Let `random` generate a random float in `[0,1)`. If `random() < 0.5`, then you go the next element and then to step 1. (You may generate a number by other means, so long as their is an (ideally) equal chance of skipping and remaining. E.g., you can use choose an element from a two-member set and perform the action based on the result.)
3. Otherwise, you perform function `f` on `e`.

## Objective

Given an array/list/string like either `A` and a number `K`, run through the array, adding `K` to each member accessed. Output/return this array. `A` will only contain non-negative integers, and `K` will only ever be a non-negative integers. This is a , so the shortest program in bytes wins.

## Test cases (examples)

```
K, A => possible K'
[1, 2, 3, 4], 0 => [1, 2, 3, 4]
[1, 2, 3, 4], 1 => [1, 3, 3, 5]
[0, 0, 0, 0], 2 => [2, 0, 0, 2]

```

# Answer
# Pyth, 7

```
m+*O2vz

```

Try it here

Uses a random choice instead of floating point comparison, but should be indistinguishable.

### Expansion:

```
m+*O2vz     ## implicitly, a d and Q are added to the end of the program
m+*O2vzdQ   ## Q = eval(input()), z= input()
m           ## map over each element d of Q
 +     d    ## add to d
  *O2vz     ## the product of eval(z) and a random number chosen from [0, 1]

```

Using floating point:

```
m+*<.5O0vz

```

Try it here
> 3 votes

# Answer
# Clojure, ~~41~~ 37 bytes

```
(fn[a k](map #(+(*(rand-int 2)k)%)a))

```

Knocked off a couple of bytes by multiplying by 0 or 1 and dropping the "if". Credit to most all of the other submitters!
> 5 votes

# Answer
# Jelly, ~~9~~ ~~8~~ 7 bytes

From `8` to `7` thanks to @FryAmTheEggman.

```
+2X’¤¡€

```

Try it online!

### Explanation

```
+2X’¤¡€
      €   Map over each argument...
 2X           Choose a random number from {1,2}
   ’          Minus 1
    ¤                (grammar stuff)
     ¡        Repeat that number of times...
+                 Add the second input (to the argument being mapped over).

```
> 4 votes

# Answer
# MATL, 11 bytes

```
tZy1$rEki*+

```

Uses floating point random numbers.

**Try it online!**

### Explanation

```
t      % implicit input (array). Duplicate
Zy     % size (array specifying number of rows and columns)
1$r    % random vector between 0 and 1 with that size
Ek     % duplicate, round down: gives 0 or 1 with the same probability
i      % input (number K to be added)
*      % multiply: gives either 0 or K for each element
+      % add element-wise

```
> 3 votes

# Answer
# Japt, 6 bytes

```
®+V*Mq

```

Test it

---

## Explanation

Implicit input of array `U` and integer `V`. Map (`®`) over the array and, to each element, add `V` multiplied by `Mq`, which randomly generates either `0` or `1`. Implicit output of resulting array.
> 3 votes

# Answer
# Python 2, ~~60~~ 58 bytes

```
from random import*
lambda a,k:[e+choice([0,k])for e in a]

```

This program turned out really simple. There aren't many golfing tricks in there, apart from the the obvious "`from module import*`", using a lambda instead of a regular function and the general lack of whitespace. Other than that it's actually quite idiomatic. If I was writing this for real I'd probably do it in a very similar way:

```
import random
def running_addition(seq, k):
    return [e + random.choice([0, k]) for e in seq]

```

Or perhaps something more fancy:

```
import random
import operator
import functools

def run_through(seq, func):
    def random_func(arg):
        if random.randint(0, 1):
            return func(arg)
        return arg

    return [random_func(e) for e in seq]

def running_addition(seq, k):
    return run_through(seq, functools.partial(operator.add, k))

```

But that's enough showing off :)

This is the old, 60 byte version from when using a float for randomness was required:

```
from random import*
lambda a,k:[e+k*(random()<.5)for e in a]

```

For each element of the list, add `k*(random()<.5)`. Python booleans evaluate to 0 and 1, so this adds 0 to any elements for which the condition isn't true.

Python's `random.random()` returns floats in `[0, 1)`, so I didn't have to worry about that.
> 2 votes

# Answer
# Julia, ~~33~~ ~~29~~ 27 bytes

```
x->k->x+rand(0:1,endof(x))k

```

This is an anonymous function that accepts an array with an inner anonymous function that accepts an integer and returns an array. To call it, assign it to a variable and call like `f(x)(k)`.

We generate an array with the same length as the input array consisting of zeros and ones chosen at random with equal probability. We multiply this by the input integer and add that to the input array.

Try it online!

Saved 2 bytes thanks to Dennis!
> 2 votes

# Answer
# Ruby, 28 bytes

```
->a,k{a.map{|e|e+k*rand(2)}}

```
> 2 votes

# Answer
# AWK, 56 bytes

```
x=NF{for(srand(systime());++i<x;)rand()>.5?$i+=$x:0}NF--

```

Try it online!

The random number generator in AWK has to be seeded or it will yield the same sequence of numbers every time the script is run. So that a big chunk of this code. The code expects the "array" to be a list of space separated numbers as commandline argument. The `A` increment value is the last commandline argument.

```
x=NF{                                              }

```

Setting `x` saves some characters, always evals to `true` and the braces group the code run against the input line.

```
     for(srand(systime());      )

```

The code block just one `for` statement, which starts by seeding the random number generator.

```
                          ++i<x;

```

The "should I iterate again" check iterates a counter to process all but the last commandline argument. The last one is the `A` value from the challenge, so we need to ignore that.

```
                                 rand()>.5?$i+=$x:0}NF--

```

The body of the loop increments the current commandline argument by the `A` value using a ternary conditioned on the return value from the random number generator.

```
                                                    NF--

```

Once all the arguments have been incremented (or not), printing them is just a matter of decrementing the number of commandline arguments by one. That's always truthy, directs AWK to ignore the last one, and since there's no code block all the arguments are printed.
> 2 votes

# Answer
# JavaScript (ES6), 38 bytes

```
solution=

a=>k=>a.map(n=>Math.random()<.5?n:n+k)

document.write("<pre>"+
[ [[1,2,3,4], 0], [[1,2,3,4], 1], [[0,0,0,0], 2], [[4,22,65,32,91,46,18], 42] ]
.map(c=>"["+c[0]+"],"+c[1]+": "+solution(c[0])(c[1])).join`\n`)
```
> 1 votes

# Answer
## PowerShell v2+, 34 bytes

```
param($a,$k)$a|%{$_+$k*(random 2)}

```

Takes input `$a` and `$k`, the array and the int respectively. We then loop through the array and each loop iteration output the current element plus `$k` times `(random 2)` which will execute `Get-Random -Maximum 2` (i.e., either a `0` or a `1`). These are all left on the pipeline and output as an array is implicit.
> 1 votes

# Answer
## CJam, 10 bytes

```
{f{2mr*+}}

```

Expects the array and the number on top of the stack in that order and replaces them with the new array.

Test it here.
> 1 votes

# Answer
# Python 3 152 110 98 bytes

This is my first code golf solution so I don't know any tricks. I tested this using a main function with test cases. The file size is only this function.

```
from random import*
def a(x,y):
 p=0
 for z in x:
  if random()>.5:x[p]=z+y
  p+=1
 print(x)

```

Thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ for the advice on removing whitespace. Additional praise to @undergroundmonorail for advice that saved 12 bytes.
> 1 votes

# Answer
# php 71 bytes

```
function f($s,$k){foreach($s as $v){$v+=rand(0,2)==0?k:0;echo $v.",";}}

```
> 1 votes

# Answer
# k (12 bytes)

```
{x+y*(#x)?2}

```

e.g.

```
k){x+y*(#x)?2}[0 0 0 0;2]
2 2 2 0

```

More generally, where `f` can be passed as an argument for 16 characters

```
{@[x;&(#x)?2;y]}

```

e.g.

```
k){@[x;&(#x)?2;y]}[0 0 0 0;2+]
0 0 2 0

```
> 1 votes

# Answer
## Clojure, 32 bytes

```
#(for[i %](+(*(rand-int 2)%2)i))

```

Thanks you David for `rand-int` idea, definetely shorter than the `if(>(rand)0.5)` approach. Here `for` beats `map`.
> 1 votes

# Answer
# Perl 5, 30 + 1 (-a) = 31 bytes

```
$,=<>;say.5>rand?$_:$_+$,for@F

```

Try it online!
> 1 votes

# Answer
# Factor, 29 bytes

```
[ '[ .5 [ _ + ] whenp ] map ]

```

Try it online!

* `'[ ... _ ... ]` Slot whatever is on top of the data stack (A) into the quotation at the `_`.
* `map` Apply a quotation to each member of a sequence (K), collecting the results into a sequence of the same length.
* `.5 [ _ + ] whenp` `whenp` is a version of `when` that takes a probability instead of a boolean. In other words, there is a 50% chance that `whenp`'s quotation will be called.
> 1 votes

# Answer
# Java ~~108~~ ~~107~~ ~~85~~ 82 bytes

```
void f(int[]s,int k){for(int i:s)System.out.print((i+=Math.random()<.5?k:0)+";");}

```

14 bytes saved thanks to @TimmyD
> 0 votes

# Answer
# Octave, 28 bytes

```
@(A,R)R*(rand(size(A))<.5)+A

```

Sample run on ideone.
> 0 votes

# Answer
# 05AB1E, 10 bytes

Code:

```
vždÉ²*y+})

```

Try it online!.
> 0 votes

# Answer
# Java, 84 bytes

```
int[]r(int[]A,int K){for(int i=0;i<A.length;A[i++]+=Math.random()>.5?0:K);return A;}

```

### Ungolfed

```
int[] r(int[] A, int K) {
    for (int i = 0;
         i < A.length;
         A[i++] += Math.random() > .5 ? 0 : K);
    return A;
}

```

### Notes

* The afterthought of the loop could also be it's body, there is no difference in size.
* The input array is modified but the statement does not contain a restriction regarding this issue. If you would count the modified array as a form of "Output/return", you could shave off another 9 bytes by removing `return A;`. The return type would need to be changed from `int[]` to `void`. This however does not save additional bytes since an additional space is needed between `void` and `r`.

### Shorter version (As mentioned in the note), 75 bytes

```
void r(int[]A,int K){for(int i=0;i<A.length;)A[i++]+=Math.random()>.5?0:K;}

```

### Output

```
[1, 2, 3, 4], 0 => [1, 2, 3, 4]
[1, 2, 3, 4], 1 => [1, 3, 3, 4]
[1, 2, 3, 4], 2 => [3, 2, 3, 4]
[1, 2, 3, 4], 3 => [4, 5, 3, 7]
[1, 2, 3, 4], 4 => [5, 2, 3, 8]
[1, 2, 3, 4], 5 => [6, 2, 8, 9]

```
> 0 votes

# Answer
## Mathcad, bytes

---

No formal byte count as Mathcad counting protocol yet to be decided.
> 0 votes

---
Tags: code-golf, array, random
---


title: Are vertices in a clockwise order?

text:
# Question
Title: Are vertices in a clockwise order?
Your program must accept as input six numbers, which describe a triangle - for example, the inputs 80, 23, 45, 1, 76, -2 describe a triangle with vertices (80, 23), (45, 1), and (76, -2). The input must be given as six plain real numbers or as a list of six real numbers, in the order given in the example. Your task is to figure out whether the triangle's vertices are given in clockwise order. Assume that the input vertices are not all in one line. In this case, the vertices are not in clockwise order because the second vertex is to the bottom-left of the first.

This is code-golf, meaning the submission with the shortest number of bytes wins. Good luck!

# Answer
# JavaScript (ES6), 38 bytes

Returns a Boolean value (*true* for clockwise).

```
(a,b,c,d,e,f)=>a*d+b*e+c*f<b*c+a*f+d*e

```

Try it online!

$$D=\begin{vmatrix} a&b&1\\ c&d&1\\ e&f&1 \end{vmatrix}=(ad-bc)-(af-be)+(cf-de)$$

$$D\<0\iff ad+be+cf\<bc+af+de$$
> 14 votes

# Answer
# Jelly, 8 bytes

```
s2;€1ÆḊṠ

```

Try it online!

-2 bytes thanks to Bubbler by transposing the matrix from ngn's formula which saves bytes on padding with 1s, since determinant is invariant over transposition.

Outputs `-1` for clockwise and `1` for counterclockwise. Stole ngn's formula from chat.

```
s2;€1ÆḊṠ   Main Link; [x0, y0, x1, y1, x2, y2]
s2         Slice into chunks of size 2; [[x0, y0], [x1, y1], [x2, y2]]
  ;        Append...
   €       to each chunk...
    1      1; [[x0, y0, 1], [x1, y1, 1], [x2, y2, 1]]
     ÆḊ    Determinant
       Ṡ   Sign

```
> 9 votes

# Answer
# , ~~62~~ ~~44~~ 36 bytes

*Edit: Realized that I'd ridiculously over-engineered my first version after looking at Arnauld's answer which uses the same approach. Upvote that!*

*Edit 2: And then I looked hyper-neutrino's answer (upvote that one, too!) realized that that strategy would be shorter anyway.*

```
function(p)det(rbind(matrix(p,2),1))

```

Try it online!

Outputs a positive value for anticlockwise, and a negative value for clockwise. Add 2 bytes (`>0`) (like this) if you prefer to have a `TRUE`/`FALSE` output.
> 6 votes

# Answer
# , 24 16 bytes

```
0>1-/ .*@,.3 2$]

```

Try it online!

-8 thanks to Bubbler for pointing out I could take a single determinant of a 3x3 to implement the shoelace formula

Takes input as a single list.

Looks like hyper-neutrino beat me to the idea, which is just to use the shoelace formula and then check if the answer is negative.

Since the shoelace formula expects the coordinates in counter-clockwise order, it will be negative only when they're in clockwise order.

## how

Consider the input:

```
80 23 45 1 76 _2

```
* `3 2$]` Shape into matrix:

```
80 23
45  1
76 _2

```
* `1...,.` Zip with 1:

```
1 80 23
1 45  1
1 76 _2

```
* `-/ .*` Determinant:

```
787

```
* `0>` Is it negative?

```
0

```
> 3 votes

# Answer
# Factor \+ `math.matrices.laplace`, 44 bytes

```
[ 2 group [ 1 suffix ] map determinant sgn ]

```

Try it online!

Port of @hyper-neutrino's Jelly answer.
> 3 votes

# Answer
# MATLAB/Octave, 33 bytes

```
@(A)det([reshape(A,2,3);1,1,1])<0

```

Try it online!
Anonymous function. Takes as input list of points (so a vector in MATLAB's nomenclature). It reshapes it into 2x3 array, adds ones and calculates the determinant.
The reshaped array with ones looks like so: $$ \begin{bmatrix} A(1) & A(3) & A(5) \\ A(2) & A(4) & A(6) \\ 1 & 1 & 1 \end{bmatrix}$$
> 3 votes

# Answer
# Charcoal, 28 bytes

```
≔⪪Ａ²θ›⁰ΣＥθ×§ι⁰ΣＥ³×⊖λ§§θ⁺κ⊖λ¹

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for clockwise, nothing if not. Explanation:

```
≔⪪Ａ²θ

```

Split the input into three pairs of coordinates.

```
›⁰ΣＥθ×§ι⁰ΣＥ³×⊖λ§§θ⁺κ⊖λ¹

```

Multiply each coordinate by each cyclically adjacent coordinate and its adjacency, i.e. $$ x\_0 (y\_{0+1} + 0y\_{0+0} - y\_{0-1}) + x\_1 (y\_{1+1} + 0y\_{1+0} - y\_{1-1}) + x\_2(y\_{2+1} + 0y\_{2+0} - y\_{2-1}) $$ and compare the sum to zero to see whether the vertices are clockwise.
> 1 votes

# Answer
# Python 2, 42 bytes

```
lambda a,b,c,d,e,f:a*d+b*e+c*f<b*c+a*f+d*e

```

Try it online!

Port of Arnuald's JS answer. But unfortunately using dot product is longer, because `@` operator requires numpy.
> 0 votes

---
Tags: code-golf, decision-problem, geometry
---


# Question
Title: Tips for golfing a fibonacci sequence generator
One day in July 2020, I made the following C program:

```
#define A m]
a[9999],*m=a;main(){for(2[A=4[A=1;;){for(;4[A;putchar(6[m-=3]+48));
for(puts(a);7[A;2[A=4[A,4[A=1)if(4[A+=3[m+=3]-1,9<(3[A=2[A+=3[A))++
5[A,7[A=1,3[A-=10;}}

```

with three superfluous newlines removed, it's 167 bytes and it prints the fibonacci sequence (as decimal numbers, separated with newline) potentially infinitely (it *will* crash when exceeding the buffer size after printing many terms of the sequence). Try it online (gcc)! Try it online (clang)!.

As I had trouble golfing it myself, I decided to ask the C golfers of CGCC for help. The challenge is to golf it, or more formally, to produce *the same output as this program* (and of course you can derive your own solution based on it). The code should stay *reasonably* portable (i.e. not perform out-of-bounds accesses before program termination is desired, use compiler extensions, etc...).

Your program is expected to print at least `15939` consecutive fibonacci numbers, starting from the smallest, separated with newlines, printed as decimal numbers, starting with `0 1 1 2 3 5 ...`.

Your answer might also provide improvements to the original version as an extra (printing more sequence terms with minimally more bytes, etc... - just make sure to post the golfed version *with* your answer, because it's the main goal of this question).

# Answer
# 142 bytes (-25)

3 more bytes saved by @ceilingcat.

```
a[9999]={0,1},i=2,k,s;main(c){for(;i--;c&&putchar(i?k+48:10))c|=k=a[i]>>4;for(;c=s>9,++i<9999;a[i]=k<<4|s%10)s=a[i]/16+c+(k=a[i]&15);main(c);}

```

Try it online! (GCC)

Try it online! (clang)

---

# 145 bytes (-22)

This is a complete rewrite which can probably be golfed some more.

```
a[9999]={0,1},i,k,s;main(c){for(i=2;;){while(i--)(c|=k=a[i]>>4)&&putchar(i?k+48:10);for(;c=s>9,++i<9999;a[i]=k<<4|s%10)s=a[i]/16+c+(k=a[i]&15);}}

```

Try it online! (GCC)

Try it online! (clang)

## How?

### Encoding

For each entry `a[i]` with `i > 0`, we store the **i**-th decimal digit of the last Fibonacci term into the bits **0** to **3** and the **i**-th decimal digit of the penultimate term into the bits **4** to **7**. (The convention used here is that the 1st decimal digit is the least significant one.)

We start with all entries set to **0** except `a[1]` which is set to **1**:

```
a[1] = 00000001
       \__/\__/
         |   |
         |   +--> first and only digit of Fib(2) = 1
         +------> first and only digit of Fib(1) = 0

```

It is then updated as follows:

```
00000001 -> 00010001 -> 00010010 -> 00100011 -> 00110101 -> ...
\__/\__/    \__/\__/    \__/\__/    \__/\__/    \__/\__/
  0   1       1   1       1   2       2   3       3   5

```

### Printing

Each number is printed by iterating from the most significant digit to the least significant one, ignoring leading zeros and ending with a line-feed.

```
while(i--)
  (c |= k = a[i] >> 4)
  && putchar(i ? k + 48 : 10);

```

We start with `i = 2` and `c = argc` (which is guaranteed to be greater than **0**) in order to make sure that the initial `0` is printed.

### Updating

In order to compute the next term `Fib(n+1)`, we iterate through all values stored in `a[]`, this time from least significant to most significant. We add the last digit to the penultimate one, update each entry accordingly and keep track of the carry into `c`.

```
for(; c = s > 9, ++i < 9999; a[i] = k << 4 | s % 10;)
  s = a[i] / 16 + c + (k = a[i] & 15);

```

We have `i = 9999` and `c = 0` at the end of this loop, which are the expected values to print the next number, starting from the 2nd iteration.

We also end up with `s = 0`, which means that `c` will be re-initialized to `0` as expected before the next update.
> 3 votes

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


title: Mark My Mail! - ASCII Barcodes

text:
# Question
Title: Mark My Mail! - ASCII Barcodes
# 4-state barcodes

Many postal services (Royal Mail UK, Canada Post, US Mail, etc) use a 4-state barcode to encode information about their mail. Rendered in ASCII, it may look something like this:

```
|   | |   | | | |   |     |   |
| | | | | | | | | | | | | | | | |
    | |   |   | | |   |     |

```

A 4-state barcode is a row of bars. Each bar can be extended upwards, downwards, or both, allowing 4 possibilities. This means that each bar essentially represents a base 4 digit:

```
            |       |
Bar:    |   |   |   |
                |   |

Digit:  0   1   2   3

```

The problem with this symbology is that it each barcode is a valid, different barcode upside down: drastically changing the meaning if the orientation is incorrect. Therefore, a *start* and *stop* sequence are normally implemented so the scanner can calculate which way it is supposed to be read.

For the purpose of this challenge, we will be using the start/stop sequence specified by Australia Post: **each barcode begins and ends with a `1 0` sequence.**

---

# The Challenge

Your task is to write a program or function which, given a positive integer `N`, converts it to an ASCII 4-state barcode, where each bar (except for the start/stop sequences) represents a digit in the base-4 representation of `N`.

### Example:

Given the integer `19623`, we would first convert it to its base-4 representation, `10302213`.

We would then map each digit to the corresponding bar:

```
1 0 3 0 2 2 1 3

|   |       | |
| | | | | | | |
    |   | |   |

```

Finally, we would add the start/stop sequences:

```
Start:              End:
1 0                 1 0

|   |   |       | | |
| | | | | | | | | | | |
        |   | |   |

```

The resulting barcode should be the program's output.

---

# Rules:

* The input will be a positive integer, within the range of your language's standard integer size.
* The output:
    + May be either a list of lines, or a string containing newlines.
    + May contain leading or trailing newlines/spaces, as long as the shape remains intact.
    + Should show the barcode with the above format - it must use the pipe character (`|`) and space character () when drawing bars, and there should be 1 space in between each upright bar.
* This is , so the shortest program (in bytes) wins!

---

# Test Cases

**4095:**

```
|   | | | | | | |
| | | | | | | | | |
    | | | | | |

```

**4096:**

```
|   |             |
| | | | | | | | | | |

```

**7313145:**

```
|   |   | |   | |   | |   | |
| | | | | | | | | | | | | | | |
      | | | |     | | | |

```

# Answer
# MATL, ~~34~~ ~~30~~ ~~29~~ 28 bytes

```
TFiK_YAyhhH&\EQE+t~vB!P'|'*c

```

Try it online!

### Explanation

```
TF      % Push array [1 0] (start sequence)
i       % Push input
K_YA    % Convert to base 4. Gives an array of 4-ary digits
y       % Duplicate from below: pushes [1 0] again (stop sequence)
hh      % Concatenate horizontally twice. Gives array of 4-ary digits
        % including start and stop sequences
H&\     % Two-output modulo 2: pushes array with remainders and array
        % with quotients of dividing by 2
EQE     % Times 2, plus 1, times 2, element-wise. This effectively
        % multiplies each entry by 4 and adds 2
+       % Add element-wise to the array of remainders. The stack now
        % contains an array of numbers 2, 3, 6 or 7. Each number
        % encodes, in binary form, a column of the output. The
        % previous multiplication of the quotients by 4 will have the
        % effect of shifting one row down (one binary digit upwards),
        % to make room for the central row. The addition of 2 will
        % create the central row, which is always full
t~      % Duplicate, logical negate. Gives an array of zeros of the
        % same length
v       % Concatenate vertically into a 2-row matrix
B       % Convert to binary. Gives a matrix, where each row is the
        % binary representation of one of the numbers of the input
        % matrix, read in column-major order
!P      % Transpose, flip vertically
'|'*    % Multiply by '|'. This transforms 1 into 124 (ASCII code of
        % '|') and leaves 0 as is
c       % Convert to char. Char 0 is shown as space. Implicitly display

```
> 9 votes

# Answer
# Python 3, ~~103~~ ~~99~~ 96 bytes

```
def f(i,r=[]):
 while i:r=[' | |||||  ||'[i%4::4]]+r;i//=4
 k='|| ',' | ';[*map(print,*k,*r,*k)]

```

Try it online!
> 9 votes

# Answer
# Jelly, ~~16~~ 15 bytes

```
4;jƓb|ṃ⁾| ẎZṙ2G

```

Try it online!

### How it works

```
4;jƓb|ṃ⁾| ẎZṙ2G  Main link. No arguments.

4                Set the argument and the return value to 4.
 ;               Concatenate the return value with the argument, yielding [4, 4].
   Ɠ             Read an integer n from STDIN.
  j              Join, yielding [4, n, 4].
    b            Convert 4, n, and 4 to base 4. Note that 4 is [1, 0] in base 4.
     |           Perform bitwise OR of each resulting quaternary digit and 4.
                 This pads the binary representation of a digit d to three digits:
                 [1, d:2, d%2]
      ṃ⁾|        Convert the results to base " |", i.e., binary where ' '
                 represents 0 and '|' represents 1.
          Ẏ      Concatenate the resulting arrays that correspond to 4, n, and 4.
           Z     Zip; transpose rows and columns.
            ṙ2   Rotate 2 units yo the left, correcting the order of [1, d:2, d%2]
                 to [d%2, 1, d:2].
              G  Grid; separate columns by spaces, rows by linefeeds.

```
> 8 votes

# Answer
# JavaScript (ES6), ~~89~~ ~~87~~ 83 bytes

```
n=>`|  ${(g=(a,k=n)=>k?g(a,k>>2)+(k&a?'| ':'  '):' ')(1)}|
| |${g(~0)}| |
   `+g(2)

```

### Test cases

```
let f =

n=>`|  ${(g=(a,k=n)=>k?g(a,k>>2)+(k&a?'| ':'  '):' ')(1)}|
| |${g(~0)}| |
   `+g(2)

console.log(f(4095))
console.log(f(4096))
console.log(f(7313145))
```

### How?

*NB*: In the version below, template literals have been replaced with standard strings so that the code can be indented properly.

```
n =>                        // given the input n
  '|  ' +                   // append the top leading pattern
  (g = (a,                  // g is a recursive function taking a = mask
           k = n) =>        // and using k = value, initially set to n
    k ?                     //   if k is not zero:
      g(a, k >> 2) +        //     do a recursive call for the next group of 2 bits
      (k & a ? '| ' : '  ') //     append '| ' if the bit is set or '  ' otherwise
    :                       //   else:
      ' '                   //     append an extra leading space and stop the recursion
  )(1) +                    // invoke g() with mask = 0b01
  '|\n' +                   // append the top leading pattern and a linefeed
  '| |' +                   // append the middle leading pattern
  g(~0) +                   // invoke g() with all bits set in the mask
  '| |\n' +                 // append the middle trailing pattern and a linefeed
  '   ' +                   // append the bottom leading pattern
  g(2)                      // invoke g() with mask = 0b10

```
> 7 votes

# Answer
# Jelly, 19 bytes

```
;4⁺;b4Fd2Uj€1Zị⁾| G

```

Try it online!

-1 thanks to Mr. Xcoder.
> 7 votes

# Answer
# Octave, ~~78 77 75 74 70~~ 69 bytes

```
@(x)' |'(dec2bin([2 6 3 7;~(1:4)](:,[2 1 dec2base(x,4)-47 2 1]))-47)'

```

Try it online!

Unlike the original approach, this one uses a simple lookup table to map the base-4 values onto their binary equivalent. The lookup table also adds the spacing between each bar by adding a zero in between each number (which maps to a bar of all spaces).

The lookup table directly maps to bars as:

```
   base4:  0 1 2 3 -

  lookup:  2 6 3 7 0

  binary:  0 1 0 1 0
           1 1 1 1 0
           0 0 1 1 0

```

Conversion from binary to `|` and  is now done by indexing into a string of those two characters - basically the same principle as the lookup table for binary conversion.

---

\*Saved 1 byte, thanks @LuisMendo

---

### Original:

```
@(x)['' circshift(dec2bin([a=[5 4 dec2base(x,4)-44 5 4];a*0](:))'*92,1)-4384]

```

Try it online!

Anonymous function which returns the barcode as a string.

This is based on the fact that if we add 4 to the base4 digits, then we can represent bar/space by the number converted to binary with bits 1 and 2 swapped:

```
   base4:  0 1 2 3

    add4:  4 5 6 7

  binary:  0 1 0 1
           0 0 1 1
           1 1 1 1

swap 2/1:  0 1 0 1
           1 1 1 1
           0 0 1 1

```

The tricky bit from a golfing perspective is adding the spaces between the bars and converting from `0/1` to `'|'/' '`.
> 7 votes

# Answer
# , ~~154~~ 109 bytes

```
function(n,d=c(1,0,n%/%4^floor(log(n,4):0)%%4,1,0),o=c(" ","|"))cat("",o[1+d%%2],"
",o[2+0*d],"
",o[1+(d>1)])

```

Try it online!

Saved a whole bunch of bytes by indexing and using `cat` rather than constructing a matrix and using `write`, as well as 6 from a slightly different conversion to base 4. Prints with a leading space in each row and no trailing newlines.

The indexing takes place using some modular arithmetic, not unlike some other answers, but since R uses 1-based indexing, the arithmetic is somewhat different.

Explanation:

```
function(n,
 d=c(1,0,                         # d contains the padding and
   n%/%4^floor(log(n,4):0)%%4,   # the base 4 digits
   1,0),                         #
 o=c("|"," ")                    # the vector to index into
 cat("",                         # cat separates things with spaces by default
                                 # so the empty string will print a leading space
  o[1+d%%2],"                    # odds have a | above
",                               # literal newline, a space will follow it (hence leading spaces)
 o[2+0*d],"                      # array of 2s since the middle is always |
",                               # another literal newline
 o[1+(d>1)])                     # digits greater than 1 have a | below

```
> 4 votes

# Answer
# Japt, ~~32~~ 31 bytes

```
A¤i2Us4)¬®n s|iS)ù2 w i|1ÃqR² y

```

Test it online!

Not really satisfied with this yet, but it's a start...

### Explanation

```
A¤  i2Us4)¬ ®   n s |iS)ù2 w i |1Ã qR²  y
As2 i2Us4)q mZ{Zn s'|iS)ù2 w i'|1} qRp2 y
                                           Implicit: U = input, A = 10, R = newline, S = space
As2                                        Convert 10 to a binary string.
    i2   )                                 At index 2, insert
      Us4                                    the input converted to base 4.
          q                                Split into chars.
            mZ{                  }         Map each char Z to
               Zn                            Z converted to a number,
                  s'|iS)                     converted to base " |" (binary using ' ' as 0 and '|' as 1),
                        ù2                   left-padded to length 2 with spaces,
                           w                 reversed,
                             i'|1            with another pipe inserted at index 1.
                                   q       Join the resulting list on
                                    Rp2      a newline repeated twice (adds in blank columns).
                                        y  Transpose the entire string.
                                           Implicit: output result of last expression

```
> 3 votes

# Answer
# , 57 49 47 bytes

10 bytes thanks to FrownyFrog!

```
[:,.2{."0[:|:' |'{~#:@2 6 3 7{~1 0,4&#.inv,1,0:

```

How it works:

`1 0,4&#.inv,1,0:` \- converts the number to a list of base-4 digits, adds 1 0 to the beginning and the end of the list

`((#:2 6 3 7){' |')` \- lookup table for the encryption, binary 0 corresponds to space, 1 to '|'

`{~` \- encrypts the base 4 digit by selecting a string from the lookup table above (argument reversed)

`|:` \- transposes the resulting array from 3 columns to 3 rows

`[:` \- caps the fork

`,.2{."0` \- puts spaces between the bars

Try it online!
> 3 votes

# Answer
# Haskell, ~~91~~ 90 bytes

```
h s=[do a<-4%s++0%0;x!!a:" "|x<-[" | |","||||","  ||"]]
_%0=[1,0]
b%n=b%div n b++[mod n b]

```

Try it online! Returns a list of lines.

---

Same byte count alternative for first line:

```
h s=[do a<-4%s++0%0;" | |  ||||"!!(x+a):" "|x<-[0,6,4]]

```
> 3 votes

# Answer
# Charcoal, 50 bytes

```
ＮθＦ²⊞υι¿θＷθ«⊞υ﹪θ⁴≧÷⁴θ»⊞υθＦ²⊞υιＥ⟦ |¦|¦  ||⟧⪫Ｅ⮌υ§ιλω

```

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

```
Ｎθ

```

Input a number.

```
Ｆ²⊞υι

```

Push the stop sequence to the predefined empty list.

```
¿θ

```

If the number is positive,

```
  Ｗθ«⊞υ﹪θ⁴≧÷⁴θ»

```

repeatedly apply divmod to convert it to reversed base 4,

```
  ⊞υθ

```

otherwise just push it.

```
Ｆ²⊞υι

```

Push the start sequence to the list.

```
Ｅ⟦ |¦|¦  ||⟧

```

Map over three strings. Each string represents barcode translation for the digits `0123` for each row.

```
⪫Ｅ⮌υ§ιλω

```

Map over the digits (reversed back into usual order), convert them to bars or spaces using the translation, then join the results into three strings which are then implicitly printed on separate lines.
> 3 votes

# Answer
# Python 2, ~~116~~ 114 bytes

<sup>-2 bytes thanks to notjagan</sup>

```
c=a=0,1
n=input()
while n:c+=n%4,;n/=4
for l in zip(*[' |'[n%2]+'|'+' |'[n/2]for n in c+a][::-1]):print' '.join(l)

```

Try it online!
> 2 votes

# Answer
# APL+WIN, 63 bytes

```
(⍉5 3⍴' | ||  |||||   ')[;,⍉(2 1,(1+((⌈4⍟n)⍴4)⊤n←⎕),2 1),[.1]5]

```

Explanation:

```
(⍉5 3⍴' | ||  |||||   ') create a matrix where columns represent bars plus one for separator spaces

(1+((⌈4⍟n)⍴4)⊤n←⎕) prompt for screen input and convert to base 4 and add 1 to convert to index origin 1

2 1,...,2 1 concatenate start stop

,[.1]5 concatenate separator space indices

(.....)[.....] index into bar matrix to display

```
> 2 votes

# Answer
# , ~~42 40~~ 39 bytes

```
' |'{~[:#:4#.2|.0|:4#:@+1 0(,,[)4#.inv]

```

Shaved 2 bytes thanks to Dennis. 1 byte thanks to ngn.

Try it online!

### How it works

```
                                4#.inv]      to base 4
                        1 0(,,[)             append (1 0) on both sides
                   4#:@+                     add 4 to each digit and convert to binary
                0|:                          transpose
             2|.                             rotate the rows
      [:#:4#.             from base 4 to base 2, it's supposed to separate the columns
' |'{~                                       to characters

```
> 2 votes

# Answer
# 05AB1E, 19 bytes

```
4BT.øS4~bT„| ‡øÁ€S»

```

Try it online!

This is a half-port of Dennis' approach, which is just one byte shorter than the method I used before (which I am quite happy with):

# 05AB1E, 20 bytes

```
4BT.øS2‰í1ýøT„| ‡€S»

```

Try it online!

### How it works?

```
4BT.øS2‰í1ýøT„| ‡€S»  | Full program. Takes input from STDIN, outputs to STDOUT.

4B                    | Convert to base 4.
  T                   | Push a 10 to the stack.
   .ø                 | Surrond (prepend and append the 10 to the base 4 representation).
     S                | Split into individual characters/digits.
                      +---------------------------------------------------------------
                      | This part used to be ¸4.ø4в˜ in the previous version, which
                      | means: surround with 4's, convert each to base 4 (4 -> [1, 0])
                      | and finally deep-flatten the list.
                      +---------------------------------------------------------------
      2‰              | Divmod 2 ([N // 2, N % 2]).
        í             | Reverse (element-wise).
         1ý           | Add a 1 in the middle (element-wise).
           ø          | Transpose.
            T„| ‡     | Translate (‡) from "10" (T) to "| " („| ).
                 €S»  | Format as a grid.
                 €S   | Push the characters of each.
                   »  | Join by newlines, while joining inner lists by spaces.

```

I have asked Adnan (the creator of 05AB1E) about the grid thingy in chat, and they helped me save 2 bytes, by pointing out a feature of 05AB1E: when joining multi-dimenisional lists by newlines, the inner lists are joined using spaces too, so `ðý` is unnecessary.
> 2 votes

# Answer
# APL (Dyalog Classic), 33 bytes

```
' |'[≠\2/2⊖1⍪2 2⊤1 0(,,⊣)4⊥⍣¯1⊢⎕]

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES6) 79 bytes

Uses .toString to convert the number to base 4, and then casework with each line and bitwise OR to build the output line by line. Outputs a list of lines.

```
n=>[2,3,1].map(d=>[...'10'+n.toString(4)+'10'].map(q=>(q|d)>2?"|":" ").join` `)

```

```
f = n=>[2,3,1].map(d=>[...'10'+n.toString(4)+'10'].map(q=>(q|d)>2?"|":" ").join` `)

console.log(f(19623))
console.log(f(4095))
console.log(f(4096))
console.log(f(7313145))
```
> 2 votes

# Answer
# Bash+coreutils, 71 67 bytes

```
dc -e4ddon?np|sed 's/./& /g;h;y/01/23/;G;y/12/21/;H;x;y/0123/ | |/'

```

Try it online!

# Explanation

The `dc` bit converts to base 4, prepending and appending with a `4` (turns into `10` in the output) and using `n` to keep everything on one line.

The rest happens in `sed`:

```
s/./& /g;     Add a space after each digit
h;            Make a copy in hold space
y/01/23/;     Prepare up the second row (2/3 will turn to pipes)
G;y/12/21/;   Append what will be the third row and prep it (1/3 will turn to pipes)
H;x;          Prepend hold space
y/0123/ | |/  Make 1 and 3 pipes, 0 and 2 spaces

```
> 2 votes

# Answer
# Retina, 83 bytes

```
.+
$*
+`(1+)\1{3}
${1};
^
1;;
$
;1;;
1*;
$.&
.+
$&¶$&¶$&
T`13` `^.+
T`12` `.+$
\d
|

```

Try it online! Link includes the faster test cases. Explanation:

```
.+
$*

```

Convert to unary.

```
+`(1+)\1{3}
${1};

```

Convert to base 4 as unary numbers separated by `;`s.

```
^
1;;

```

Prepend the start sequence.

```
$
;1;;

```

Append a `;`, turning it into a digit terminator rather than a separator, and the stop sequence.

```
1*;
$.&

```

Convert to decimal, but adding 1 to each digit.

```
.+
$&¶$&¶$&

```

Triplicate it.

```
T`13` `^.+

```

On the first row, `1`s and `3`s (representing `0`s and `2`s) become spaces.

```
T`12` `.+$

```

On the last row, `1`s and `2`s (representing `0`s and `1`s) become spaces.

```
\d
|

```

All other digits become bars.
> 1 votes

# Answer
# Pip, ~~33~~ ~~31~~ ~~29~~ ~~27~~ 26 bytes

25 bytes of code, +1 for `-S` flag.

```
Y^aTB4WRt" |"@[y%2oMyy/2]

```

Try it online!

### Explanation

We observe a pattern in the four bar types:

* The first row is a space if the digit is even, pipe if odd.
* The second row is always a pipe.
* The third row is a space if the digit is 0 or 1, pipe if 2 or 3.

So:

```
                           a is cmdline arg; o is 1; t is 10 (implicit)
  aTB4                     Convert a to base 4
      WRt                  Wrap it before and after with 10
 ^                         Split into a list of digits
Y                          and yank into y
              [         ]  List of:
               y%2          0 if even, 1 if odd for each item in y
                  oMy       1 mapped to y, i.e. constant 1 for each item in y
                     y/2    Each item in y divided by 2 (0, 0.5, 1, or 1.5)
         " |"@             Use the elements of that list as indices into this string
                           Note that indices are truncated to integers!
                           Autoprint, separating rows with newline and elements of
                           each row with space (-S flag)

```
> 1 votes

# Answer
# SOGL V0.12, 28 bytes

```
4─10¹:h++{»1F2%¹{Ƨ| W}¹∑ā}⁰H

```

Try it Here!
> 1 votes

# Answer
# PHP, 99+1 bytes

```
for($n=10 .base_convert($argn,10,4). 104;(~$c=$n[$i++])||3>$y+=$i=1;)echo" | ||  |||||

"[$c*3+$y];

```

requires PHP \>= 5.5 for literal string indexing and \< 7.1 for the indexing to not yield a warning.

Run as pipe with `-nR` or try it online.

Insert one more newline to get a trailing one.
> 1 votes

# Answer
# C (gcc), 176 bytes

```
#include<stdio.h>
int n,m;f(n,r){if(n)f(n>>2);printf("%c%c",n?32:10,(n&r||!r)&&n?'|':32);}main(){scanf("%d",&n);m=(n+(4<<(32-__builtin_clz(n)/2*2)))*16+4;f(m,1);f(m,0);f(m,2);}

```

Try it online!

Slightly less terribly formatted (less golfed):

```
#include<stdio.h>
int n,m;
f(n,r) {
    if(n)
        f(n>>2);
    printf("%c%c",n?32:10,(n&r||!r)&&n?'|':32);
}

main() {
    scanf("%d",&n);
    m=(n+(4<<2*(16-__builtin_clz(n)/2)))*16+4;
    f(m,1);
    f(m,0);
    f(m,2);
}

```

## Explanation

First, consider the following code to read an integer and output the base 4 version:

```
#include <stdio.h>
int n;
f(n) {if(n)printf("%d\n",n&3,f(n>>2));}
main(){scanf("%d",&n);f(n);}

```

This uses tail recursion to reverse the order of the output. Each recursive step bitshifts by 2 (lops off the last 2 bits and divides by 4). It outputs the result bitmasked with 3 (0b11), which only shows the last two bits, which is the last digit base 4.

The function call is included in the `printf` as a trailing argument (it isn't printed, but it is evaluated) to avoid needing to use {} (+2 bytes) to group the `printf` and the function call.

The solution here extends this base-4 code. First, m is defined as n, but such that in base 4 it will have 10 prepended and appended to it. We then print m.

In printing base 4 regularly, we used a bitmask of 3 to get the digit. In the mail code, the top line is that digit's low-order bit (a bitmask of 1) and the bottom line is the high order bit (a bitmask of 2). Accordingly, the `r` in `f(n,r)` is the bitmask - our main function calls `f(m,1)` for the first line and `f(m,2)` for the last line.

To make the middle line work (always print "|"), we add `||!r` to the conditional - if r is 0, it will always evaluate to true and print a "|". Then we call `f(m,0)` for the middle line.

Finally, we want newlines to behave. Including an extra `printf` is expensive as far as bytes of source code goes, so instead we add another %c specifier to the existing `printf`. `n?32:10` prints a newline if n is 0 (false), and a space otherwise. 32 and 10 are used instead of '\n' and ' ' to save bytes.
> 1 votes

# Answer
# Common Lisp, 191 bytes

```
(lambda(n &aux(k`(1 0,@((lambda(n &aux r f)(do()((= n 0)f)(setf(values n r)(floor n 4))(push r f)))n)1 0)))(format t"~3{~{~:[  ~;| ~]~}~%~}"`(,(mapcar'oddp k),k,(mapcar(lambda(c)(> c 1))k))))

```

Try it online!
> 1 votes

# Answer
# Python 2, 142 126 bytes

```
B=lambda n:n<4and`n`or B(n/4)+`n%4`
def F(i):
 for r in 0,1,2:print' '.join(" |"[(int(x)%2,1,x>'1')[r]]for x in'10'+B(i)+'10')

```

Big thanks to ovs!

I tried to not copy the other answers' methods and... yuck.
> 1 votes

# Answer
# C# (.NET Core), 160 bytes

```
i=>{string s=$"10{B(i)}10",a="";for(int y=0;y<3;y++,a+="\n")foreach(var t in s)a+=t<51&y!=1&t-(y>>1)!=49?"  ":"| ";return a;string B(int n)=>n>0?B(n/4)+n%4:"";}

```

Try it online!

I'm sure I've missed some improvements.

### DeGolfed

```
i=>{
    string s = $"10{B(i)}10", // prepend and append 10 to the base 4 number
           a="";

    for (int y=0; y<3; y++, a+="\n") // go through each row
        foreach (var t in s)         // go through each char digit
            a += t<51 & y != 1 & t-(y>>1) != 49 ? "  " : "| "; // check if bar or space occurs

    return a;

    string B(int n) => n>0? B(n/4) + n%4 : ""; // convert int to base 4
}

```

`t<51 & y != 1 & t-(y>>1) != 49` checks that the char isn't '3', not the second row, and then some binary magic to see if the first or third row should contain the space.
> 1 votes

# Answer
# Japt, 42 bytes

```
s4 +A iA)d1"|| "0" | "2" ||"3'|³ ò3 miR ·y

```

Try it online!
> 0 votes

# Answer
# Pyth, 32 bytes

```
jjL;CmXX1jk_d1`T"| ".DR2sj[4Q4)4

```

**Try it here!**
> 0 votes

# Answer
# C, 120 bytes

Sadly only works on Windows, since `itoa` is too much of a convenience to be standard.

```
char*p,s[21]="10";g(a){for(p=s;*p;)printf(!a|*p++&a?" |":"  ");puts(p);}f(n){strcat(itoa(n,s+2,4),"10");g(1);g(0);g(2);}

```
> 0 votes

# Answer
# APL (Dyalog), 50 bytes

```
{↑,/(' |',¨' ')[⍉↑¯1⌽¨(3⍴2)∘⊤¨4+1 0,1 0,⍨4⊥⍣¯1⊢⍵]}

```

Try it online!
> 0 votes

# Answer
# Python 2, ~~135~~ ~~133~~ 131 bytes

```
i=input();r=[1,0];c="  ","| ";a=b=""
while i:r=[i%4]+r;i=i/4
for x in[1,0]+r:a+=c[x%2];b+=c[x>1]
print a+"\n"+c[1]*len(r)+"| |\n"+b

```

Try it online!

Alternative Python approach.
> 0 votes

# Answer
# Perl 5, 102 + 1 (`-n`) = 103 bytes

```
do{unshift@a,($t=$_%4)%2?'|':$";unshift@b,$t>1?'|':$"}while$_>>=2;say"|   @a |
"."| "x(@a+4)."
    @b"

```

Try it online!
> 0 votes

# Answer
# Vyxal, 40 bytes

```
4τk…t:„JpfDƛ∷`| `$i;Ṅ,ƛ\|;Ṅ,ƛ½⌊` |`$i;Ṅ,

```

Try it Online!
> 0 votes

# Answer
# Japt `-R`, 27 bytes

3 and a half years later and I'm *still* not happy with this!

```
[4U4]cì4 Ës|ù2)ù2 Ô¬q|ÃÕË¬¸

```

Try it

```
[4U4]cì4 Ës|ù2)ù2 Ô¬q|ÃÕË¬¸     :Implicit input of integer U                   > 4095
[4U4]                           :Build the array [4,U,4]                       > [4,4095,4]
     c                          :Flat map                                      >
      ì4                        :  Convert to base 4 digit array               > [1,0,3,3,3,3,3,3,1,0]
         Ë                      :Map                                           >
          s                     :  Convert to string in custom base            >
           |ù2                  :    "|" left-padded with spaces to length 2   >
              )                 :  End base conversion                         > ["|","","||","||","||","||","||","||","|",""]
               ù2               :  Left pad with spaces to length 2            > [" |","  ","||","||","||","||","||","||"," |","  "]
                  Ô             :  Reverse                                     > ["| ","  ","||","||","||","||","||","||","| ","  "]
                   ¬            :  Split                                       > [["|"," "],[" "," "],["|","|"],["|","|"],["|","|"],["|","|"],["|","|"],["|","|"],["|"," "],[" "," "]]
                    q|          :  Join with "|"                               > ["|| "," | ","|||","|||","|||","|||","|||","|||","|| "," | "]
                      Ã         :End map                                       >
                       Õ        :Transpose                                     > ["| ||||||| ","||||||||||","  ||||||  "]
                        Ë       :Map                                           >
                         ¬      :  Split                                       > [["|"," ","|","|","|","|","|","|","|"," "],["|","|","|","|","|","|","|","|","|","|"],[" "," ","|","|","|","|","|","|"," "," "]]
                          ¸     :  Join with spaces                            > ["|   | | | | | | |  ","| | | | | | | | | |","    | | | | | |    "]
                                :Implicit output joined with newlines          > "|   | | | | | | |
                                                                                | | | | | | | | | |
                                                                                | | | | | |    "

```
> 0 votes

---
Tags: code-golf, string, ascii-art, base-conversion
---


title: Tips for code golfing in Vlang

text:
# Question
Title: Tips for code golfing in Vlang
What tips do you have for code-golfing in the V lang? I have been trying to find ways to shorten codegolfs on there but can't find any resources on it. Do you guys have any?

Please suggest tips that are at least somewhat specific to the V programming language (e.g. "remove comments" isn't helpful).

Please post one tip per answer.

# Answer
> 3 votes
When making an instance of a struct, you can omit argument names if they're in the right order.

```
Person{age:-1
name:"bar"}
Person{-1"bar"}

```

If the type is already known, you can omit `Person`, but you'll have to explicitly give the field names.

When making a change to an object, you can copy it by placing `...x` at the start (where `x` is the object to copy from).

# Answer
> 1 votes
# Remove unnecessary whitespace

Take the following code:

```
mut x:="foo"
println(x)
x+="bar"
println(x)

```

You can rewrite the code like so:

```
mut x:="foo"println(x)x+="bar"println(x)

```

This is still perfectly valid syntax. In general, any two statements can be combined if they are separated by a symbol (though this is not always the case).

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


title: Draw an ASCII hexagon of side length n

text:
# Question
Title: Draw an ASCII hexagon of side length n
Given a positive integer \\$n\\$ output an ASCII hexagon with diagonal side length \\$n\\$, as pictured (note there are \\$2n\\$ `_` characters on the top edge)

### Examples:

\\$n = 1\\$

```
 __
/  \
\__/

```

\\$n = 2\\$

```
  ____
 /    \
/      \
\      /
 \____/

```

\\$n = 5\\$

```
     __________
    /          \
   /            \
  /              \
 /                \
/                  \
\                  /
 \                /
  \              /
   \            /
    \__________/

```

etc.

Shortest code in bytes wins. Usual input/output methods apply.

# Answer
> 12 votes
# Canvas, ~~15~~ 9 bytes

```
 _；１＊⁸／∔╬

```

Try it here!, another 9 bytes

-6 bytes after fixing the program.

Draws a quarter of the hexagon, and quad palindromizes.

# Answer
> 9 votes
# Python 2, 92 bytes

```
k=n=input()
while 1:a=k^k>>n;print" "*a+"\/_"[k/n-2]+"_ "[-n<k<n]*2*(2*n+~a)+"\_/"[k/n];k-=1

```

Try it online!

# Answer
> 7 votes
# C (gcc), ~~119~~ 109 bytes

```
a,i,j;f(n){for(i=a+=a=j=n*2;~j;)putchar(!i--?i=a,j--,13:i%(n*3)<n|j%(n*2)?(i-~j-n)%a?(i-j+n)%a?32:92:47:95);}

```

Try it online!

* saved 2 thanks to @ceilingcat

The table below is not updated so values can differ, but the concept is:

* we have 2 pairs of parallel lines

```
        .    .
_______.______.________
  |   /        \   |  .
. |  /          \  | .
 .| /            \ |.
  |/              \|
  |\              /|.
 .| \            / | .
. |  \          /  |
__|___\________/___|___
  |    .      .

```

we iterate x,y from size to 0 and we sum them to check if a / should be printed, we subtract to check for \ , we use modulo to check both parallels.

```
    i 65432109876543210. j
 i+j-n    ________      8
13+7-4=> /        \     7
14+6-4  /          \    6
15+5-4 /            \   5
      /              \  4
      \     1+3-4=>  /  3
       \    2+2-4   /   2
        \   3+1-4  /    1
         \________/     0

```

# Answer
> 6 votes
# Charcoal, 14 bytes

```
←×_θ↖θ→↗θ×_θ‖Ｍ

```

Try it online!

+1 byte fix from ASCII-Only.

Draws half of the hexagon, and mirrors it.

# Answer
> 6 votes
# Haskell, 100 bytes

```
f n=unlines[q<$>[1..3*n]++[1-n..0]|y<-[-n..n],let q x|abs y==n,x>n='_'|x==y='\\'|x+y==1='/'|1>0=' ']

```

Try it online!

Golfing AZTECCO's answer plus some new techniques.

The main idea is that the hexagon is simpler if we transplant the first `n` columns to the end.

```
|-|
   ______
  /      \
 /        \
/          \
\          /
 \        /
  \______/

         |-|
______
      \    /
       \  /
        \/
        /\
       /  \
______/    \

```

Now all the `/` and `\` are in a single line, and the `_` are all to the left of those. This makes it much easier to do AZTECCO's strategy of determining the character from the coordinate. To implement these relabeled coordinates, we replace the `x`-coordinates `[1..4*n]` with a cycled and shifted version `[1..3*n]++[1-n..0]`.

# Answer
> 5 votes
# Perl 5 (`-p`), 102 bytes

```
s/_+/__$&/g,s/^|$/ /gm,s/^ *\S /$&  /gm,s-( +)\\
-$&/ $1 \\
\\ $1 /
- for($\=' __
/  \
\__/')x--$_}{

```

Try it online!

`-p` and `}{` at the end is a trick to only print the output record separator `$\` at the end. It only works for one input record; the header is used to print all in one tio link.

```
$\=' __
/  \
\__/'   # output record separator initialized with hexagon (size 1)

s/_+/__$&/g,s/^|$/ /gm,s/^ *\S /$&  /gm,s-( +)\\
-$&/ $1 \\
\\ $1 /
- # regexes to increase the hexagon by 1

for .. --$_ # to repeat n-1 times where n is the input

```

# Answer
> 5 votes
# Haskell, 150 bytes

```
r=reverse
m(o:c:k)=o:c:c:c:k++" "
f 1=[["\\  /","__ "],["/__\\"]]
f n|[w:i,j]<-map m<$>f(n-1),_:_:k<-r$m w=[r k:w:i,k:j]
h[i,j]=unlines$r<$>r i++j
h.f

```

Try it online!

A more recursive version of this answer. The arbitrariness of this challenge makes this pretty frustrating.

## Explanation

This answer is a bit hard to explain. The challenge is, as I already said, arbitrary in a few ways, so the code is sort of just a nest of symbols.

### Idea

The idea of the program here is to build up the two halves. That is when calculating the nth hexagon we get the two halves for the n-1th hexagon and use that to make the next biggest one.

There are some caveats though. We build the top half up-side-down and we build both halves mirrored left to right. We do this because it is convenient to do it this way. No deep reason it just makes things shorter even if it does make things a little incomprehensible.

### Details

The first line is pretty straight forward `r` is an alias for `reverse`. The second line is not so straight forward. `m` is a nonsense function, it exists because it or a similar operation needs to be done in a few places. It doesn't really have a semantic meaning. The best explanation of what it does here is the code.

```
m(o:c:k)=o:c:c:c:k++" "

```

From here we start getting to `f` which handles basically all of the logic. The first case for `f` is the base case, it is pretty standard

```
f 1=[["\\  /","__ "],["/__\\"]]

```

Note that we return a list of two items instead of a tuple. In any sane program we would be using a tuple since it is fixed at 2 elements. However later we will map over both arguments of this with the same function. It is hard to do that with a tuple but easy with a list, and the list doesn't pose any drawbacks so we use it.

Then we have the inductive case. First we fetch the previous case, and double map our `m` over it. This makes the hexagon 1 unit wider (2 characters) and moves it half a unit (1 character) to the right (although since this whole thing is backwards the space characters are added on the *right*). We pattern match this to `[w:i,j]` because we want to use `w` to make new rows later. Speaking of which next we make the rows. We do this with a pattern match:

```
_:_:k<-r$m w

```

This is sort of nonsense code. It just slaps together things we already had to produce the correct output. `k` and its reverse form the new rows so we add them in. and return that.

After `f` we have `h` which turns the output of `f` into a string. It undoes all the wacky transforms we used during the construction and packages it up to be used.

With all that we just compose `f` and `h` for the final function.

# Answer
> 4 votes
# Python 2, ~~119~~ 114 bytes

```
i=n=input()
d=0
exec"k=i/n|d;print' '*i+'\_/'[~k]+'_ '[i-d<n]*2*(2*n+~i)+'\_/'[k]\nif i==d:d=i=-1\ni-=d|1;"*(n-~n)

```

Try it online!

# Answer
> 4 votes
# Retina 0.8.2, 94 bytes

```
.+
$* ¶$&$*
\G
¶$%'/$`$%_$%_$`\
r` \G
$%`\$'$%_$%_$%'/¶
^¶( *)
$1 $.&$*_$.&$*_$&
T` `\_` +/$

```

Try it online! Link includes test cases. Explanation:

```
.+
$* ¶$&$*

```

Insert two rows of `n` spaces.

```
\G
¶$%'/$`$%_$%_$`\

```

Convert the first row into the top sides of the hexagon.

```
r` \G
$%`\$'$%_$%_$%'/¶

```

Convert the second row into the bottom sides of the hexagon.

```
^¶( *)
$1 $.&$*_$.&$*_$&

```

Insert the top line.

```
T` `\_` +/$

```

Replace the bottom line.

# Answer
> 4 votes
# Python 3.8 (pre-release), 174 bytes

```
n=int(input())
b,a,s="\/ "
z,f=range(n),lambda c,d,t:((n-1-i)*s+c+2*(n+i)*s+d for i in t)
print(f"{'_'*2*n:^{4*n}}",*f(a,b,z),*f(b,a,z[:0:-1]),f"{b:>{n}}{'_'*2*n}/",sep="\n")

```

Try it online!

-1 byte thanks to @Duncan

-8 bytes thanks to @Danis

# Answer
> 4 votes
# C (gcc), ~~194~~ \\$\cdots\\$ ~~149~~ 144 bytes

Saved ~~13~~ ~~14~~ 19 bytes thanks to ceilingcat!!!

```
p(n,c){for(;n--;)printf(L"/\\ _\n"+c);}i;t;f(n){p(n,2);for(i=t=p(2*n,3);i>=p(1,4);t=i/n?--i,1:t)i+=!p(!p(n+i<<!p(!p(n+~i,2),t),t&!i|2),!t)-2*t;}

```

Try it online!

### Explanation (before some golfs)

```
p(n,c){for(;n--;)                     // Helper function to print
         putchar("/\\ _\n"[c]);}      //  one of '/', '\', ' ', '_' , or
                                      //  newline n times, this function
                                      //  also returns 0
i;t;f(n){                             // Main function prints an n hexagon
        p(n,2);                       // Print n leading spaces for the 1st
                                      //  line
        for(                          // Main loop
            i=t=p(2*n,3);             // Set i and t to 0,
                                      //  and print 2*n '_'s for the 1st line
            i>=p(1,4);                // Loop until i goes below 0, and
                                      //  print a newline
                                      // At the end of each loop:
            i+=1-2*t,                 //  increment i for the 1st half
                                      //   and then decrement i in the 2nd
            t=i/n?--i,1:t)            //  keep t as t unless i equals n,
                                      //  then make t 1 and decrement i
                                      // In the main loop:
                p(n+~i,2),            //  print n-i-1 leading spaces
                p(1,t),               //  print a '/' in the 1st half and a
                                      //   '\' in the 2nd
                p(n+i<<1,t&!i|2),     //  print the 2*(n+i) middle spaces
                                      //   unless at the bottom print '_'s
                p(1,!t);              //  print a '\' in the 1st half and a
                                      //   '/' in the 2nd
   }

```

# Answer
> 4 votes
# , 50 47 bytes

*-3 thanks to Jonah!*

```
' \/_'{~]|."1((0,]+2*|.)@=@i.,.3,3,~0$~<:,])@+:

```

Try it online!

```
((0,]+2*|.)@=@i.  ,.  3,3,~0$~<:,])@+:
     0 0 0 0            3 3 3 3
     1 0 0 2            0 0 0 0
     0 1 2 0            0 0 0 0
     0 2 1 0            0 0 0 0
     2 0 0 1            3 3 3 3

    ]|."1
0 0 3 3 3 3 0 0
0 2 0 0 0 0 1 0
2 0 0 0 0 0 0 1
1 0 0 0 0 0 0 2
0 1 3 3 3 3 2 0

' \/_'{~
  ____
 /    \
/      \
\      /
 \____/

```

# Answer
> 4 votes
# JavaScript (ES6),  ~~109~~  107 bytes

```
w=>(x=0,W=w*4,i=g=y=>~y?`
 /\\_`[x++-W?y*!i|w/x|x>w*3?(x+~y+w)%W?(x+y)%W-w?1:3:2:4:x=i=0&y--]+g(y):'')(w*2)

```

Try it online!

### Commented

```
w => (                        // w = input
  x = 0,                      // initialize x to 0
  W = w * 4,                  // W = total width
  i =                         // initialize i to a non-zero value
  g = y =>                    // g is a recursive function taking y
  ~y ?                        //   if y is not equal to -1:
    `\n /\\_`[                //     list of characters
      x++ - W ?               //     if this is not the end of the row:
        y * !i |              //       if this is neither the first nor the last row
        w / x |               //       or x is less than or equal to w
        x > w * 3 ?           //       or x is greater than w * 3:
          (x + ~y + w) % W ?  //         if (x - y - 1 + w) mod W is not equal to 0:
            (x + y) % W - w ? //           if (x + y) mod W is not equal to w:
              1               //             draw a space
            :                 //           else:
              3               //             draw a '\'
          :                   //         else:
            2                 //           draw a '/'
        :                     //       else:
          4                   //         draw a '_'
      :                       //     else:
        x = i = 0 & y--       //       decrement y, set x and i to 0 and draw a linefeed
    ] + g(y)                  //     append the result of a recursive call
  :                           //   else:
    ''                        //     stop the recursion
)(w * 2)                      // initial call to g with y = w * 2

```

# Answer
> 4 votes
# 05AB1E, ~~33~~ ~~29~~ 25 bytes

-4 () bytes thanks to Kevin Cruijssen!

```
L+<'/úíºI·'_×š»∊¶¡`ðs‡).c

```

Try it online!

*05AB1E* has a canvas builtin which might be useful, but is quite tricky to get working, this is just the mirror builtins `º` and  and the centralize builtin `.c`.

# Answer
> 4 votes
# Haskell, ~~129~~ 120 bytes

```
g=mod
f n|a<-n*4=[c|y<-[-n..n],x<-[0..a],let c|x<1='\n'|g x(n*3+1)>n,abs y==n='_'|g(x+y)a==1='/'|g(x-y)a<1='\\'|1>0=' ']

```

Try it online!

* saved 9 thanks to @Wheat Wizard and @xnor.
* Check @xnor answer and its big improvement on the approach to the problem (avoiding modulo and parallel lines) !
* Equivalent of my C answer

We make cartesian coordinates using list comprehension |y\<-\[0..n\*2\],x\<-\[0..a\]

\[c| ... ,let c| ... | ... | ... \] and we yeld the character needed based on x-y or x+y to draw lines..
We use modulo to draw multiple lines(2)
Special case is for `_` which doesn't need a x/y ratio but a range, we used modulo to do just one comparison `>` instead of an a\>x\>b like

# Answer
> 3 votes
# SlimSharp, 150 bytes

```
I n=RI(),m=n;S b=new S('-',n*2).Pad(n*-3),l="/",r="\\";Action<I> x=a=>P(l.Pad(-a).Pad(4*n-a)+r);P(b);for(;m>0;)x(m--);l=r;r="/";for(;m<n;)x(++m);P(b);

```

> https://dotnetfiddle.net/iXLzcO

The fiddle differs slightly from the post because .Net Fiddle can't use the RI() function to read from the console.

This is still the naiive version, without any recursive or coordinate mapping tricks. I'm unlikely to get shorter, because SlimSharp hasn't defined shortcuts for some of the relevant array and string functions yet.

---

# C#, 227 bytes

The full C# looks like this, and that's still assuming all the necessary `using` directives and that we get to abstract to a method.

```
void H(int n){int m=n;string b=new string('-',n*2).PadLeft(n*3),l="/",r="\\";Action<int> x=a=>Console.WriteLine(l.PadLeft(a).PadRight(4*n-a)+r);Console.WriteLine(b);for(;m>0;)x(m--);l=r;r="/";for(;m<n;)x(++m);Console.Write(b);}

```

# Answer
> 2 votes
# Ruby, 141 bytes

```
->(n,g=->c,d{(1..n).map{|i|" "*(n-i)+d+" "*2*(n+i-1)+c}},l=g[?/,e=?\\].reverse){[" "*n+?_*n*2,g[e,?/],l[0..-2],l[-1].sub(/ +(?=\/)/,?_*n*2)]}

```

Try it online!

If an upper underscore is allowed, then it would take a bit lesser bytes, while the hexagon is as pretty as it was earlier ;-)

# Ruby, 114 bytes

```
->n{[" "*n+?_*2*n,(g=->c,d{(1..n).map{|i|" "*(n-i)+c+" "*2*(n+i-1)+d}})[?/,e=?\\],g[e,?/].reverse," "*n+?‾*n*2]}

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 70 bytes

```
ð×©'_¹·×«©¶«©¹'/1Λ¹·Ì'.2Λ¹'\3.Λ«©„./`.;©¶¡Â‚€»`s'.ð:,¹3*>(£„._`:„/\Â‡,

```

Try it online!

# Answer
> 2 votes
# Perl 5, 143 bytes

```
sub f{$n=pop;@b=map{join'',$"x($n-$_),'/','  'x($n+$_-1),'\\',$/}1..$n;join('',$"x$n,$u=__ x$n,$/,@b,map y|/\\|\\/|r,reverse@b)=~s| +/$|$u/|sr}

```

Try it online!

```
sub f{
  $n=pop;             #n = input
  @b=map{             #set array @b to line 2 - n+1
    join'',           #join parts into a line string
    $" x ($n-$_),     #space times n-1
    '/',              #char /
    '  ' x ($n+$_-1), #space times n+iterator minus 1
    '\\',             #char \
    $/                #char newline
  } 1..$n;            #n lines
  join('',            #return string of these joined:
    $" x $n,          #n spaces
    $u = __ x$n,      #n*2 underscores
    $/,               #char newline
    @b,               #lines 2 to n+1 constructed above
    map y|/\\|\\/|r,  #and bottom part which is the same
      reverse@b       #as top part reversed and /\ rotated
  )=~s| +/$|$u/|sr    #and change last spaces of last line to _'s
}

```

# Answer
> 2 votes
# Haskell, 186 168 bytes

-18 bytes with xnor's fixes and removing unneeded spaces on the last line

```
s=' '
(!)=replicate
e=reverse
h n=unlines$(\m->(n!s++(2*n)!'_'++n!s):e(e<$>m)++init m++[(n-1)!s++'\\':(2*n)!'_'++"/"])$(\i->i!s++'\\':(4*n-2*i-2)!s++'/':i!s)<$>[0..n-1]

```

Try it online!

Ungolfed:

```
hex :: Int -> String
hex n = unlines $ first: middle ++ (init $ reverse (map reverse middle)) ++ [last]
  where
    first = replicate n ' ' ++ replicate (2*n) '_' ++ replicate n ' '
    f i = replicate i ' ' ++ "/" ++ replicate (n-i + 2*n + n-i -2) ' ' ++ "\\" ++ replicate i ' '
    middle = map f [n-1,n-2..0]
    last = replicate (n-1) ' ' ++ "\\" ++ replicate (2*n) '_' ++ "/" ++ replicate (n-2) ' '

```

# Answer
> 1 votes
# Vyxal, 60 bytes

```
ð*\_?*d+,(n-‹ð*\/n?+ð*d++\\+,)(nð*\\?d‹n-n›?=[\_|ð]*d++\/+,)

```

Try it Online!

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

```
n=>[...Array((N=2*n)+1)].map((_,i,a,g=i>n,s=g?i-n-1:n-i,j=i&&N-i,r='_'.repeat(N),S=Z=>' '.repeat(Z))=>i?S(s)+'/\\'[+g]+(j?'':r)+S(g?j&&6*n-2*i:N+2*--i)+'\\/'[+g]:S(n)+r).join`
`

```

Try it online!

Not the shortest but uses a different approach. Second in my series of text-writing programs which aren't the shortest, but help assemble a repertoire of array solutions.

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


title: Compute the generalised XOR

text:
# Question
Title: Compute the generalised XOR
The goal of this challenge is to generalise the bitwise XOR function to other bases. Given two non-negative integers \\$ x \\$ and \\$ y \\$, and another integer \\$ b \\$ such that \\$ b \geq 2 \\$, write a program/function which computes the generalised XOR, described the following algorithm:

1. First, find the base \\$ b \\$ representation of \\$ x \\$ and \\$ y \\$. For example, if \\$ b = 30 \\$ and \\$ x = 2712 \\$, then the digits for \\$ x \\$ would be \\$ \[3, 0, 12\] \\$. If \\$ y = 403 \\$, then the digits for \\$ y \\$ would be \\$ \[13, 13\] \\$.
2. Next, pairwise match each digit in \\$ x \\$ with its corresponding digit in \\$ y \\$. Following on from the previous example, for \\$ b^0 \\$ we have \\$ 12 \\$ and \\$ 13 \\$, for \\$ b^1 \\$ we have \\$ 0 \\$ and \\$ 13 \\$, and for \\$ b^2 \\$ we have \\$ 3 \\$ and \\$ 0 \\$.
3. Let \\$ p \\$ and \\$ q \\$ be one of the pairs of digits. The corresponding digit in the output will be equal to \\$ -(p + q) \bmod b \\$, where \\$ \bmod \\$ is the modulo function in the usual sense (so \\$ -1 \bmod 4 = 3 \\$). Accordingly, the output digit for \\$ b^0 \\$ is \\$ 5 \\$, the next digit is \\$ 17 \\$, and the final is \\$ 27 \\$. Combining the output digits and converting that back to an integer, the required output is \\$ 5 \cdot 30^0 + 17 \cdot 30^1 + 27 \cdot 30^2 = 24815 \\$.

This definition retains many of the familiar properties of XOR, including that \\$ x \oplus\_b y = y \oplus\_b x \\$ and \\$ x \oplus\_b y \oplus\_b x = y \\$, and when \\$ b = 2 \\$ the function behaves identically to the usual bitwise XOR.

This challenge is , so the shortest code in bytes wins. You may not accept/output digit arrays of base \\$ b \\$, and your code should work in theory for all bases, and not be limited by builtin base conversion which limit your program/function from working for say \\$ b \> 36 \\$. However, assuming that your integer data type width is sufficiently large is fine.

## Test cases

Formatted as `x, y, b => output`

```
2712, 403, 30   => 24815
24815, 2712, 30 => 403
27, 14, 2       => 21
415, 555, 10    => 140
0, 10, 10       => 90
10, 0, 10       => 90
52, 52, 10      => 6
42, 68, 10      => 0
1146, 660, 42   => 0

```

# Answer
> 8 votes
# Jelly, 7 bytes

```
bUSN%Uḅ

```

Try it online!

-3 byte thanks to Unrelated String

```
bUSN%Uḅ  Main link; take [x, y] on the left and b on the right
b        Convert x and y to base b
 U       Upend; reverse each of x and y's digits
  S      Sum; vectorizes
   N     Negate
    %    Modulo with b
     U   Upend; reverse the digits
      ḅ  Convert from base b

```

The double reverse is necessary such that the digits line up on the correct side should one digit list be shorter than the other.

Almost all ASCII!

# Answer
> 6 votes
# Vyxal, ~~14~~ ~~13~~ 11 bytes

```
vτR÷+N⁰%Ṙ⁰β

```

Try it Online!

Takes `[x, y]` and `b` and outputs the result.

*-1 thanks to the power of vectorisation*

*and -2 thanks to porting Jelly*

## Explained (old)

```
vτR÷Zv∑N⁰%Ṙ⁰β
vτ             # Convert x and y to base b
  R            # reverse each result
   ÷Z          # zip the digits
               # to each pair of digits ([p, q]):
     v∑N       #     -(p + q)
        ⁰%     #     % b
          Ṙ    # reverse the result of the above map and
           ⁰β  # convert it from base b to base 10

```

# Answer
> 6 votes
# Python 2, 45 bytes

```
f=lambda b,x,y:x+y and-(x+y)%b+f(b,x/b,y/b)*b

```

Try it online!

The \\$\text{div}\\$ and \\$\text{mod}\\$ operator in Python 2 work much better than JavaScript in this challenge...

# Answer
> 5 votes
# , 16 bytes

```
[#.[|[:-@+/#.inv

```

Try it online!

Just a straight translation of the algorithm:

* `#.inv` Convert to base `b`
* `[:-@+/` Negative of elementwise sum
* `[|` Mod by `b`
* `[#.` Convert back to decimal

# Answer
> 5 votes
# C (gcc), <sup>~~65~~ ~~47~~</sup> 45 bytes

No bytes added or saved but thanks for a bug fix by Chris Bouchard!!!

```
f(x,y,b){x=x+y?~-b*(x+y)%b+b*f(x/b,y/b,b):0;}

```

Try it online!

# Answer
> 4 votes
# , ~~57~~ 53 bytes

```
f=function(x,b)"if"(any(x),-sum(x)%%b+f(x%/%b,b)*b,0)

```

Try it online!

Using @tsh's recursive approach, taking input as `[x, y], b`.

---

Straightforward, taking input as `[x, y], b`:

### , ~~69~~ ~~65~~ 64 bytes

```
function(x,b,n=b^(0:max(0,log(x,b))))-(x[1]%/%n+x[2]%/%n)%%b%*%n

```

Try it online!

# Answer
> 4 votes
# Ruby, 42 bytes

```
f=->x,y,b{x+y<1?0:(-x-y)%b+b*f[x/b,y/b,b]}

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog Extended), 10 bytes

Basically a translation of Jonah's J solution.

Tacit infix function. Takes \\$b\\$ as left argument and \\$\\{x,y\\}\\$ as right argument.

```
⊣⊥⊣|∘-+/⍤⊤

```

Try it online!

`⍤⊤` convert \\$\\{x,y\\}\\$ to base \\$b\\$, one digit-value per row, padding with leading zeros if needed, then:

`+/` sum each row

`∘-` negate those sums, then:

`⊣|` find the remainder when dividing by \\$b\\$

`⊣⊥` evaluate in base \\$b\\$

# Answer
> 3 votes
# 05AB1E, 11 bytes

Last 5 bytes very similar to the Vyxal answer ;)

```
вí0ζO(¹%R¹β

```

Try it online!

```
в            # convert [x, y] to base b; this results in a list of two lists of digits
 í           # reverse each digit list
  0ζ         # zip with 0 as filler
    O        # sum each pair of digits
     (       # negate all sums
      ¹%     # modulo b
        R    # reverse the resulting base-b digits
         ¹β  # convert from base b

```

# Answer
> 3 votes
# Red, 78 bytes

```
f: func[x y b][either x + y = 0[0][(b * f x / b y / b b)-(x + y % b - b % b)]]

```

Try it online!

My first humble attempt at golfing in Red. This is is the common recursive approach to the problem, but involves a few extra steps in the calculation of the output "digit" because the operators behave quite inconveniently for this task: `%` is remainder, not modulus, while unary minus seems to work only in literals. So, we would need to use verbose function names `negate` and `modulo`, but the shown approach saves a few bytes over that.

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

* -1 byte by applying a crazy bit-wise expression as suggested by Arnauld.

```
b=>g=(x,y)=>(s=~-x-~y)&&s*~-b%b+g(x/b,y/b)*b

```

Try it online!

# Answer
> 1 votes
# Japt, 17 bytes

Ouch!

```
®ìV ÔÃÕ®xn uVÃÔìV

```

Try it

```
®ìV ÔÃÕ®xn uVÃÔìV     :Implicit input of array U=[x,y] and integer V=b
®                     :Map U
 ìV                   :  Convert to base V digit array
    Ô                 :  Reverse
     Ã                :End map
      Õ               :Transpose
       ®              :Map
        x             :  Reduce by addition
         n            :  After negating each
           uV         :  Mod V
             Ã        :End map
              ìV      :Convert from base V digit array

```

# Answer
> 1 votes
# Charcoal, 18 bytes

```
Ｉ↨⮌Ｅ↨Σθη﹪±Σ÷θＸηκηη

```

Try it online! Link is to verbose version of code. Takes input in the form `[[x, y], b]`. Explanation:

```
      θ             List `[x, y]`
     Σ              Take the sum
    ↨  η            Convert to base `b`
   Ｅ                Map over digits
            θ       List `[x, y]`
           ÷        Vectorised integer divide by
              η     `b`
             Ｘ      Raised to power
               κ    Current index
          Σ         Summed
         ±          Negated
        ﹪       η   Reduced modulo `b`
  ⮌                 Reversed
 ↨                η  Convert from base `b`
Ｉ                    Cast to string
                     Implicitly print

```

# Answer
> 1 votes
# Core Maude, 155 bytes

```
mod X is pr INT . vars B X Y : Nat . op f : Nat Nat Nat -> Nat . eq f(0,0,B)=
0 . eq f(X,Y,B)= B * f(X quo B,Y quo B,B)+((B - 1)*(X + Y))rem B[owise]. endm

```

The answer is obtained by reducing the function `f`, which takes x, y, and b.

### Example Session

```
             \||||||||||||||||||/
           --- Welcome to Maude ---
             /||||||||||||||||||\
         Maude 3.1 built: Oct 12 2020 20:12:31
         Copyright 1997-2020 SRI International
           Tue Jun  1 20:59:00 2021
Maude> mod X is pr INT . vars B X Y : Nat . op f : Nat Nat Nat -> Nat . eq f(0,0,B)=
> 0 . eq f(X,Y,B)= B * f(X quo B,Y quo B,B)+((B - 1)*(X + Y))rem B[owise]. endm
Maude> red f(2712, 403, 30) .
reduce in X : f(2712, 403, 30) .
rewrites: 28 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 24815
Maude> red f(24815, 2712, 30) .
reduce in X : f(24815, 2712, 30) .
rewrites: 28 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 403
Maude> red f(27, 14, 2) .
reduce in X : f(27, 14, 2) .
rewrites: 46 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 21
Maude> red f(415, 555, 10) .
reduce in X : f(415, 555, 10) .
rewrites: 28 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 140
Maude> red f(0, 10, 10) .
reduce in X : f(0, 10, 10) .
rewrites: 19 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 90
Maude> red f(10, 0, 10) .
reduce in X : f(10, 0, 10) .
rewrites: 19 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 90
Maude> red f(52, 52, 10) .
reduce in X : f(52, 52, 10) .
rewrites: 19 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 6
Maude> red f(42, 68, 10) .
reduce in X : f(42, 68, 10) .
rewrites: 19 in 0ms cpu (0ms real) (~ rewrites/second)
result Zero: 0
Maude> red f(1146, 660, 42) .
reduce in X : f(1146, 660, 42) .
rewrites: 19 in 0ms cpu (0ms real) (~ rewrites/second)
result Zero: 0

```

### Ungolfed

```
mod X is
    pr INT .

    vars B X Y : Nat .

    op f : Nat Nat Nat -> Nat .
    eq f(0, 0, B) = 0 .
    eq f(X, Y, B) =
        B * f(X quo B, Y quo B, B)
            + ((B - 1) * (X + Y)) rem B [owise] .
endm

```

# Answer
> 1 votes
# Pip, ~~29~~ 23 bytes

```
{Y-$+ay&y%b+b*(fa//bb)}

```

Stretching the input format a bit, this submission is function that takes two arguments: a two-element list containing \\$x\\$ and \\$y\\$, and an integer \\$b\\$. Try it online!

### Explanation

Recursive function idea borrowed from tsh's Python answer.

```
{                     }  A function:
  -$+a                    Negated sum of the first argument (the list of two numbers)
 Y                        Yank that value into y
      y&                  If y is 0 (falsey), return 0; otherwise, return:
        y%b                Negated sum modulo the second argument (the base)
           +               Plus
            b*             The base, times
              (f     )     A recursive call
                a//b       with the two numbers int-divided by the base
                    b      and the same base as before

```

---
Tags: code-golf, base-conversion
---


title: How can this code be more "golfed"?

text:
# Question
Title: How can this code be more "golfed"?
I'm not sure if this is the right place to ask, but I found this similar question so I'll go ahead.

I'm *very* new to code golfing, so keep your smothered laughs and throw-up emoji's to yourselves please ;). Anyway, someone recently posted a challenge (that was shortly deleted) to draw a 16x16 pixel image of the Old Man from the original Legend of Zelda, who gives you the wooden sword.

This guy:

Here's my code (643 characters):

```
from PIL import Image,ImageColor
g=ImageColor.getrgb
r=range
l=[list('0000033333300000000023233232000000003313313300000000331331330000000042333324000000042222222240000044220000224400044224222242244034424422224424433444442222444443344404422440444304440444444044400444044444404440004044444444040000004444444400000004433443344000'[i*16:i*16+16])for i in r(16)]
i=Image.new('RGB',(16,16),color='black')
for j in r(16):
    for k in r(16):
        t=k,j
        v=l[j][k]
        if v=='2':
            i.putpixel(t,g('white'))
        if v=='3':
            i.putpixel(t,g('#FFC864'))
        if v=='4':
            i.putpixel(t,g('red'))
i.show()

```

It's bad, I know. Anyway, anyone care to share some tips on shortening it?

# Answer
I'm proposing a slightly new strategy. Instead of `Image.putpixel`, we use `Image.frombytes`, which creates an image directly from an encoded string of `RGB` values. The logic is similar to the `putpixel` version, but when implemented, it turns out to be considerably shorter:

### 406 bytes

```
from PIL import Image
x=b'\0\0\0',b'\xff\xff\xff',b'\xff\xc8\x64',b'\xff\0\0'
D='0000022222200000000012122121000000002202202200000000220220220000000031222213000000031111111130000033110000113300033113111131133023313311113313322333331111333332233303311330333203330333333033300333033333303330003033333333030000003333333300000003322332233000'
Image.frombytes('RGB',(16,16),b''.join(x[int(c)]for c in D)).show()

```

However, the compressed string `D` takes up almost half of the program! We can use @ovs's idea to "compress" it by storing it in a higher base (such as base 36). Now the code is almost half as long:

### 267 bytes

```
from PIL import Image
x=b'\0\0\0',b'\xff\xff\xff',b'\xff\xc8\x64',b'\xff\0\0'
D=int('MG8FMXO3ZANJ48JRXWYBSK3DF0HDWGJ34QP4XXAYS0EMXW3OJUIPDTNGOJGZIQZEKKSTFNJB1XQIAVDYAS8S06VLJVICO4STFK',36)
Image.frombytes('RGB',(16,16),b''.join(x[D>>2*c&3]for c in range(256))).show()

```

Finally, notice that the image is vertically symmetric. Knowing this, we can cut the size of our compressed string in half, with some overhead from the added logic. Along with some general golfing tricks, we arrive at a messy 223-byte solution:

### 222 bytes

```
from PIL import Image
Image.frombytes('RGB',[16]*2,b''.join(b'\0\xff\xff\xff\0\xff\xc8\0\0\xffd\0'[int('5VJ6J7FF7GD34HSPDCBV1SHKVG80MFVR3VX2RKU7WMRHBW0XZ4',36)>>2*(c//16*8+(c^-(c%16>7))%8)&3::4]for c in range(256))).show()

```
> 12 votes

# Answer
Splitting the string into rows of 16 and then using two nested loops to go over each pixel is taking a lot of bytes to do. It would be easier to just loop over the original string and use `(index%16,index//16)` to point at a specific row and column.

Also, instead of specifying a background color you can just draw every single pixel, which is shorter when using hyper-neutrino's advice to use a list of colors. You can also use `#000` and `#FFF` instead of `black` and `white` (1 byte shorter each).

Bonus tip: `(16,16)` can become `[16]*2` (1 byte shorter)

Combining this with knosmos huge save by using data compression and makonede's suggestion to use as imports we can get this down to 353 bytes:

```
import base64,zlib
from PIL import Image,ImageColor as C
i=Image.new('RGB',[16]*2)
for j in range(256):i.putpixel((j%16,j//16),C.getrgb(['#000','#000','#FFF','#FFC864','red'][int(zlib.decompress(base64.a85decode(b"Garp%d1+#J#QrG=W9sOr.gFe$difq+:dD#Fi'\\kVYS/be9`DBVETlH%2Un>#OH/p!dpQBq?eAD\\o?Ok%[FUW>EJ8;cLZ6ZbI2XaB#r3e")).decode("u8")[j])]))
i.show()

```
> 11 votes

# Answer
Just removing some whitespace, we can get:

```
from PIL import Image,ImageColor
g=ImageColor.getrgb
r=range
l=[list('0000033333300000000023233232000000003313313300000000331331330000000042333324000000042222222240000044220000224400044224222242244034424422224424433444442222444443344404422440444304440444444044400444044444404440004044444444040000004444444400000004433443344000'[i*16:i*16+16])for i in r(16)]
i=Image.new('RGB',(16,16),color='black')
for j in r(16):
    for k in r(16):
        t=k,j;v=l[j][k]
        if v=='2':i.putpixel(t,g('white'))
        if v=='3':i.putpixel(t,g('#FFC864'))
        if v=='4':i.putpixel(t,g('red'))
i.show()

```

(since you can inline the if statements, and putting two statements on one line with `;` saves bytes when you're in a block)

Then, you can collapse the repetitive `i.putpixel` by using a ternary `if-else`. Alternatively, you can just use a list to select the appropriate value:

```
from PIL import Image,ImageColor
g=ImageColor.getrgb
r=range
l=[list('0000033333300000000023233232000000003313313300000000331331330000000042333324000000042222222240000044220000224400044224222242244034424422224424433444442222444443344404422440444304440444444044400444044444404440004044444444040000004444444400000004433443344000'[i*16:i*16+16])for i in r(16)]
i=Image.new('RGB',(16,16),color='black')
for j in r(16):
    for k in r(16):
        t=k,j;v=int(l[j][k])
        if v>1:i.putpixel(t,g(['white','#FFC864','red'][v-2]))
i.show()

```

Basically, for `2`, `3`, and `4`, what this does is it uses a list, `['white', '#FFC864', 'red']` and selects the `v-2`th element from it.
> 6 votes

# Answer
You use the literal `16` 8 times. In python 3.8+, you can write `c:=16` and then `c` the other times:

```
i=Image.new('RGB',(c:=16,c),color='black')

```
> 6 votes

# Answer
Shave off 97 bytes from hyper-neutrino's answer by encoding the data with base85 and zlib:

```
import base64,zlib
from PIL import Image,ImageColor
g=ImageColor.getrgb
r=range
l=[list(zlib.decompress(base64.a85decode(b"Garp%d1+#J#QrG=W9sOr.gFe$difq+:dD#Fi'\\kVYS/be9`DBVETlH%2Un>#OH/p!dpQBq?eAD\\o?Ok%[FUW>EJ8;cLZ6ZbI2XaB#r3e")).decode("u8")[i*16:i*16+16])for i in r(16)]
i=Image.new('RGB',(16,16),color='black')
for j in r(16):
 for k in r(16):
  t=k,j;v=int(l[j][k])
  if v>1:i.putpixel(t,g(['white','#FFC864','red'][v-2]))
i.show()

```
> 5 votes

# Answer
**EDIT:** Turns out Python 2 doesn't have `base64.a85decode`, so this won't work. But you can still combine a b-string with an r-string, and combine that with Leo's amazing tip, and you've saved \\$292\\$ bytes.

```
import base64,zlib
from PIL import Image,ImageColor as C
i=Image.new('RGB',[16]*2)
for j in range(256):i.putpixel((j%16,j//16),C.getrgb(['#000','#000','#FFF','#FFC864','red'][int(zlib.decompress(base64.a85decode(br"Garp%d1+#J#QrG=W9sOr.gFe$difq+:dD#Fi'\kVYS/be9`DBVETlH%2Un>#OH/p!dpQBq?eAD\o?Ok%[FUW>EJ8;cLZ6ZbI2XaB#r3e")).decode("u8")[j])]))
i.show()

```
> 3 votes

# Answer
# ~~215~~ ~~210~~ ~~216~~ ~~210~~ 216 bytes

By using literal characters in place of some of the Unicode escapes from dingledooper's 222 byte solution, we can save a byte. ~~But by encoding the program in Latin-1, we can save 7!~~

**EDIT:** Saved 5 bytes thanks to Jakque!

**EDIT:** Python by default parses programs as UTF-8, so this won't work. You would need a magic comment `#coding:l1` on the first line, so this would actually end up having to add 11 bytes.

**EDIT:** Just tested on TIO, turns out I was wrong. 6 bytes have been regained!

**EDIT:** After some more testing with Bash to try and get the raw bytes in, I was in fact correct the first time. Back to 216.

```
from PIL.Image import*;frombytes('RGB',[16]*2,b''.join(bytes('\0ÿÿÿ\0ÿÈ\0\0ÿd\0','l1')[int('5VJ6J7FF7GD34HSPDCBV1SHKVG80MFVR3VX2RKU7WMRHBW0XZ4',36)>>2*(c//16*8+(c^-(c%16>7))%8)&3::4]for c in range(256))).show()

```
> 2 votes

# Answer
```
import PIL.Image, base64, zlib
s = b'c$}?~T@Jt?2!nfA54&42e`bR~6Cc(PgZQCUfkXDR5YV!&&a9D%ndJ9|Ir)dDC5CqM!KF%g^YH~{$pjovNiD-9`RpnztxNF;#WPO6@aBt?_fv%3QW0r-!$ZTqrT#L(OW41F%c&RU*cng'
i = PIL.Image.frombytes("RGB", (16,16), zlib.decompress(base64.b85decode(s)))

```
> 1 votes

# Answer
Instead of making a bunch of zeros, you probably could have made something like 0x8 and then parse it to display as 8 zeros. However I am not sure if that's any shorter.
> 0 votes

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


title: Conway's Prime Game

text:
# Question
Title: Conway's Prime Game
Specifically, Conway's PRIMEGAME.

This is an algorithm devised by John H. Conway to generate primes using a sequence of 14 rational numbers:

```
 A   B   C   D   E   F   G   H   I   J   K   L   M   N
17  78  19  23  29  77  95  77   1  11  13  15  15  55
--  --  --  --  --  --  --  --  --  --  --  --  --  --
91  85  51  38  33  29  23  19  17  13  11  14   2   1

```

For example, F is the fraction `77/29`.

So here's how the algorithm finds the prime numbers. Starting with the number `2`, find the first entry in the sequence that when multiplied together produces an integer. Here it's `M`, `15/2`, which produces `15`. Then, for that integer `15`, find the first entry in the sequence that when multiplied produces an integer. That is the last one, `N`, or `55/1`, which yields `825`. Write down the corresponding sequence. (The astute among you may recognize this as a FRACTRAN program.)

After some iterations, you'll get the following:

```
2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290, 770, 910, 170, 156, 132, 116, 308, 364, 68, 4 ...

```

Note that the last item listed is `4`, or `2^2`. Behold our first prime number (the `2` exponent) generated with this algorithm! Eventually, the sequence will look like the following:

```
2 ... 2^2 ... 2^3 ... 2^5 ... 2^7 ... etc.

```

Thus, yielding the prime numbers. This is OEIS A007542.

## The Challenge

Given an input number `n`, either zero- or one-indexed (your choice), either output the first `n` numbers of this sequence, or output the `n`th number of this sequence.

## Examples

The below examples are outputting the `n`th term of the zero-indexed sequence.

```
 n   output
 5   2275
19   4
40   408

```

## Rules

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

# Answer
> 7 votes
# FRACTRAN, 99 bytes

```
17/2821 78/2635 19/1581 23/1178 29/1023 77/899 95/713 77/589 1/527 11/403 13/341 15/434 15/62 55/31

```

Try it online!

The program takes `2*31^n` as an input, which is used as the initial state.

All the fractions in the original FRACTRAN program have been divided by 31 (the first unused prime register), so the program stops at the nth iteration.

# Answer
> 5 votes
# Python 3, ~~173 165 153 145 144 136 135 127 126 125 108 107~~ 104 bytes

```
f=lambda n:2>>n*2or[f(n-1)*t//d for t,d in zip(b"NM_M\r7",b"[U3&!\r")if f(n-1)*t%d<1][0]

```

Try it online!

* -30 bytes thanks to Jonathan Frech!
* -3 bytes thanks to Lynn!

`2>>n*2` is `2` for `n==0` and `0` otherwise.

103 bytes if we can return floats.

# Answer
> 4 votes
# Jelly, ~~49~~ 43 bytes

```
×“×NŒçøM_M¢¿ÆÐÐ7‘“[U3&!øçŒ×Æ¿Ç£¢‘:@xḍɗḢ
2Ç¡

```

Try it online!

* -6 bytes thanks to miles

# Answer
> 3 votes
# Python 3, 107 bytes

```
f=lambda n,k=2:n and f(n-1,[k*a//b for a,b in zip(b"NM_M\r7",b"[U3&!\r")if k*a%b<1][0])or k

```

Try it online!

Encodes the list of fractions by `zip`ing two bytestrings containing unprintable low-ASCII characters.

If `n` is zero, we return the argument `k`; otherwise we recurse with new parameters. Our new `k` is the first value `k*a//b` corresponding to some fraction `(a, b)` in the list such that `k*a//b` is an integer, i.e. `k*a%b<1`.

# Answer
> 2 votes
# MATL, 50 bytes

```
Hi:"'0m26<l~l *,..V'31-*'{uSFA=731-+."!'32-&\w~)1)

```

Try it online!

# Answer
> 2 votes
# , 116 110 bytes

```
g=.3 :0
((1047856500267924709512946135x%&(96#.inv])5405040820893044303890643137x)([:({.@I.@(=<.){[)*)])^:y 2
)

```

Try it online!

0-indexed; returns the n-th number

Some bytes can be saved by making the verb tacit, but I have problems making `^:` work.

## Explanation:

describes the rational numbers in the form NrD, where N is the numerator and D is the denominator, for example `17r91 78r85 19r51 23r38...` I created 2 separate lists for the numerators and denominators and made 2 base-96 numbers from them.

`1047856500267924709512946135x%&(96#.inv])5405040820893044303890643137x` converts the base-96 numbers to lists and constructs a list of fractions by divinding the two lists.

```
   1047856500267924709512946135x%&(96#.inv])5405040820893044303890643137x
17r91 78r85 19r51 23r38 29r33 77r29 95r23 77r19 1r17 11r13 13r11 15r14 15r2 55

```

`2` start with 2

`^:y` repeat the verb on its left `n` times (y is the argument to the function)

`]` the right argument (starts at 2, and then uses the result of each iteration)

`*` multiply the list of fractions by the right argument

`(=<.)` are the results integer (compare each number with its floor)

`{.@I.@` finds the index `I.` of the first `{.` of the integers

`{[` uses the index to retrieve the number

# Answer
> 2 votes
# 05AB1E,  ~~44~~  43 bytes

0-indexed

```
2sF•Ë₁ǝßÌ?ƒ¥"h2ÔδD‡béαA5À>,•тв2ä`Š*s‰ʒθ_}нн

```

Try it online!

**Explanation**

```
2                                             # initialize stack with 2
 sF                                           # input times do:
   •Ë₁ǝßÌ?ƒ¥"h2ÔδD‡béαA5À>,•                  # push a base-255 compressed large number
                            тв                # convert to a list of base-100 digits
                              2ä`             # split in 2 parts to stack
                                 Š            # move denominators to bottom of stack
                                  *           # multiply the last result by the numerators
                                   s‰         # divmod with denominators
                                     ʒθ_}     # filter, keep only those with mod result 0
                                         нн   # get the div result

```

The large number pushed is `17781923297795770111131515559185513833292319171311140201`

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

* thanks to @Arnauld and @Neil for reducing by 11 bytes

```
(n,N=2,I=13,B=Buffer(`[U3&!\rNM_M\r7`))=>n--?f(n,N/B.find(x=>N%x<!!++I)*B[I]):N

```

Try it online!

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

```
n->a=2;for(i=1,n,a=[x|x<-a*[17/91,78/85,19/51,23/38,29/33,77/29,95/23,77/19,1/17,11/13,13/11,15/14,15/2,55],x\1==x][1]);a

```

Try it online!

# Answer
> 1 votes
# Retina, 213 bytes

```
K`17/91¶78/85¶19/51¶23/38¶29/33¶77/29¶95/23¶77/19¶1/17¶11/13¶13/11¶15/2¶1/7¶55/1¶17/91¶78/85¶19/51¶23/38¶29/33¶77/29¶95/23¶77/19¶1/17¶11/13¶13/11¶15/2¶1/7¶55/1¶2
\d+
*
"$+"+`((_+)/(_+)¶(.+¶)*)(\3)+$
$1$#5*$2
r`_\G

```

Try it online! Explanation:

```
K`17/91¶78/85¶19/51¶23/38¶29/33¶77/29¶95/23¶77/19¶1/17¶11/13¶13/11¶15/2¶1/7¶55/1¶17/91¶78/85¶19/51¶23/38¶29/33¶77/29¶95/23¶77/19¶1/17¶11/13¶13/11¶15/2¶1/7¶55/1¶2

```

Replace the input with a list of all the fractions, plus the initial integer.

```
\d+
*

```

Convert everything to unary.

```
"$+"+`

```

Repeat the substitution the number of times given by the original input.

```
((_+)/(_+)¶(.+¶)*)(\3)+$

```

Find a denominator that evenly divides the integer.

```
$1$#5*$2

```

Replace the integer with the result of the division multiplied by the numerator.

```
r`_\G

```

Convert the integer to decimal and output the result.

# Answer
> 1 votes
# Attache, 81 bytes

```
Nest<~{Find[Integral,_*&`//=>Chop[Ords!"0zmt2R6E<@l<~6l2 0*,,*.-.!V "-31,2]]},2~>

```

Try it online! Outputs a fraction over 1. For example, input `5` returns `2275/1`. This can be fixed with plus 2 bytes by prepending `N@` to the program.

## Explanation

This is a curried function, which curries `Nest` with two predefined arguments:

```
{Find[Integral,_*&`//=>Chop[Ords!"0zmt2R6E<@l<~6l2 0*,,*.-.!V "-31,2]]}

```

and `2`. This last argument is simply the initial seed, and the argument that is passed to this function is the number of iterations to nest the given function.

The following is used to encode PRIMEGAME:

```
&`//=>Chop[Ords!"0zmt2R6E<@l<~6l2 0*,,*.-.!V "-31,2]]

```

This is evaluated as such:

```
A> "0zmt2R6E<@l<~6l2 0*,,*.-.!V "
"0zmt2R6E<@l<~6l2 0*,,*.-.!V "
A> Ords!"0zmt2R6E<@l<~6l2 0*,,*.-.!V "
[48, 122, 109, 116, 50, 82, 54, 69, 60, 64, 108, 60, 126, 54, 108, 50, 32, 48, 42, 44, 44, 42, 46, 45, 46, 33, 86, 32]
A> Ords!"0zmt2R6E<@l<~6l2 0*,,*.-.!V "-31
[17, 91, 78, 85, 19, 51, 23, 38, 29, 33, 77, 29, 95, 23, 77, 19, 1, 17, 11, 13, 13, 11, 15, 14, 15, 2, 55, 1]
A> Chop[Ords!"0zmt2R6E<@l<~6l2 0*,,*.-.!V "-31,2]
 17 91
 78 85
 19 51
 23 38
 29 33
 77 29
 95 23
 77 19
  1 17
 11 13
 13 11
 15 14
 15  2
 55  1
A> &`//=>Chop[Ords!"0zmt2R6E<@l<~6l2 0*,,*.-.!V "-31,2]
[(17/91), (78/85), (19/51), (23/38), (29/33), (77/29), (95/23), (77/19), (1/17), (11/13), (13/11), (15/14), (15/2), (55/1)]

```

Let's replace this expression with `G` in the explanation. Our first function becomes:

```
{Find[Integral,_*G]}

```

This performs a single iteration of FRACTRAN code over `_`, the input to the function. It `Find`s an `Integral` member (one which is an integer) of the array `_*G`, which is the input `_` multiplied with each member of `G`. `Nest` simply applies this transformation the given number of times.

## Attache, 42 bytes

I implemented parts of the `$langs` library, being inspired by this challenge, so I mark this section non-competing.

```
Needs[$langs]2&FRACTRAN_EXAMPLES.prime.run

```

This simply queries the list of `FRACTRAN_EXAMPLES` I have. Each example is a `FractranExample` instance, which calls the inbuilt `FRACTRAN` function. The `prime` example is Conway's PRIMEGAME.

# Answer
> 1 votes
# F# (Mono), 215 bytes

```
let q m=
 let rec i x y=
  if y=m then x
  else[17;91;78;85;19;51;23;38;29;33;77;29;95;23;77;19;1;17;11;13;13;11;15;14;15;2;55;1]|>List.chunkBySize 2|>List.find(fun[n;d]->x*n%d=0)|>fun[n;d]->i(x*n/d)(y+1)
 i 2 0

```

Try it online!

# Answer
> 0 votes
## PHP, 183 bytes (189 with "php" tag)

Golfed :

```
$t=2;for(;@$i++<$argv[1];){foreach([17/91,78/85,19/51,23/38,29/33,77/29,95/23,77/19,1/17,11/13,13/11,15/14,15/2,55/1]as$n){$a=$t*$n;if(preg_match('/^\d+$/',$a)){$t=$a;break;}}}echo$t;

```

Ungolfed:

```
<?php
$t=2;
for(;@$i++<$argv[1];){
    foreach([17/91,78/85,19/51,23/38,29/33,77/29,95/23,77/19,1/17,11/13,13/11,15/14,15/2,55/1] as $n){
        $a=$t*$n;
        if(preg_match('/^\d+$/',$a)){
            $t=$a;break;
        }
    }
}
echo $t;

```

Try it online!

# Answer
> 0 votes
# MMIX, 84 bytes (14 instrs + 28 data bytes)

jxd (everything from `5b553326` (`[U3&`) on is data)

```
00000000: e3010002 f7010000 5a000002 f8020000  ẉ¢¡£ẋ¢¡¡Z¡¡£ẏ£¡¡
00000010: f402000a 83030200 1e040103 feff0006  ṡ£¡½³¤£¡œ¥¢¤“”¡©
00000020: 23020201 5bfffffc 8303020d 1a010304  #££¢[””‘³¤£Æȷ¢¤¥
00000030: 27000001 f1fffff5 5b553326 211d1713  '¡¡¢ȯ””ṫ[U3&!øçŒ
00000040: 110d0b0e 0201114e 13171d4d 5f4d010b  ×Æ¿Ç£¢×NŒçøM_M¢¿
00000050: 0d0f0f37                             ÆĐĐ7

```

Disassembly and explanation:

```
primegm SET  $1,2           // i = 2
        PUT  rD,0           // prep for division
0H      PBNZ $0,1F          // loop: if(steps) goto pass
        POP  2,0            // return i
1H      GETA $2,0F          // pass: den = &denoms
1H      LDBU $3,$2          // try: d = *den
        DIVU $4,$1,$3       // n = i / d
        GET  $255,rR        // r = i % d
        ADDU $2,$2,1        // den++
        PBNZ $255,1B        // if(r) goto try
        LDBU $3,$2,13       // d = den[13] (the numerator)
        MULU $1,$3,$4       // i = n * d
        SUBU $0,$0,1        // steps--
        JMP  0B             // goto loop
0H      BYTE 91,85,51,38,33,29,23,19,17,13,11,14,2,1    // denoms: [BYTES]
        BYTE 17,78,19,23,29,77,95,77,1,11,13,15,15,55   // nums: [BYTES]

```

It's quite useful that every single numerator and denominator fits into one byte. Else I'd have needed to use much more space to fit them.

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