title: Surreal Numbers

text:
# Question
Title: Surreal Numbers
Surreal Numbers are one way of describing numbers using sets. In this challenge you will determine the value of a surreal number.

# Intro

A surreal number consists of two sets: a left and right. The value of the surreal number must be greater than all numbers in the left set and less than all numbers in the right set. We define 0 as having nothing in each set, which we write as `{|}`. Each surreal number also has a birth date. 0 is born on day 0. On each successive day, new surreal numbers are formed by taking the numbers formed on previous days and placing them in the left/right sets of a new number. For example, `{0|} = 1` is born on day 1, and `{|0} = -1` is also born on day 1.

To determine the value of a surreal number, we find the number "between" the left and right sets that was born earliest. As a general rule of thumb, numbers with lower powers of 2 in their denominator are born earlier. For example, the number `{0|1}` (which is born on day 2 by our rules) is equal to `1/2`, since 1/2 has the lowest power of 2 in its denominator between 0 and 1. In addition, if the left set is empty, we take the largest possible value, and vice versa if the right set is empty. For example, `{3|} = 4` and `{|6} = 5`.

*Note that `4` and `5` are just symbols that represent the surreal number, which just happen to align with our rational numbers if we define operations in a certain way.*

Some more examples:

```
{0, 1|} = {1|} = {-1, 1|} = 2
{0|3/4} = 1/2
{0|1/2} = 1/4
{0, 1/32, 1/16, 1/2 |} = 1

```

# Input

A list/array of two lists/arrays, which represent the left and right set of a surreal number. The two lists/arrays will be sorted in ascending order and contain either dyadic rationals (rationals with denominator of 2^n) or other surreal numbers.

# Output

A dyadic rational in either decimal or fraction form representing the value of the surreal number.

# Examples

```
Input -> Output
[[], []] -> 0
[[1], []] -> 2
[[], [-2]] -> -3
[[0], [4]] -> 1
[[0.25, 0.5], [1, 3, 4]] -> 0.75
[[1, 1.5], [2]] -> 1.75
[[1, [[1], [2]]], [2]] -> 1.75

```

This is , so shortest code wins.

# Answer
# Python 3.7, ~~228~~ ~~197~~ 184 bytes

Thanks to @LyricLy and friends for helping me golf this down a lot

`1e999` stolen from @Quintec's solution

```
m=1e999
g=lambda p:[f(*x)if[]==x*0else x for x in p]
def f(l,h):
 h=min(g(h+[m]));l=max(g(l+[-m]));s=1
 while h-l<=1:l*=2;h*=2;s*=2
 return-(-h//1+1)/s if h<=0else l*h>=0and(l//1+1)/s

```

Try it online!
> 3 votes

# Answer
# Python, ~~371~~ ~~362~~ ~~261~~ ~~251~~ ~~248~~ ~~241~~ ~~236~~ ~~234~~ 231 bytes

*-122 bytes thanks to @ASCII-only*

```
def f(s):
 if s<[]:return s
 a=map(f,s[1]+[1e999,-1e999]+s[0]);m,n,u=a[-1],a[0],1
 while n-m<=1:m*=2;n*=2;u/=2.
 x,y=abs(m)-1,abs(n)-1;s=m>0>n or m<0<n;r=[[m-x*s,m+x*s][m<0]+1,[n-y*s,n+y*s][n<0]-1][x>y];return u*int([0,r][`r`<"m"])

```

Try it online!
> 1 votes

---
Tags: code-golf, math, number, rational-numbers, set-theory
---


title: Solve a 2xN Maze

text:
# Question
Title: Solve a 2xN Maze
Given a \\$2\times N\\$ maze, determine if you can get from the start top left corner to end bottom right corner using only up, down, left, and right moves.

## Input

A \\$2\times N\\$ block (\\$1 \le N \le 100\\$) of your choice of two distinct characters, one representing walls and the other representing empty tiles that can be moved through. You may use any reasonable input format, ex. one string with newline, two strings, or two lists of characters, or a binary matrix.

It is guaranteed the start and end positions are empty tiles.

## Output

Truthy or Falsey value indicating if the maze is solvable.

## Examples

In these test cases, `x` represents wall and `.` represents empty tile.

### True cases

```
.
.

```

```
..
x.

```

```
.x
..

```

```
...
...

```

```
..x
x..

```

```
....
..x.

```

```
.x...x...
...x...x.

```

```
...xx.....x
xx.....xx..

```

### False cases

```
.x
x.

```

```
.x.
.x.

```

```
.xx
xx.

```

```
.xxx.
..x..

```

```
..x.
xxx.

```

```
.xx.x..
..xx...

```

```
.....x.x.
xxx.x....

```

```
....xx.xxx
.....xxx..

```

# Answer
> 15 votes
# APL (Dyalog Unicode), 8 bytes

```
∧/⍲⌿2∨/⎕

```

Try it online!

Takes input from stdin as a 2-row boolean matrix, where 1 is a wall and 0 is a space. Prints 1 for true, 0 for false (which are the only truthy/falsy values in APL).

### How it works

Given a maze (1=wall, 0=space)

```
0 0 1 0 0 0 1
1 0 0 1 1 0 0

```

Think of putting a bar between every two horizontally adjacent cells, where at least one side must be a wall (1):

```
0   0 | 1 | 0   0   0 | 1
1 | 0   0 | 1 | 1 | 0   0
          ^

```

Then the maze has a solution if and only if no two bars align vertically, as pointed above.

```
∧/⍲⌿2∨/⎕
       ⎕  ⍝ Take input from stdin
    2∨/   ⍝ Compute the "bars" in the above diagram,
          ⍝ by ORing every two horizontally adjacent bits
  ⍲⌿      ⍝ Compute NAND of the two bars vertically;
          ⍝ each column is passable unless both rows are 1
∧/        ⍝ Reduce by AND; check if all columns are passable

```

# Answer
> 14 votes
# Python 2, 26 bytes

```
lambda m,n:m&(n/2|n|2*n)<1

```

Try it online!

Takes inputs as numbers representing bit sequences, which the challenge author okayed. Though I realized this representation is kind-of suspect because leading zeroes are ambiguous.

The idea is to check whether any 1 in the top number (x symbol in the top line) corresponds to a 1 in any of the three adjacent positions in the below number. We do this by "smearing" each bit the bottom number `n` in three positions as `n/2|n|2*n`, or-ing the number with its left and right shift.

It would also work to do `(m|m*2)&(n|n*2)<1`, but precedence means more parens are needed.

# Answer
> 11 votes
# Ruby, ~~29~~ 28 bytes

```
->t,b{"#{t+2*b}"!~/45|54|6/}

```

Try it online!

Takes input as two integers, `t` and `b`, each representing a row of the maze, with digits `1` representing empty tiles and `2` representing walls. Returns `false` if `t+2*b` contains the digits `45` or `54` (two walls touch diagonally) or `6` (two walls touch vertically). Returns `true` otherwise.

It's possible to get down to 22 bytes by porting @xnor's very elegant Python 2 answer: Try it online!

# Answer
> 11 votes
# Regex (POSIX ERE / RE2 or better), ~~13~~ 10 bytes

```
x(|
|.
.)x

```

Try it online! \- POSIX ERE
Try it on regex101 \- RE2
Try it online! \- ECMAScript
Try it online! \- .NET

The problem statement didn't say anywhere that there specifically had to be \\$2\\$ rows and \\$N\\$ columns rather than \\$2\\$ columns and \\$N\\$ rows, or that the input can't be taken in transposed form.

So here is a solution that works on virtually any regex engine. Like A username's answer, this matches iff the maze is ***not* solvable**. The wall character is `x`, and empty tiles can be represented by any other character.

# Regex (POSIX ERE / RE2 or better), ~~33~~ ~~30~~ 27 bytes

```
^((''
|^)(('.
)*|(.'
)*))*$

```

Try it online! \- POSIX ERE
Try it on regex101 \- RE2
Try it online! \- ECMAScript
Try it online! \- .NET

This is version that matches **solvable** mazes and doesn't match unsolvable mazes. It was interesting to implement in a regex flavor that has no negative lookahead. The way it works is pretty much like actually walking through the maze and solving it.

The empty tile character is `'`, and walls can be represented by any other character. The input given to this regex must not begin with a newline, and must end with a single newline.

The version of POSIX ERE on TIO treats newlines incorrectly in this version, even though with `REG_NEWLINE` not set, newline is supposed to be treated like any normal character. So in the ERE test harness, I made it use `!` as a line separator instead of newline. But when tested locally on my machine, it works with actual newlines.

# Regex (GNU ERE or better), ~~29~~ 24 bytes

```
^((''
|^)(.?'.?
)?\3*)*$

```

Try it online! \- GNU implementation of POSIX ERE, old version
Try it on regex101 \- ECMAScript
Try it online! \- ECMAScript
Try it online! \- .NET

The addition of backreferences allows for a more compact regex. But there doesn't seem to be a clear-cut standard that includes backreferences without lookaheads. The closest appears to be GNU ERE, used by egrep and sed `-E`, but there doesn't seem to be any library interface for it, and neither of those utilities support matching raw newlines.

The version of GNU libc on TIO enables backreferences in ERE, but with an up-to-date version of the libraries, they're only enabled in BRE, not ERE. The version on TIO has the newline bug, though, so same workaround for newlines is used in the TIO test harness.

The empty tile character is `'`, and walls can be represented by any other character. Matches iff the maze is **solvable**. The input given to this regex must not begin with a newline, and must end with a single newline.

# Regex (ECMAScript or better + `/s` flag), 17 bytes

```
^(?!.*x(|
|.
.)x)

```

Try it on regex101 \- ECMAScript 2018
Try it online! \- ECMAScript 2018
Try it online! \- .NET

With negative lookahead it is trivial to modify the 10 byte regex into one that matches iff the maze is **solvable**.

As in the regex it's based on, the wall character is `x`, and empty tiles can be represented by any other character.

Note that the `/s` flag was introduced in ECMAScript 2018 (JavaScript ES9).

# Regex (Perl / Java / PCRE2 / .NET), 29 bytes

```
^(.(?=.*
(\2.|)))+x.*
\2.?.?x

```

Try it online! \- Perl
Try it on regex101 \- PCRE2
Try it online! \- .NET

This takes the input in the form of \\$2\\$ rows of \\$N\\$ columns. The challenge just wouldn't be complete with that submitted only in .NET flavor and not PCRE as well. Matches iff the maze is ***not* solvable**. The wall character is `x`, and empty tiles can be represented by any other character.

The .NET balanced group method is still shorter (at 27 bytes), as expected.

This solution takes advantage of the fact that the upper-left corner will never be blocked. It would need to be modified otherwise, because it looks for a wall in the top row that has a wall diagonally or orthogonally below it. It starts this search at the second column from the left.

# Answer
> 5 votes
# , 19 17 bytes

```
0=1#.[:,*&#./;._3

```

Try it online!

-2 thanks to Bubbler for suggesting Max Cubes instead of subarrays.

A port of Bubbler's APL solution saves 1 byte:

```
2 e.[:+/2+./\"1]

```

but it seemed a shame not use J "Max Cubes" here, as the problem seems almost tailor-made for it.

## How

Let's take the example:

```
0 1 1 1 0 0
0 0 0 0 1 0

```

`v;._3` will apply the verb `v` to every 2x2 block. Eg, `<;._3` will produce:

```
┌───┬───┬───┬───┬───┐
│0 1│1 1│1 1│1 0│0 0│
│0 0│0 0│0 0│0 1│1 0│
└───┴───┴───┴───┴───┘

```

In our case, we want a verb that detects "walls" (diagonal or vertical). `*/@:#.` does the job. It converts each row from a binary number into an integer `#.`, and then multiplies the resulting 2 integers together `*/@:`. This result will always be `0` if there is no wall.

So now we can just sum all of the results `1#.` and check if the result is 0 `0=`. If it is, there are no walls and we can get through. Otherwise, we're blocked.

# Answer
> 5 votes
# Snails, 7 bytes

Based on @xnor's observation, this checks if there are `x`s above (`u`), below (`d`) or diagonally from (`y`) another `x`. Returns `0` for solvable mazes a positive integer otherwise. I've wanted to use this language for so long!

```
\xudy\x

```

Try it online!

## Explanation

Snails is a 2D pattern matching language that was created by @feresum which is not entirely unlike regex.

In this program, the `\x` matches a literal `x`, then looks above, below or diagonally to it (`udy`) for another literal `x` (`\x`).

# Answer
> 4 votes
# MATL, ~~10~~ ~~9~~ 7 bytes

```
4&1ZI2<

```

Input is a binary matrix, with `1` for `.` and `0` for `x`.

Output is an array of ones (which is truthy) if the maze is solvable, or an array containing at least a zero (which is falsey) if not solvable.

Try it online! Or verify all test cases including check for truthyness or falsiness.

# Explanation

### Solvability is equivalent to full connectedness of all non-wall tiles

The maze is solvable if and only if all non-wall tiles are connected to each other using 4-neighbourhood.

**Proof**

*All connected ⇒ solvable*: this is clear.

*Solvable ⇒ all connected*. Let the maze be

```
A ··· SUWY
B ··· TVXZ

```

This maze is solvable by assumption. Consider its rightmost square of size 2:

```
WY
XZ

```

There are two ways that `Z` can be connected to the input:

* Through tiles `W` and `Y`: this means that `W` and `Y` are non-wall. They are connected to `Z`. If `X` is non-wall it is connected to `W`, `Y` and `Z` too.
* Through tile `X`: this means that `X` is non-wall. It is connected to `Z`. If `W` or `Y` are non-wall they are connected to `X` and `Z` too.

We now proceed from either `W` or `X` to the left, considering the square

```
UW
VX

```

By the same reasoning as above, all non-wall tiles in this square will be connected to each other, and to the tiles from the previous square.

This way we proceed until `A` is reached (which is possible by hypothesis), and all non-wall tiles are connected.

### How the code works

The program checks that the image formed by considering wall tiles as background and non-wall tiles as foreground has a single connected component.

```
4      % Push 4
&1ZI   % Implicit input: binary matrix. Label connected components using
       % 4-neighbourhood. This assigns a different label to each connected
       % component of ones in the input. Labels are positive integers. The
       % result is a matrix of the same size as the input
2<     % Less than 2? Element-wise. All comparisons will be true if and
       % only if there is a single connected component
       % Implicit diplay

```

# Answer
> 4 votes
# , 38 bytes

```
function(t,b)all(c(b[-1],T,b,T,b)[!t])

```

Try it online!

Checks that the bottom row is 'open' at position x-1, x and x+1 for every 'closed' position in the top row.

How?

* consider matrix of 3 rows:

1. remove first item from bottom row of maze + add `1` at the end
2. bottom row of maze
3. add `1` at the start of the bottom row of maze without last item

* check that all elements are `1` in columns where top row of maze is `0`

Golfing:

* R 'recycles' logical indices, so we don't actually need to make a matrix, we can just list the elements
* no need to remove the last item of the bottom row of maze since it's guaranteed to be true

# , a different approach, still 38 bytes

```
function(t,b)all(t&t[-1]|b&c(b[-1],1))

```

Try it online!

Completely different approach, but annoyingly the same number of characters. Checks that it's always possible to move rightwards, either on the top or on the bottom.

How?

`top & top[-1]` = logical AND of each element of `top` with it's neighbour to the right

`|` = logical OR

`bot & bot[-1]` = logical AND of each element of `bot` with it's neighbour to the right

The last element (that has no rightward neighbour) is a problem, because R 'wraps around' the longer vector, so if the last top element is `0` and the first bottom element is `0` then it will fail. We can fix this by forcing it to evaluate to `TRUE`, which we can do by adding a `1` at the end of the 'chopped-off' bottom row (since we know the last element of the full-length row must be 1).

# Answer
> 4 votes
## Excel, 38 bytes

```
=AND(ISERROR(FIND({12,3,21},A1+2*A2)))

```

Input is 2 strings (1 for each row of the maze), in cells `A1` and `A2`, with `1` for a Wall, and `0` for a space.

First, it adds the first row, and twice the second row together. This will convert each column to base-4 representation of whether it contains no walls (`0`), wall in the top row only (`1`), wall in the bottom row only (`2`), or wall in both rows (`3`)

We then try to `FIND` any examples where there are walls in both rows (`3`), **or** walls in different rows of adjacent columns (`12` or `21`)

If both of these return errors, then there is a clear path

# Answer
> 4 votes
# Regex (.NET), ~~35~~ ~~31~~ 27 bytes

```
^(.)* ?#.*
(?>(?<-1>.)*) ?#

```

This had to be done. Checks if the string contains one of the following (uses #s and spaces) :

```
 #
#

```

```
#
#

```

```
#
 #

```

Matches impassible grids, doesn't match passible ones.

See Martin Ender's excellent capture group documentation.

Try it online!

Thanks to Deadcode for -9 bytes.

# Answer
> 4 votes
# Jelly, 4 bytes

```
+ƝẠƇ

```

Try it online!

Takes a list of pairs, where `0` represents a path and `1` represents a wall. Returns a falsy value if the maze is solvable and a truthy value if not.

# Jelly, 6 bytes

```
ḋ×ṛɗ/Ẹ

```

Try it online!

Takes a list of pairs, where `0` represents a wall and `1` represents a path. Returns `1` if the maze is solvable and `0` if not.

# Answer
> 3 votes
# Charcoal, ~~26~~ 23 bytes

```
⭆⪫Ｅ²Ｓ¶⎇⁼ι.ψι←¤-Ｊ⁰¦⁰Ｔ¹¦¹

```

Try it online! Link is to verbose version of code. Takes two strings of `.`s and `x`s as input (actually any character other than space or `.` would work) and outputs `-` if the maze can be solved or a blank space if it cannot. Edit: Saved 3 bytes because I had misread the question. Explanation:

```
⭆⪫Ｅ²Ｓ¶⎇⁼ι.ψι

```

Print the input, but change all the `.`s to null bytes, since Charcoal knows how to fill those.

Move to the end position.

```
¤-

```

Flood fill the null bytes with `-`s (chosen because this is Charcoal's default output character for a Boolean true value, but any character other than space would work).

```
Ｊ⁰¦⁰

```

Jump back to the start position.

```
Ｔ¹¦¹

```

Delete everything other than the start position, which is now `-` if the maze could be solved, or blank if it could not be solved.

# Answer
> 3 votes
# Perl 5 `-p0`, 67 bytes

```
$x=$_;$_=!grep{$b=$_-1;$x=~/^.{$b,$_}x.*?\n.{$b,$_}x/gm}1...5*y///c

```

Try it online!

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

```
Max@MorphologicalComponents[#,CornerNeighbors->1<0]<2&

```

Try it online!

Credit for this idea goes to this answer by alephalpha from a couple years ago, where it used in a different context.

The core insight here is that -- if the maze can be solved -- then the "spaces" form a single contiguous morphological chunk. And Wolfram has a built-in for detecting that.

# Answer
> 2 votes
# Io, 90 bytes

```
method(x,y,x map(i,v,v>0and(list(i-1,i,i+1)map(c,y at(c abs))detect(>0)))reduce(or)!=true)

```

Try it online!

# Io, 98 bytes

Port of Bubbler's APL solution.

```
method(x,(o :=x map(o,o slice(0,-1)map(i,v,v+o at(i+1))))at(0)map(i,v,v*o at(1)at(i))push(0)sum<1)

```

Try it online!

# Answer
> 2 votes
# 05AB1E (legacy), 7 bytes

Port of @Bubbler's answer.

```
€ü~øP_P

```

Try it online!

## Explanation

```
€       Map:
 ü          Apply to pairs:
  ~             OR
   ø    Transpose
    P   Product
     _  NOT
      P Product

```

# Answer
> 2 votes
# Haskell, ~~53~~ 51 bytes

```
or.map(or.foldr1(zipWith(&&))).mapM(\x->[x,tail x])

```

Try it online!

The anonymous function takes a list of two lists where True is a wall and False is empty. Returns False if the maze is solvable.

# Answer
> 1 votes
# Prolog, 99 bytes

```
f([[1,_],[_,1]|_]):- !,0=1.
f([[_,1],[1,_]|_]):- !,0=1.
f([[1,1]|_]):- !,0=1.
f([_|T]):-T==[];f(T).

```

Try it in SWISH

xnor's comment that the problem statement was equivalent to checking if no 2 x's touched vertically or diagonally helped me a lot here.

---

## Imperfect version (never terminates if false), 66 bytes

```
f([X|T],C):-nth0(C,X,0),(T==[];f(T,C);D is mod(C+1,2),f([X|T],D)).

```

Try it in SWISH

Requires the first input to be a list of length N containing lists of length 2. Empty tiles are denoted by 0, and walls are denoted by anything else (I could also have used characters, I suppose, but this seemed easier). The second input (`C`) is 0 if we're currently at the tile on top, and 1 if we're at the tile on the bottom.

An example query would be:

```
?- f([[0,1],[0,1],[0,0],[1,0],[1,0],[0,0],[0,0],[0,1],[0,1],[0,0],[1,0]],0).
true.

```

However, if the maze is unsolvable, there wouldn't be any output, it'd just keep running.

# Answer
> 1 votes
# JavaScript, 63 bytes

```
n=>k=>!n.filter((e,i)=>e>0&[k[i-1],k[i],k[i+1]].includes(1))[0]

```

Takes input in currying format, each argument being an array of 1s and 0s. Outputs `true` if the maze is solvable and `false` if unsolvable.

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


# Question
Title: Easier communication means faster coding means fewer coders means …
My father who was a really good APLer and taught me all the basics of APL (and much more), passed away on this day, five years ago. In preparation for 50 Years of APL, I found this patent letter (translated for the convenience of those who do not read Danish) for a handwritten logo. It explains a major reason for APL never gaining a large user base – a reason which of course applies to all of this community's amazing golfing languages too:

---

A 3497/77 Req. 29th Aug. 1977 at 13

**Henri Brudzewsky,** engineering consultancy company, **Mindevej 28, Søborg,**

**class 9**, including computers, especially APL coded computers,
**class 42:** IT service agency company, especially during use of APL coded computers.

---

# Task

**Produce infinitely repeating output of the text `EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS`  with no newlines.** You may begin the text with `EASIER` or `FASTER` or `FEWER`.

# Answer
# 05AB1E, 25 bytes

```
[‘Ã¦ƒËRSˆ¾¥ƒŽÁˆ¾¡ŸÂïˆ¾ ‘?

```

Try it online!

Explanation:

```
[‘Ã¦ƒËRSˆ¾¥ƒŽÁˆ¾¡ŸÂïˆ¾ ‘?
[                         Start infinite loop
 ‘Ã¦ƒËRSˆ¾¥ƒŽÁˆ¾¡ŸÂïˆ¾ ‘   Push the compressed string in uppercase, starting from FEWER, with a trailing space
                        ?  Print without trailing newline

```
> 15 votes

# Answer
## SVG(HTML5), 336 bytes

```
<svg width=500 height=500><defs><path id=p d=M49,250a201,201,0,0,1,402,0a201,201,0,0,1,-402,0></defs><text font-size="32"><textPath xlink:href=#p>EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS</textPath><animateTransform attributeName=transform type=rotate from=360,250,250 to=0,250,250 dur=9s repeatCount=indefinite>
```

Edit: Some people have found that the font doesn't quite fit for them so here is a version that allows you a few pixels of adjustment:

```
<p><input type=number value=0 min=0 max=9 oninput=p.setAttribute('d','M250,250m20_,0a20_,20_,0,1,1,-20_,-20_a20_,20_,0,1,1,-20_,20_a20_,20_,0,1,1,20_,20_a20_,20_,0,1,1,20_,-20_'.replace(/_/g,this.value))></p>
<svg width=500 height=500><defs><path id=p d=M250,250m200,0a200,200,0,1,1,-200,-200a200,200,0,1,1,-200,200a200,200,0,1,1,200,200a200,200,0,1,1,200,-200></defs><text font-size="32"><textPath xlink:href=#p>EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS</textPath><animateTransform attributeName=transform type=rotate from=360,250,250 to=0,250,250 dur=9s repeatCount=indefinite>
```
> 41 votes

# Answer
# PHP, 76 Bytes

```
for(;;)echo strtr(EASI0MMUNICATION1FAST0DING1FEW0DERS1,["ER CO"," MEANS "]);

```

Try it online!
> 13 votes

# Answer
# Vim 69 bytes

```
qqAFEWER CODERS MEANS EASIER COMMUNICATION M<C-n> FASTER CODING M<C-n> <esc>@qq@q

```
> 12 votes

# Answer
# Python 2, ~~82~~ 81 bytes

*-1 byte thanks to Leaky Nun.*

I'm probably doing something wrong but it's really late so meh. Note the trailing comma.

```
while 1:print'FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS',

```

Try it online!

## Another solution, 85 bytes

I can probably golf this further.

```
while 1:print'%sER CO%s MEANS'*3%('FEW','DERS',' EASI','MMUNICATION',' FAST','DING'),

```

Try it online!
> 6 votes

# Answer
## HTML, 122 bytes.

Sorry, can't help myself.

```
<marquee style="width:5em;word-spacing:5em;">EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS </marquee>
```
> 6 votes

# Answer
# Jelly, ~~33~~ 29 bytes

4 bytes thanks to Erik the Outgolfer.

```
“©%5ÐƬwȮh¬Þ6.⁷ḷḊḥṫɠlḶṀġß»Œu⁶¢

```

Try it online!
> 5 votes

# Answer
# Brachylog, 70 bytes

```
"FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS "w↰

```

Try it online!

## How it works

```
"..."w↰
"..."     generate the string "..."
     w    print to STDOUT without trailing newline
      ↰   do the whole thing all over again

```
> 5 votes

# Answer
# HTML/CSS (firefox only), ~~179~~ ~~177~~ ~~183~~ ~~176~~ 173 bytes

```
<b id=a>EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS </b>E<a><style>*{margin:0;}a{position:fixed;left:0;right:0;height:1em;background:-moz-element(#a)}

```

Certianly nowhere near the lowest scores, I just thought it would be fun to get infinite repitition in HTML/CSS, without any JS involved :)

## Changelog:

* Removed quotes around id attribute
* added "round" background-repeat to stretch the text so it wraps correctly
* changed to single-line output
* replace `width:100%` style with `right:0` to save 3 bytes
> 4 votes

# Answer
# Python 3, 87 bytes

```
while 1:print(end="FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ")

```

Try it online!
> 3 votes

# Answer
# C (gcc), 92 bytes

```
main(){for(;printf("FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS "););}

```

Try it online!
> 3 votes

# Answer
# LOLCODE, 116 bytes

```
HAI 1
IM IN YR O
VISIBLE "FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS "!
IM OUTTA YR O
KTHXBYE

```

Try it online!
> 3 votes

# Answer
# Ruby, 77 bytes

assigning `" MEANS "` to a variable saved all of 1 byte :-)

```
loop{$><<"EASIER COMMUNICATION#{m=" MEANS "}FASTER CODING#{m}FEWER CODERS"+m}

```
> 3 votes

# Answer
# JavaScript (ES6), ~~90~~ 87 bytes

```
while(1)console.log`EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS `

```

---

## Functioning Alternative, 100 bytes

"Functioning" here meaning "won't crash your browser" (for a while, at least)!

```
setInterval(_=>console.log`EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS `,1)

```
> 3 votes

# Answer
# Befunge, 73 bytes

```
" SNAEM GNIDOC RETSAF SNAEM NOITACINUMMOC REISAE SNAEM SREDOC REWEF">:#,_

```

Try it online!
> 2 votes

# Answer
# Octave, 86 bytes

```
while fprintf('FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ')end

```

**Explanation:**

This is fairly self-explanatory. The only real "trick" here is to use `while fprintf`. When `fprintf` is given a return argument, it will return the number of characters printed, and all non-zero numbers are considered `true` in Octave, so the loop condition will always be true.

---

I desperately tried to make the more interesting approach shorter, but it turned out to be 9 bytes longer, unfortunately:

```
while fprintf('FEW%sDERS%sEASI%sMMUNICATION%sFAST%sDING%s',{'ER CO',' MEANS '}{'ababab'-96})end

```

This tries to insert the strings `'ER CO'` and `' MEANS'` into the string at the correct locations, using direct indexing where `'ababab'-96` is a shorter version of `[1 2 1 2 1 2]`.

This was a bit shorter (93 bytes), but still longer than the naive approach

```
while fprintf('FEWER CODERS%sEASIER COMMUNICATION%sFASTER CODING%s',{' MEANS '}{[1,1,1]})end

```

And another one (89 bytes), using Level River St's approach:

```
while fprintf(['FEWER CODERS',s=' MEANS ','EASIER COMMUNIDATION',s,'FASTER CODING',s])end

```

This should work in theory, for one less byte than the original solution, but it fails for some strange reason:

```
while fprintf"FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS "
end

```

This uses the buggy feature that `fprintf('abc def')` is equivalent to `fprintf"abc def"`. The `end` must be on the next line, but it's still one byte shorter since two parentheses are skipped.

And one more for 87:

```
while fprintf('FEWER CODERS%sEASIER COMMUNICATION%sFASTER CODING%s',k=' MEANS ',k,k)end

```

---

Well, don't say I didn't try :)
> 2 votes

# Answer
## Alice, 70 bytes

```
" SNAEM "k"SREDOC REWEF"e0j"GNIDOC RETSAF"e0j"NOITACINUMMOC REISAE"d&o

```

Try it online!

### Explanation

Unfortunately, reusing the `MEANS` (with spaces) only saves a single byte over just printing the whole thing in one go. Consequently, extracting the `ER CO` would actually cost a byte (or probably more, because it would be slightly more expensive to extract another section).

```
" SNAEM "                Push the code points of " MEANS " in reverse.
k                        If there is a return address on the return address stack (which
                         there isn't right now), pop it and jump there.
"SREDOC REWEF"           Push the code points of "FEWER CODERS" in reverse.
e0j                      Jump to the beginning of the line, pushing the location of the
                         j to the return address stack. Hence, we push the code points
                         of " MEANS " again, but then the k pops the return address and
                         jumps back here.
"GNIDOC RETSAF"          Push the code points of "FASTER CODING" in reverse.
e0j                      Jump to the beginning of the line again.
"NOITACINUMMOC REISAE"   Push the code points of "EASIER COMMUNICATION" in reverse.
d                        Push the stack depth.
&o                       Print that many bytes from the top of the stack.
                         Afterwards the IP wraps around to the first column and the
                         program starts over.

```
> 2 votes

# Answer
## C#, 102 bytes

```
_=>{for(;;)System.Console.Write("EASIER COMMUNICATION{0}FASTER CODING{0}FEWER CODERS{0}"," MEANS ");};

```
> 2 votes

# Answer
# AWK, 85 bytes

```
BEGIN{for(c=" MEANS ";;)printf"EASIER COMMUNICATION"c"FASTER CODING"c"FEWER CODERS"c}

```

Try it online!

Apparently I came up with the same shortcut as others. All other substitutions take up too much space. :(
> 2 votes

# Answer
# Retina, ~~64~~ 60 bytes

```
+>(`$
EASI_MMUNICATION@FAST_DING@FEW_DERS@
@
 MEANS
_
ER CO

```

Try it online!

### Explanation

The program consists of three grouped replacement stages. The group as a whole is applied repeatedly until the output stops changing (which it never will) and the output is printed after each time (rather than just at the end, because there will be no end)

The first stage adds the string `EASI_MMUNICATION@FAST_DING@FEW_DERS@` at the end of the input. The input starts out empty, but keeps growing.

The second stage replaces each of those `@`s with the string `MEANS` (surrounded by a space on each side).

The third stage replaces the `_`s with the string `ER CO`.
> 2 votes

# Answer
# Pyth, 69 bytes

```
Wp"FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS

```

Try it online!

## How it works

```
Wp"...
W       while the following is true: (do nothing)
 p      print the following and return the following
  "...

```
> 1 votes

# Answer
# Lua, 92 bytes

```
while 1 do io.write("FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ")end

```

Try it online!
> 1 votes

# Answer
# Java (OpenJDK 9), 114 bytes

```
static void f(){while(1>0)System.out.print("FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ");}

```

Try it online! Stop the execution after a few seconds because it does not know when to stop.
> 1 votes

# Answer
## C, 86 bytes

```
f(){printf("FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ");f();}

```

See it work online.
> 1 votes

# Answer
# bc, 76 bytes

```
while(1)"EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS "

```
> 1 votes

# Answer
# MATL, 68 bytes

```
`'EASIER COMMUNICATION*FASTER CODING*FEWER CODERS*'42' MEANS 'Zt&YDT

```

Try it online!

### Explanation

```
`                                                     % Do...while
  'EASIER COMMUNICATION*FASTER CODING*FEWER CODERS*'  %   Push this string
  42                                                  %   Push 42 (ASCII for '*')
  ' MEANS '                                           %   Push this string
  Zt                                                  %   String replacement
  &YD                                                 %   printf to STDOUT
  T                                                   %   Push true as loop condition
                                                      % End (implicit)

```
> 1 votes

# Answer
# Perl 6,  ~~81 80~~  79 bytes

```
print ('EASIER COMMUNICATION','FASTER CODING','FEWER CODERS'X'MEANS'),' 'for ^Inf

```

Try it

```
loop {print ('EASIER COMMUNICATION','FASTER CODING','FEWER CODERS'X'MEANS'),' '}

```

Try it

```
loop {print [~] 'EASIER COMMUNICATION','FASTER CODING','FEWER CODERS'X'MEANS '}

```

Try it
> 1 votes

# Answer
# Axiom, ~~92~~ 89 bytes

```
repeat fortranLiteral"EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS "

```

insert in one line to Axiom window. Possible there is one function shorter than "fortranLiteral" that not write "\n"
> 1 votes

# Answer
# Braingolf, 77 bytes

```
"FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS "[!&@<1+>]

```
> 1 votes

# Answer
# Blank, 267 bytes

```
[70][69][87][69][82][32][67][79][68][69][82][83][32][77][69][65][78][83][32][69][65][83][73][69][82][32][67][79][77][77][85][78][73][67][65][84][73][79][78][32][77][69][65][78][83][32][70][65][83][84][69][82][32][67][79][68][73][78][71][32][77][69][65][78][83][32]{p}

```

Pushes `FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS` to the stack, then prints it. Never terminates as no `{@}`

Also fun fact, I used the following Braingolf script to generate this code

```
"FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS "l>[<$_<91+2^9-@_ 91+2^7-@l>]"{p}"@3

```
> 1 votes

# Answer
# PowerShell, 100 97 bytes

```
for(){"EASIER COMMUNICATION","FASTER CODING","FEWER CODERS"|%{Write-Host -NoNewLine "$_ MEANS "}}

```

Try it online!

---

Older answer:

# PowerShell, 100 bytes

```
while(1){"EASIER COMMUNICATION","FASTER CODING","FEWER CODERS"|%{Write-Host -NoNewLine "$_ MEANS "}}

```

Try it online!

PowerShell is a little tricky for this because most dignified ways of outputting to the console also insert a new line. `Write-Host` is required because of this. However, it still demonstrates how pipelining can shorten the coding footprint.

You will need to stop the execution after a short time because it will not return as it is an infinite loop.

Edit: shaved off 3 bytes by changing a `while` loop to a `for` loop.
> 1 votes

# Answer
# Groovy 79 bytes

```
m=" MEANS";for(;;)print"EASIER COMMUNICATION$m FASTER CODING$m FEWER CODERS$m "

```

Uses groovy's string interpolation.
> 1 votes

# Answer
# Ly, 75 bytes

```
1[p"EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS "&o1]

```

Try it online!

Explanation:

```
1[p                                                                      1] # infinitely
   "EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS "&o   # print the string

```
> 1 votes

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

```
class c{static void Main(){for(;;)System.Console.Write("EASIER COMMUNICATION{0}FASTER CODING{0}FEWER CODERS{0}"," MEANS ");}}

```

This is a full program rather than just a function like the other C# answer.

Test online
> 1 votes

# Answer
## Keg, 69 bytes

```
{ SNAEM GNIDOC RETSAF SNAEM NOITACINUMMOC REISAE SNAEM SREDOC REWEF(,

```

Explanation:

```
{#                                                                     Infinite loop
  SNAEM GNIDOC RETSAF SNAEM NOITACINUMMOC REISAE SNAEM SREDOC REWEF#   Pushing the string reversed
                                                                   (, #And outputting it reversed

```

TIO
> 1 votes

# Answer
# Hexadecimal Stacking Pseudo-Assembly Language, 810 bytes

```
00000020002040000020005340000020004E40000020004140000020004540000020004D40000020002040000020005340000020005240000020004540000020004440000020004F40000020004340000020002040000020005240000020004540000020005740000020004540000020004640000020002040000020005340000020004E40000020004140000020004540000020004D40000020002040000020004740000020004E40000020004940000020004440000020004F40000020004340000020002040000020005240000020004540000020005440000020005340000020004140000020004640000020002040000020005340000020004E40000020004140000020004540000020004D40000020002040000020004E40000020004F40000020004940000020005440000020004140000020004340000020004940000020004E40000020005540000020004D40000020004D40000020004F400000200043400000200020400000200052400000200045400000200049400000200053400000200041400000200045400000140000010000

```

Try it online!

```
000000  Label Start:
200020
400000
.
.
.       push letters
140000  print string
010000  jump to start

```
> 1 votes

# Answer
# Whitespace, 415 bytes

```
(much whitespace)
```

Try it online!

```
lssl        label start:
sssttssssstsststtsttstsststttsstttsstsstttssstsssttttsttttsttttsttttsststttsstssststtssssstttsttttsstssttsttssttsttsstsssstssttssssssttttttstttsttsttsttstsstssssssttssststttssttttttstttstssssssttsssttsssssttssttsststttstttttttstststsstsssstttstsstsssstsssstttstttsststsssstssssttttstttssstttssttssstsssstssl
            push base 24 sentence "EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS "
lsssl       label print:
sssttsssl   24
stsstl      copy 1
stsstl      copy 1
tstt        mod
ssststttl   23
tsst        sub
lsl         dup
ltstl       jz space
ssstttsssl  push 56
tsss        add
lsstl       label space:
ssstsssssl  push 32
tsss        add
tlss        printc
tsts        div
sls         dup
ltsl        jz start
lslsl       jump print

```
> 1 votes

# Answer
# Husk, 30 bytes

```
¢ma¨ÿȦ3ċṀÏ₁ÄẋΩƒ'ŸċḋÄẋḟω≡¢oΔ₅ṁż

```

Try it online!

The battle of which language has better builtin compression.
> 1 votes

# Answer
# convey, 69 bytes

```
}'EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS '

```

Try it online!

convey outputs strings forever, which is usually annoying but sometimes helpful.
> 1 votes

# Answer
# BRASCA, 76 bytes

I should add string compression to BRASCA...

```
1[x` SNAEM SREDOC REWEF SNAEM GNIDOC RETSAF SNAEM NOITACINUMMOC REISAE`[o]1]

```

Try it online!

## Explanation

```
1[x                                                                       1]  - Infinite loop
   ` SNAEM SREDOC REWEF SNAEM GNIDOC RETSAF SNAEM NOITACINUMMOC REISAE`       - Push the string
                                                                       [o]    - Output each character

```
> 1 votes

# Answer
# Tcl, 94 bytes

```
while 1 {puts -nonewline "EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS "}

```

Try it online!
> 0 votes

# Answer
# Bash 68 bytes

```
f()(printf "%sER CO%s MEANS " EASI MMUNICATION FAST DING FEW DERS;f)

```

Try it online
> 0 votes

# Answer
# brainfuck, 657 bytes

```
+[++++[++++>---<]>++.----.>-[--->+<]>--.----------.----.+++++++++++++.--[----->++<]>.+[->++<]>+.[->+++++<]>.--..++++++++.-------.-----.------.--.>-[--->+<]>-.-----------.++++++.-.++[----->++<]>.++++++[->++<]>+.--------.----.+++++++++++++.+++++.+[--->+<]>++++.+++[->++<]>.-----.>-[--->+<]>--.+.[----->+<]>+.+++++++++++++.--[----->++<]>.+[->++<]>+.[->+++++<]>.-----------.+++++.+++++.-------.+[->++++<]>.++++++[->++<]>+.--------.----.+++++++++++++.+++++.+[--->+<]>++++.+++[->++<]>.-.>+[--->++<]>+.++[----->+<]>.+++++++++++++.--[----->++<]>.+[->++<]>+.[->+++++<]>.-----------.+.+++++++++++++.+.+[--->+<]>++++.++++++[->++<]>+.--------.----.+++++++++++++.+++++.]

```

Try it online!
> 0 votes

# Answer
# APL NARS, 152 bytes, 76 chars

```
f
A:⍞←'EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS '⋄→A

```

I don't know if there are some leak or the buffer for output is buffered in a way increase its size. Possible i see it wrong but it seems that the size mem in NARS increase, and afther some second the output of the line disappear.
> 0 votes

# Answer
# MathGolf, 74 bytes

```
1{"EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS "_q}∟

```

Try it online!

Explantion:

```
1                                                                          Loop condition
 {                                                                         Start block
  "EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS "_q   Output the string
                                                                        }∟ Do without popping

```
> 0 votes

# Answer
# Batch 116 bytes

```
@echo off&Set M= MEANS &Set C=ER CO
For /L %%i in ()Do <nul Set/P =EASI%C%MMUNICATION%M%FAST%C%DING%M%FEW%C%DERS%M%

```

How:

* `For /L %%i in ()Do` enacts an infinite loop
* `nul set/p =` prints the trailing string without a newline.
> 0 votes

---
Tags: code-golf, string, kolmogorov-complexity, animation
---


title: Solve the Alien Probe puzzle

text:
# Question
Title: Solve the Alien Probe puzzle
## Introduction

In this TED-Ed video (which I'd recommend watching first), a puzzle is presented. 27 unit cubes must be painted with one of red, green, or purple on each face, so that they can be reassembled into a large 3x3x3 cube that shows only red on the outside, then a different arrangement that shows only green, and then only purple. One solution is presented at the end of the video, but it is not obviously generalisable (and there are lots more solutions).

Then, in this lazykh video, a simple algorithm for solving the puzzle is presented. It is as follows:

1. Paint the faces that currently make up the exterior of the large cube green
2. For each dimension of the cube (X, Y, Z), shift the arrangement of the cubes over in that direction by 1 unit
3. Repeat these steps for each colour

The lazykh video has graphics which explain the algorithm more clearly than can be done in this textual medium, so I suggest you watch that as well.

This algorithm generalises easily for higher sizes and numbers of colours than 3 (e.g. a 5x5x5 cube which must be painted with 5 different colours). Interestingly, it also generalises to higher dimensions than 3, but I'll save that for a different challenge.

## Challenge

Given the size \\$ n \\$ (where \\$ n \\$ is a positive integer) of the large cube, output *a* solution to the \\$ n \times n \times n \\$ version of this generalised puzzle.

Using the algorithm described above is certainly not the only way to find a solution, but I've included it as a starting-point. You are free to work out the solution however you choose.

Output should be given as a list of 6-tuples (or similar structure), representing the face colours of each small cube. The elements of the tuples should be from a predictable sequence of distinct values, (e.g. integers from \\$ 0 \\$ to \\$ n - 1 \\$), each representing a colour. The faces within a tuple can be in whatever order you choose but **it must be consistent**. The list should be flat and \\$ n ^ 3 \\$ in length, but its elements can be in any order (since they will need to be rearranged anyway for assembly into the \\$ n \\$ alien probes).

## Test cases

```
Input Output
1     [(0, 0, 0, 0, 0, 0)]
2     [(0, 0, 0, 1, 1, 1), (1, 0, 0, 0, 1, 1), (0, 1, 0, 1, 0, 1), (1, 1, 0, 0, 0, 1), (0, 0, 1, 1, 1, 0), (1, 0, 1, 0, 1, 0), (0, 1, 1, 1, 0, 0), (1, 1, 1, 0, 0, 0)]
3     [(0, 0, 0, 2, 2, 2), (2, 0, 0, 1, 2, 2), (1, 0, 0, 0, 2, 2), (0, 2, 0, 2, 1, 2), (2, 2, 0, 1, 1, 2), (1, 2, 0, 0, 1, 2), (0, 1, 0, 2, 0, 2), (2, 1, 0, 1, 0, 2), (1, 1, 0, 0, 0, 2), (0, 0, 2, 2, 2, 1), (2, 0, 2, 1, 2, 1), (1, 0, 2, 0, 2, 1), (0, 2, 2, 2, 1, 1), (2, 2, 2, 1, 1, 1), (1, 2, 2, 0, 1, 1), (0, 1, 2, 2, 0, 1), (2, 1, 2, 1, 0, 1), (1, 1, 2, 0, 0, 1), (0, 0, 1, 2, 2, 0), (2, 0, 1, 1, 2, 0), (1, 0, 1, 0, 2, 0), (0, 2, 1, 2, 1, 0), (2, 2, 1, 1, 1, 0), (1, 2, 1, 0, 1, 0), (0, 1, 1, 2, 0, 0), (2, 1, 1, 1, 0, 0), (1, 1, 1, 0, 0, 0)]
6     https://gist.github.com/pxeger/a82bdce4427f487490ce0df19840807a#file-6-txt
20    https://gist.github.com/pxeger/a82bdce4427f487490ce0df19840807a#file-20-txt

```

## Rules

# Answer
# Wolfram Language (Mathematica), ~~36~~ ~~34~~ ~~33~~ 30 bytes

```
#-1|#&~Array~#~Tuples~3/.#->0&

```

Try it online!

Returns a length-\\$n^3\\$ list of \\$\\{x|x',y|y',z|z'\\}\\$ colorings.

Verify with a \\$n\times n\times n\\$ matrix output.

---

Explanation:

Consider a cube \\$x\\$th from the front in some initial configuration. If the frontmost layer of cubes is painted \\$1\\$, the second \\$2\\$, etc., so that the color number increments with each shift, the front face of the cube will be painted \\$x\\$. After one more shift, the cube will be in the backmost layer, so the back face is painted \\$x+1\\$.

The same logic applies in other dimensions, so we can paint the cube at position \\$(x,y,z)\\$ with colors \\$(x,y,z,x+1,y+1,z+1)\\$ (modulo \\$n\\$).

```
#-1|#&~Array~#~Tuples~3         (* 3-tuples of {0|1, 1|2, ..., n-1|n} *)
                       /.#->0&  (* and replace n with 0. *)

```
> 11 votes

# Answer
# JavaScript (V8),  ~~113 ... 108~~  95 bytes

*Saved 2 bytes thanks to @EliteDaMyth*
*Saved 1 byte thanks to @Shaggy*

Prints the cubies.

```
n=>{for(x=n**3;x--;print(a))for(a=[c=n];c--;)for(j=6;j--;)(x/n**(j>>1)%n+c)%n^j%2*~-n?0:a[j]=c}

```

Try it online!
> 6 votes

# Answer
# Charcoal, 21 bytes

```
ＮθＦθＦθＦθＦ⟦ικλ⟧⭆²﹪⁺μνθ

```

Try it online! Link is to verbose version of code. Outputs the faces in order `162534` (relative to dice numbering). Explanation:

```
Ｎθ

```

Input `n`.

```
Ｆθ

```

Loop over the x-axis.

```
Ｆθ

```

Loop over the y-axis.

```
Ｆθ

```

Loop over the z-axis.

```
Ｆ⟦ικλ⟧

```

For each coordinate...

```
⭆²﹪⁺μνθ

```

... output it, then output it incremented modulo `n`.
> 6 votes

# Answer
# Haskell, <sup>~~39~~</sup> 36 bytes

* -3 bytes thanks to xnor.

```
f n=mapM(\_->zip<*>(n:)$[1..n])"..."

```

Try it online!

The relevant function is `f`, which takes as input the integer `n` and returns a list of \\$n^3\\$ cubes; each cube is represented as a list of three pairs, such as `[(1,2),(1,3),(2,3)]`. Each pair represents the colors of two opposite faces, and colors are numbered from `1` to `n`.

## How?

The strategy described by the OP is equivalent to the following. Consider the cube at coordinates \\$(x,y,z)\\$, with \\$1\le x,y,z\le n\\$. Paint the two faces orthogonal to the \\$x\\$ axis with colors \\$x\\$ and \\$x+1\\$ (considered \\$\mod n\\$). Similarly, color the faces orthogonal to the \\$y\\$ axis with colors \\$y\\$, \\$y+1\\$ and the faces orthogonal to the \\$z\\$ axis with colors \\$z\\$, \\$z+1\\$.

Therefore, to generate the \\$n^3\\$ colored cubes, we just have to independently pick three pairs of colors from the set $$ \\{(1,2),(2,3),\ldots,(n-1,n),(n,1)\\}, $$ and this is exactly what the code above does.
> 6 votes

# Answer
# Ruby, ~~67 66 56~~ 54 bytes

```
->n{(1..n**3).map{|y|(0..5).map{|x|(x+y/n**(x/2))%n}}}

```

Try it online!

### Explanation:

* Look at the existing answers
* Try to find a pattern in the results
* Replicate the pattern without understanding the underlying process
* Feels like cheating.but it works
> 6 votes

# Answer
# Jelly, 6 bytes

```
ṗ3ż’$%

```

A monadic Link accepting a positive integer that yields a list. Each element is a pair of lists, the first gives the colours of three faces around a corner and the second gives the colours of their respective opposites.

**Try it online!**

### How?

The strategy is to paint each of the \\$n^3\\$ cubes in a consistent direction (e.g. always clockwise) around any corner with a different one of the \\$n^3\\$ possible \\$3\\$-tuples of the \\$n\\$ colours. Then chose any ordering of the colours and paint every unpainted face with the "next" colour after the painted face it is opposite. This gives the same resulting painting as the strategy given in the question, just in a different order.

```
ṗ3ż’$% - Link: integer, n
 3     - three
ṗ      - (implicit range [1..n]) Cartesian power (3) -> all 3-tuples made from [1..n]
    $  - last two links as a monad - f(x=that):
   ’   -   decrement (x) (vectorises)
  ż    -   (x) zip with (that)
     % - modulo (n) (vectorises)

```
> 4 votes

# Answer
# , 53 bytes

```
n=scan();cbind(e<-expand.grid(a<-1:n-1,a,a),(e+1)%%n)

```

Try it online!

Returns a matrix with rows corresponding to different small cubes, and columns - to their faces.
> 3 votes

# Answer
# 05AB1E, 9 bytes

```
L3ãεD>‚I%

```

Try it online!

```
L3ãεD>‚I%  # full program
   ε       # replace each element in...
  ã        # all lists of length...
 3         # literal...
  ã        # of elements in...
L          # [1, 2, 3, ...,
           # ..., implicit input...
L          # ]...
   ε       # with...
      ‚    # [...
           # (implicit) current element in map...
      ‚    # , ...
    D      # (implicit) current element in map...
     >     # plus 1...
      ‚    # ]...
           # (implicit) with each element...
        %  # modulo...
       I   # input
           # (implicit) exit map
           # implicit output

```
> 1 votes

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


# Question
Title: Recognise a Digit from a Positional Encoding
Starting an the origin on an infinite grid, you follow a predetermined path going up (`U`), down (`D`), left (`L`), or right (`R`). You paint every square you visit, including the square you started at and the square you finish at. Using this method, we can paint the number six using the instructions `RRDDLLUUUURR`:

The origin is shown as a green star. We call this a *positional encoding* of the number six. Note that a positional encoding is not unique; the encoding `LLUURRDDUULLUURR` also encodes the number six with some redundancy:

Note that if you visit a square you've already painted in your path, you leave it as is.

## Challenge

Given a positional encoding of one of the digits zero through nine taken as a string, output which digit it encodes.

All digits will be encoded in a \\$3\times5\\$ format as follows:

```
#     ###   ###   # #   ###
#       #     #   # #   #
#     ###   ###   ###   ###
#     #       #     #     #
#     ###   ###     #   ###

###   ###   ###   ###   ###
#       #   # #   # #   # #
###     #   ###   ###   # #
# #     #   # #     #   # #
###     #   ###   ###   ###

```

Note that:

* The positional encoding given will always map to one of the ten digits given above exactly; the input string is guaranteed to be valid.
* The digit will never be mirrored or rotated.
* There may be redundancy in the encoding (eg `LR`).
* The square you start at is always painted.

## Test Cases

```
Input                -> Output
DDDD                 -> 1
UUUU                 -> 1
DDUDDUDD             -> 1
DDUUUUDDUUDD         -> 1
LRRDDLLDDRLRR        -> 2
LDDRRLLUURRUULL      -> 2
RRDDLLRRDDLL         -> 3
LLRRUULLRLRRUUDULL   -> 3
LUUDDRRUUDDDD        -> 4
DDLLUUDDRRDD         -> 4
LLDDRRDDLL           -> 5
DLLRRUULLUURRLLRR    -> 5
RRDDLLUUUURR         -> 6
LLUURRDDUULLUURR     -> 6
RRDDLLUURRDDLLUUUURR -> 6
RRDDDD               -> 7
LLRRDDDD             -> 7
LUURRDDDDLLU         -> 8
RUULLUURRDDLLDD      -> 8
RRDDLLUURRDDDDLL     -> 9
DUDLRLLRRUULLRRUULLD -> 9
RRUUUULLDDD          -> 0
UUUUDDDDRRUUUULRDDDD -> 0

```

Also in list form:

```
[['DDDD', 1], ['UUUU', 1], ['DDUDDUDD', 1], ['DDUUUUDDUUDD', 1], ['LRRDDLLDDRLRR', 2], ['LDDRRLLUURRUULL', 2], ['RRDDLLRRDDLL', 3], ['LLRRUULLRLRRUUDULL', 3], ['LUUDDRRUUDDDD', 4], ['DDLLUUDDRRDD', 4], ['LLDDRRDDLL', 5], ['DLLRRUULLUURRLLRR', 5], ['RRDDLLUUUURR', 6], ['LLUURRDDUULLUURR', 6], ['RRDDLLUURRDDLLUUUURR', 6], ['RRDDDD', 7], ['LLRRDDDD', 7], ['LUURRDDDDLLU', 8], ['RUULLUURRDDLLDD', 8], ['RRDDLLUURRDDDDLL', 9], ['DUDLRLLRRUULLRRUULLD', 9], ['RRUUUULLDDD', 0], ['UUUUDDDDRRUUUULRDDDD', 0]]

```

## Scoring

Shortest code in bytes wins.

# Answer
# JavaScript (Node.js),  ~~89 ... 77~~  71 bytes

*Saved 6 bytes by using the modulo chain provided by @KjetilS.*

```
s=>Buffer(s).map(c=>o|=p*=4**(c%5)/8,o=p=4**8)|(o/=o&-o)*321%3081%53%11

```

Try it online!

### How?

We take the ASCII code \\$c\\$ of the direction character modulo \\$5\\$ to map it to an index in \\$\\{0,1,2,3\\}\\$.

For each direction, we update a bit mask \\$p\\$ by shifting it by a specific amount and mark the bits that are visited in another bit mask \\$o\\$.

```
 char. | ASCII | mod 5 | shift
-------+-------+-------+-------
  'U'  |   85  |   0   | >> 3
  'L'  |   76  |   1   | >> 1
  'R'  |   82  |   2   | << 1
  'D'  |   68  |   3   | << 3

```

Conveniently, the shift is equivalent to multiply \\$p\\$ by:

$$\frac{4^{(c\bmod 5)}}{8}$$

We start with both \\$p\\$ and \\$o\\$ set to \\$4^8=2^{16}\\$. This value is safe because we will never right-shift by more than \\$4\times 3 + 2\times 1=14\\$ (e.g. with `"UUUULL"`, which draws a \\$7\\$, or any other path going from the bottom-right to the top-left corner). Likewise, we will never left-shift by more than \\$14\\$ and never exceed \\$2^{30}\\$. So, both \\$p\\$ and \\$o\\$ remain 32-bit values.

Because we don't know which cell in the digit was our starting point, we normalize the final value of \\$o\\$ by removing all trailing zeros:

```
o /= o & -o

```

We end up with a unique 15-bit key identifying the digit.

```
 digit |   binary mask   | decimal
-------+-----------------+---------
   0   | 111101101101111 |  31599
   1   | 001001001001001 |   4681
   2   | 111001111100111 |  29671
   3   | 111100111100111 |  31207
   4   | 100100111101101 |  18925
   5   | 111100111001111 |  31183
   6   | 111101111001111 |  31695
   7   | 100100100100111 |  18727
   8   | 111101111101111 |  31727
   9   | 111100111101111 |  31215

```

It can be seen as a binary representation of the digit shape rotated by 180°. For instance:

```
                       100    111
                       100    001
100 100 100 100 111 -> 100 -> 001 -> "7"
                       100    001
                       111    001

```

We apply the following function to turn it into the expected digit:

$$f(n)=\big(((n\times 321)\bmod 3081)\bmod 53\big)\bmod 11$$
> 18 votes

# Answer
# Charcoal, ~~70~~ ~~65~~ ~~63~~ ~~60~~ ~~58~~ ~~43~~ 38 bytes

```
Ｆ⁺ＳR«ＵＭＫＶＩΣκ✳ι1»≔↨ＫＡ²θ⎚§”←＆Φ⁴.º!Ｈ”﹪θ⁹⁴

```

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

```
Ｆ⁺ＳR«

```

Append a dummy instruction to the input to ensure that both ends get drawn, and loop over the instructions.

```
ＵＭＫＶＩΣκ

```

Pad the neighbourhood of each cell. (This is because `PeekAll()` only returns the drawn cells and not their positions, so it would be impossible to distinguish between the groups `69`, `08` and `235`.) Each orthogonally adjacent cell is replaced with its digital sum, which is `1` for cells on the path and `0` for all other cells (whether new or previously padded).

```
✳ι1»

```

Draw the path using literal `1`s and move in the appropriate direction.

```
≔↨ＫＡ²θ

```

Record which of the cells were drawn and which were just padding, and interpret that as if it was binary.

Clear the canvas.

```
§”←＆Φ⁴.º!Ｈ”﹪θ⁹⁴

```

Cyclically index the compressed lookup table `56 0817 934 2` (where the spaces are don't care values) with the base 2 number captured above modulo 94 and output the result.

It's possible to shrink the uncompressed lookup table to 11 bytes `0473125869_` by taking the number modulo 378 for the same byte count, or to 10 bytes `8739651204` by taking the number modulo 4207, but this ends up actually a byte longer after compression, so instead if you capture the number in base 5 rather than base 2, then by taking it modulo 579 you can cyclically index the result in the table `7269105348` also for the same byte count.

Example digit decoding: Drawing `RRDDDD` results in the following canvas:

```
 000
01110
 0010
  010
  010
  010
   0

```

Reading these gives `0000111000100100100100` which is 231716 in binary, then reducing modulo 94 gives 6, which (cyclically) indexed into the lookup table produces `7`, the desired result.
> 13 votes

# Answer
# , 75 65 59 55 bytes

*-10 thanks to Jonah!*

*-6 thanks to Bubbler!*

*-4 thanks to FrownyFrog!*

Identifies the numbers by their bit mask of the following positions:

```
#0#
1 2
#3#
4 #
###

```

So 8 would be `11111`, and 7 would be `10100`

```
'=)76.:;4?'i.4 u:2#.1,i.@5(e.>./-:@->:)0+/\@,3-2*5|3&u:

```

Try it online!

### How it works

```
3-2*5|3&u:

```

Map `DRLU` to `-3 -1 1 3`. (Thanks to Arnauld!)

```
(>./…-…)0+/\@,

```

Append 0 (the drawn starting tile), and fold every prefix to absolute indices, e.g. `0 1 2 5 8 11 14`. As an index might be negative, get the highest number and subtract it from every index.

```
i.@5(e.…-:@…>:)

```

Checks which of the indices `1 3 5 7 9` are set: `1 0 1 0 0`.

```
'=)76.:;4?'i.4 u:2#.1,

```

The bit masks with a 1 prepended (so the numbers neatly fit into ASCII) is looked up in the table.
> 11 votes

# Answer
# Jelly, ~~35~~ ~~34~~ 32 bytes

```
O%15Żı*ÄÆiḞ_Ṃ$‘ŒṬFḄ%29ị“ẆA⁻R§’D¤

```

Try it online!

*-1 thanks to Zgarb fixing my brainfart*

*-2 thanks to Jonathan Allan reminding me of `Ż` and rearranging to remove a space*

I have no idea what I'm doing... Going all the way through `Ḟ‘ŒṬ` feels like it may not be necessary with a smart choice of hash function, and it's not a terrible idea to just try translating Arnauld's JS answer outright. I've tried quite a few dumber hash functions, and they've all gotten tripped up on 2 versus 5, but maybe if I keep using base conversion...

```
       Ä          Cumulative sums of
     ı*           sqrt(-1) to the (vectorized) power of
O                 the codepoints of the input
 %15              mod 15 (U,D,L,R -> 10,8,1,7 ≡ 2,0,1,3 mod 4)
    Ż             with 0 prepended.
        Æi        a + bi -> [a, b],
          Ḟ       convert the floats to integers,
           _Ṃ$    and subtract the minimum.

‘                     Increment so that all indices are positive,
 ŒṬ                   then convert them to a multidimensional Boolean array,
   F                  flatten it,
    Ḅ                 convert from binary,
     %29              mod 29,
        ị             modular index into
                D¤    the decimal digits of
         “ẆA⁻R§’      813540020976.

```
> 6 votes

# Answer
# Perl 5, ~~96~~ 84 bytes

```
$s=0 x99;substr$s,$p+=ord()*9%45%7-3,1,1for$p=49,@F;$s=~/1.*1/;$_=$&*8%29014%1637%11

```

Try it online!

Somewhat ungolfed:

```
cat <<'.' > recognise.pl
$s=0 x99;                                   #init string of 100 zeros
substr$s,$p+=ord()*9%45%7-3,1,1for$p=49,@F; #replace 0 with 1 for each step of
                      #input char, start at pos 49, -3 for U, 3 for D, -1 for L,
                      #1 for R. ord() is ascii val of UDLR
$s=~/1.*1/;           #find longest substring that starts and ends with 1, treat
                      #that string as a long int, i.e. 8 = 111101111101111
$_=$&*8%29014%1637%11 #modulus voodoo to get the digit
.
cat <<. | perl -F"" -apl recognise.pl
DDDD
UUUU
DDUDDUDD
DDUUUUDDUUDD
LRRDDLLDDRLRR
LDDRRLLUURRUULL
RRDDLLRRDDLL
LLRRUULLRLRRUUDULL
LUUDDRRUUDDDD
DDLLUUDDRRDD
LLDDRRDDLL
DLLRRUULLUURRLLRR
RRDDLLUUUURR
LLUURRDDUULLUURR
RRDDLLUURRDDLLUUUURR
RRDDDD
LLRRDDDD
LUURRDDDDLLU
RUULLUURRDDLLDD
RRDDLLUURRDDDDLL
DUDLRLLRRUULLRRUULLD
RRUUUULLDDD
UUUUDDDDRRUUUULRDDDD
.

```
> 4 votes

# Answer
# , 314 bytes

Not very short unfortunately, feels like the extra illegibility isn't worth it here.

```
{f=pryr::f
f(w,{s=switch
l=f(t,t[length(t)])
a=f(t,s=0,c(t,l(t)+s))
v=f(c,s(c,U=-1,D=1,0))
h=f(c,s(c,L=-1,R=1,0))
m=f(l,b,x=0,{for(c in l)x=a(x,b(c))
    x})
z=el(strsplit(w,''))
x=m(z,h)
y=m(z,v)
p=x-min(x)
q=y-min(y)
r=p+q*3
u=unique(r)
d=trunc(10*(var(u)+median(u)))%%28
match(d,c(0,5,20,3,2,16,1,26,8,19))-1})}

```

Try it online!

Intermediate calculations from:

```
letters=list(
x1=c(0,3,6,9,12),
x2=c(0,1,2,5,6,7,8,9,12,13,14),
x3=c(0,1,2,5,6,7,8,11,12,13,14),
x4=c(0,2,3,5,6,7,8,11,14),
x5=c(0,1,2,3,6,7,8,11,12,13,14),
x6=c(0,1,2,3,6,7,8,9,11,12,13,14),
x7=c(0,1,2,5,8,11,14),
x8=c(0,1,2,3,5,6,7,8,9,11,12,13,14),
x9=c(0,1,2,3,5,6,7,8,11,12,13,14),
x0=c(0,1,2,3,5,6,8,9,11,12,13,14)
)
sapply(letters,function(letter){trunc(10*(var(letter)+median(letter)))%%28})

```
> 4 votes

# Answer
# Jelly,  ~~31~~  28 bytes

Yes, it's very similar to Unrelated String's, but it's slightly different and was completely independently found.

```
O%15Żı*ÄÆi_Ṃ$QṢ“X|cE’Dṭ⁽½ȯ¤ḥ

```

**Try it online!**

If a larger salt (which is also less than \\$250^6\\$) for the hash built-in is found which removes the need to permute \\$\[0,9\]\\$ (making `“X|cE’Dṭ⁽½ȯ¤ḥ` become `“?????’,⁵¤ḥ’`) we get 27 (or less).

### How?

```
O%15Żı*ÄÆi_Ṃ$QṢ“X|cE’Dṭ⁽½ȯ¤ḥ - Link: listof characters
O%15                         - mod 15 of ordinals
    Ż                        - prepend a zero
     ı*                      - root(-1) raised to each of those
       Ä                     - cumulative sums
        Æi                   - convert each to [real, imaginary]
          _Ṃ$                - subtract of the minimum from each
             Q               - distinct values
              Ṣ              - sort
                          ¤  - nilad followed by link(s) as a nilad:
               “X|cE’        -   1398462570
                     D       -   to decimal digits (our domain)
                       ⁽½ȯ   -   3742 (our salt)
                       ṭ     -   tack -> [3742,[1,3,9,8,4,6,2,5,7,0]]
                           ḥ - hash (the sort results using that [salt, domain])

```

---

Previous version at 31 bytes using no built-in hash function...

```
O%15Żı*ÄÆi_Ṃ$QṢFḞḌ%⁽¥Ƭị“ċḞƒø’D¤

```

A monadic Link accepting a list of characters which yields an integer in \\$\[0,9\]\\$.

**Try it online!**

### How?

```
O%15Żı*ÄÆi_Ṃ$QṢFḞḌ%⁽¥Ƭị“ċḞƒø’D¤ - Link: listof characters
O%15Żı*ÄÆi_Ṃ$QṢ                 - as above
               F                - flatten
                Ḟ               - floor (so Ḍ gives an integer rather than a float)
                 Ḍ              - convert from base ten
                  %⁽¥Ƭ          - modulo 2153
                       “ċḞƒø’D¤ - decimal digits of 3652914780
                      ị         - 1-indexed modulo index into

```
> 3 votes

# Answer
# 05AB1E, ~~36~~ 35 bytes

```
•7‡šмÓ•žFDIÇv4y5%m8/*DŠ~s}\b0ÚC45%è

```

Port of *@Arnauld*'s 78 bytes version, so make sure to upvote him as well! (His 78→77 and 77→71 golfs would be longer in 05AB1E.)

Try it online or verify all test cases.

**Explanation:**

```
•7‡šмÓ•              # Push compressed integer 31846207905
 žF                  # Push builtin 16384 (2**14)
   D                 # Duplicate it
    I                # Push the input-string
     Ç               # Convert it to a list of codepoint integers
      v              # Loop over each codepoint `y`:
        y5%          #  Take `y` modulo-5
       4   m         #  Take 4 to the power this value
            8/       #  Divide it by 8
              *      #  Multiply it by the top of the stack
               D     #  Duplicate it
                Š    #  Tripleswap (a,b,c → c,a,b) the top three values on the stack
                 ~   #  Bitwise-OR the top two
                  s  #  And swap so the other value is at the top again
      }\             # After the loop: discard the top value
        b            # Convert the integer to binary
         0Ú          # Remove all leading/trailing 0s
           C         # Convert it from binary back to an integer
            45%      # Modulo-45
               è     # And index it into the digits of 31846207905 (0-based modulair)
                     # (after which the digit is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•7‡šмÓ•` is `31846207905`.
> 3 votes

# Answer
# , ~~217~~ ~~200~~ 192 bytes

(or only **169 bytes** by stealing Arnauld's modulo chain to get the final digit without a look-up table...)

```
function(s,u=utf8ToInt){d=sapply(c(0,u(s)),`%in%`,x=u("DRUL"))
n=apply(d[1:2,]-d[3:4,],1,function(x)(y=cumsum(x))-min(y))
match(sum(2^unique(n[,1]+5*n[,2]))%%27%%11,c(0,4,7,10,8,5,2,3,9,1))-1}

```

Try it online!

**How?** Original code (before significant golfing changes...):

```
recognize_digit=
function(s){
                                # first we 'construct' the digit from the encoding:

 d=sapply(                      # d is direction of each step, calculated by...
    c("D","R","U","L"),         # ...using each letter...
    grepl,                      # ...as a regex...
          el(strsplit(s,'')))   # ...to search each letter of the encoding.
 m=matrix(!-40:40,9)            # m is a matrix big enough to fit the letters (9x9)
 m[                             # we set the elements of m, selected by...
   apply(d[,1:2]-d[,3:4],       # ...subtracting L from R, and U from D...
   2,                           # ...and for each of the L-R and U-D columns...
   cumsum)+5                    # ...calculating the cumulative sum +5,
            ]=T                 # to 'TRUE'.
 l=m[(c=t(which(m,T)))[1]+0:4,  # l is the 3x5 'letter' matrix, starting at the
   c[2]+0:2]                    # first TRUE elment of m

                                # now we have the digit in l, so we just have to
                                # recognize it:
 match(                         # we find the match between...
  sum(l*2^(0:14))               # the number formed by using the pixels of the digit as bits...
   %%27%%11,                    # MOD 27 MOD 11 (reduces each number to a smaller number
  c(0,4,7,10,8,5,2,3,9,1))-1    # and the 'lookup' table of results for each digit.
}

```
> 3 votes

# Answer
# Batch 207 bytes

Notes:

* *must be run from the command line using:* `Echo(NoP pattern|Cmd /V:on` *where `pattern` is a list of movements IE*: `D D D D R R U U U U L L`
* **requires windows 10 with virtual terminal support**
* `ESC` is a stand in for the ANSI escape character, As it can't be pasted here, the scripts raw paste data can be found here.
    + Or it can be generated by opening the command prompt and typing:
        - `>"%TEMP%\escape.chr" Echo(``ALT`+`027` then pressing `ENTER`
    + Or output using a for loop with `Echo off`:
        - `(For /F "skip=4 DELIMS=" %a in ('Echo(prompt $E^|cmd')Do Echo(%a) >"%TEMP%\escape.chr"`

filename: NoP

```
@Echo off&Set $=Set &cls
%$%U=A&%$%D=B&%$%R=C&%$%O=^<nul set/P =&%$%E=echo(&%$%"F=|findstr /C:"L" >nul &&"
%O%ESC[6;7H*ESCD
For %%c in (%*)do %e%%%c%F%%O%ESC[2D*||%e%%%c%F:"L"="R"%%O%*||%O%ESC!%%c!*ESCD
%e%ESC[12;1H

```

How: the input is assessed using findstr and converted to the virtual terminal sequences required to move the cursor accordingly using sequential `&&` and `||` conditional tests, akin to a compound series of if / else statements.
> 2 votes

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


# Question
Title: Merge Two Paragraphs with Removing Duplicated Lines
**Challenge**

The goal of this challenge is to make a function that takes two paragraphs and output a concatenated result with removing the duplicated overlapped lines due to redundancy (but a single copy of the part of overlapped lines should be kept to avoid information loss). Each input paragraph is with the follows specifications.

* The leading/trailing spaces in each line have been removed.
* No empty line.

The output merged paragraph follows the rules as below.

* Input paragraph 2 is concatenated after input paragraph 1
* If the line(s) from the start of the input paragraph 2 is / are sequenced same (overlapped) as the end of input paragraph 1, just keep single copy of the sequenced duplicated lines.
* The definition of duplicated lines here:

+ The content in two line should be totally the same, no “partial overlapping” cases need to be considered.
    + The content sequence in two blocks of lines should be totally the same.

**Example Input and Output**

* **Inputs**

Input paragraph 1 example:

```
Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers.
It's built and run by you as part of the Stack Exchange network of Q&A sites.
With your help, we're working together to build a library of programming puzzles and their solutions.
We're a little bit different from other sites. Here's how:
Ask questions, get answers, no distractions
This site is all about getting answers. It's not a discussion forum. There's no chit-chat.

```

Input paragraph 2 example:

```
We're a little bit different from other sites. Here's how:
Ask questions, get answers, no distractions
This site is all about getting answers. It's not a discussion forum. There's no chit-chat.
Good answers are voted up and rise to the top.
The best answers show up first so that they are always easy to find.
The person who asked can mark one answer as "accepted".
Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked.
Get answers to practical, detailed questions
Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do.
Not all questions work well in our format. Avoid questions that are primarily opinion-based, or that are likely to generate discussion rather than answers.

```
* **Expected Output**

The two block of text are the same, so keep single overlapped part after merging.

```
Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers.
It's built and run by you as part of the Stack Exchange network of Q&A sites.
With your help, we're working together to build a library of programming puzzles and their solutions.
We're a little bit different from other sites. Here's how:
Ask questions, get answers, no distractions
This site is all about getting answers. It's not a discussion forum. There's no chit-chat.
Good answers are voted up and rise to the top.
The best answers show up first so that they are always easy to find.
The person who asked can mark one answer as "accepted".
Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked.
Get answers to practical, detailed questions
Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do.
Not all questions work well in our format. Avoid questions that are primarily opinion-based, or that are likely to generate discussion rather than answers.

```

**Rules of Challenge**

This is . The answer with the least bytes wins.

# Answer
> 7 votes
# Python 3.8 (pre-release), 104 bytes

```
def o(a,b,i=None):
 while(i:=a[:i].rfind(b[0]))+1:
  if b.find(a[i:])==0:return a[:i]+b
 return a+'\n'+b

```

Try it online!

I've come up with this as my first ever Code Golf challenge. Defines function `o` (short for overlay) which returns string `a` overlayed with string `b`, or their concatenation if there is no overlap.

It repetitively searches backwards in `a` for the first letter of `b` and, if a match is found, compares from that point on in `a` to the beginning of `b` until an overlap is found or `a` has been fully scanned.

# Answer
> 2 votes
# 05AB1E, 13 bytes

```
.s€»ʒÅ?}θK¹»ì

```

First input as a list of lines, second as a multi-line string. (Taking multi-line input as a list of lines is allowed by default.)

Try it online.

Would be 1 byte longer if we can take both inputs as multi-line strings: try it online.
~~Would be 3 bytes shorter if partial lines could also overlap: try it online.~~

**Explanation:**

```
.s          # Get a list of suffices of the first (implicit) input-list of lines
  €         # Map over each suffix:
   »        #  And join them by newlines
    ʒ       # Then filter of these string-suffices:
     Å?     #  And keep the one that the second (implicit) input-string starts with
    }θ      # After the filter: keep only the last/longest suffix
      K     # Remove this overlapping text from the second (implicit) input-string
       ¹»   # Push the first input-list, and join it by newlines
         ì  # And prepend it to the other string
            # (after which the result is output implicitly)

```

# Answer
> 2 votes
# Perl 5 (-0777p), 20 bytes

```
s/^(.*
)
\1|^
/$1/ms

```

Try it online!

# Answer
> 2 votes
# Python 2, ~~59~~ 51 bytes

*8 bytes thanks to @ovs*

Input is taken as two lists of strings.

```
f=lambda a,b:`a`[:-1]in`b`and b or[a.pop(0)]+f(a,b)

```

Try it online!

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

I/O format: lists of strings. Expects `(b)(a)`.

```
b=>g=a=>a.some((s,i)=>b[i]!=s)?[a.shift(),...g(a)]:b

```

Try it online!

Test cases ~~stolen~~ borrowed from @dingledooper.

### Commented

```
b =>               // anonymous outer function taking the 2nd paragraph b[]
g = a =>           // inner recursive function g taking the 1st paragraph a[]
  a.some((s, i) => // for each line s at position i in a[]:
    b[i] != s      //   truthy if the i-th line of b is not equal to s
  ) ?              // end of some(); if truthy:
    [              //   create an array consisting of:
      a.shift(),   //     the 1st line removed from a[]
      ...g(a)      //     followed by the lines returned by a recursive call
    ]              //   end of array
  :                // else:
    b              //   stop the recursion and return b[]

```

# Answer
> 2 votes
# AWK, <sup>~~28~~ \\$\cdots\\$ ~~85~~</sup> 84 bytes

Added 44 bytes to fix a bug kindly pointed out by Dominic van Essen.
Added another 13 bytes to fix another bug pointed out by Dominic van Essen and JimmyHu.
Saved a byte thanks to cnamejj!!!

```
$0 in a&&m&&!h{h=a[$0]+1;next}h&&a[$0]==h{++h;next}!NF{m=1;next}!m{a[$0]=++i}{print}

```

Try it online!

Inputs the two paragraphs separated by an empty line from `stdin`.

# Answer
> 2 votes
# Retina 0.8.2, 14 bytes

```
ms`$(.+)^\1
$1

```

Try it online! Assumes that neither paragraph will be matched in its entirety. Explanation: The leading `$` ensures that the capture begins with a newline, while the inner `^` ensures that it ends with a (possibly the same) newline. It then remains to delete the duplicate.

# Answer
> 2 votes
# APL+WIN, 19 bytes

Prompts for the second paragraph followed by the first as nested vectors of lines:

```
(∨⌿<\x^.=⍉x)⌿x←⊃⎕,⎕

```

Try it online! Thanks to Dyalog Classic

# Answer
> 2 votes
# JavaScript (Node.js), ~~70~~ 68 bytes

```
l=(a,b,c)=>b.startsWith(a.slice(c=~~c,-1))?a.slice(0,c)+b:l(a,b,++c)

```

Try it online!

# Answer
> 2 votes
# , ~~77~~ ~~74~~ ~~71~~ ~~61~~ 60 bytes

*Edit: -3 bytes and bug-fix thanks to Giuseppe, then -1 byte thanks to Robin Ryder*

```
function(p,q){while(any(p!=(s=c(p[0:F],q))[seq(p)]))F=F+1;s}

```

Try it online!

Tries increasingly long prefixes of `p` (first paragraph) and joins `q` (second paragraph) onto them, until one is found whose first elements are equal to the whole of `p` (this will always happen when the 'prefix' grows to become the entirity of `p`, of course).

# Answer
> 2 votes
# Wolfram Language (Mathematica), ~~32~~ 31 bytes

```
{a___,d=b___}±{d,c___}={a,b,c}

```

Try it online!

Defines an operator `±` (`PlusMinus`).

Mathematica's pattern-matching does the entirety of the work here:

```
{a___,b___}±{b___,c___}=    (* function of two lists, where (b___) a possibly-empty postfix of the first is a prefix of the second: *):
  {a,b,c}                   (* concatenate. *)

```

# Answer
> 1 votes
# Jelly,  ~~10~~  8 bytes

-2 bytes thanks to (same method but with a much better choice of atoms!)

```
ẇÐƤẹ0⁸ṁ;

```

A dyadic Link accepting lists of lines that yields a list of lines.

**Try it online!**

### How?

```
ẇÐƤẹ0⁸ṁ; - Link: P1, P2
 ÐƤ      - for postfixes, X, of P1:
ẇ        -   sublist (X) exists in (P2)?
   ẹ0    - indices of 0
     ⁸ṁ  - mould P1 like that
       ; - concatenate P2

```

# Answer
> 0 votes
# Perl 5, 42 bytes

```
sub f{join($;,@_)=~s,^((.+\n)*)$;\1,$1,mr}

```

Try it online!

# Answer
> 0 votes
# Husk, ~~11~~ 12 bytes

*Edit: +1 byte to fix bug (when first paragraph is entirely within second)*

```
ḟoΠz=³m`+⁰Θḣ

```

Try it online!

```
ḟ               # return first list that satisfies:
 oΠ             #   all truthy results of
   z=³          #   comparing each element to each element of arg1
                # from this list:
      m         # for each of
          Θḣ    # the prefixes of arg1, beginning with the empty list,
       `+⁰      # append arg2

```

# Answer
> 0 votes
# JavaScript (Node.js), 35 bytes

```
x=>x.replace(/^([^]*)\1^|/m,'$1')

```

Try it online!

Split two inputs with NUL(`\0`). Competive even if need to do in function

---
Tags: code-golf, string, sequence, text-processing
---


# Question
Title: Infinitely Print Zeno's Dichotomy Paradox (1/(2^n))
Wikipedia: Zeno's Dichotomy Paradox

> An infinite number of mathematicians walk into a bar. The first one orders a beer. The second one orders half a beer. The third one orders a fourth of a beer. The bartender stops them, pours two beers and says, "You're all a bunch of idiots."
>
> Reddit

Print the following series for as long as the program runs, with the denominator of each item being multiplied by two each time:

`1 + 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + ...`

As `n` approaches infinity, the sum of this sequence approaches `2`.

# Rules

No, you may not print `2`.

You may not print `1/1` as the first item.

You may remove spaces `1+1/2+...` or add spaces `1 + 1 / 2 + ...` as you need.

You may use newlines instead of spaces as a delimiter due to popular demand.

You may append a `.` plus a constant number of `0`s to the denominator if need be.

"Infinitely" means no unnecessary delays, and for as long as possible limited by the current (variable) system's specs, but not limited by your current language.

Standard loopholes apply.

This is , so shortest answer in bytes wins.

# Answer
> 14 votes
# 05AB1E, ~~10~~ 9 bytes

Saved 1 byte thanks to *Erik the Outgolfer*

```
[No…+1/J?

```

Try it online!

**Explanation**

```
[           # loop over N infinitely [0 ...]
 No         # calculate 2^N
   …+1/J    # join with the string "+1/"
        ?   # print without newline

```

# Answer
> 13 votes
# Python 2, 30 bytes

-5 thanks to Erik the Outgolfer

```
i=1
while 1:print i,'+1/';i*=2

```

Try it online!

# Answer
> 7 votes
# C (gcc), 60 bytes

```
f(){for(long long n=1;n;n*=2)printf(&"+1/%llu"[n^1?0:3],n);}

```

Goes up the the unsigned 64bit limit.

Try it online!

This one goes on forever; (it's as small as it's going to get)

# C (tcc), ~~312~~ ~~264~~ ~~255~~ ~~251~~ ~~233~~ ~~231~~ ~~208~~ ~~204~~ ~~195~~ ~~190~~ ~~188~~ 170 bytes

```
l=4;c;main(i){for(char*t="*\b1+";puts(i=t),*++t=48;l=asprintf(&t,"1/%s",t+=*++t<49))for(t+=l-2;--t>i;)*t>52?*t=*t*2%58+c,c=*--t>52,*t=*t%48*2%10+49:(*t=*t*2-48+c+(c=0));}

```

Try it online!

Here's the not so golfed version;

```
c;l=4;main(i){
    for(char*t="*\b1+";puts(i=t),*++t=48;l=asprintf(&t,"1/%s",t+=*++t<49))
        for(t+=l-2;--t>i;)
            *t>52?*t=*t*2%58+c,c=*--t>52,*t=*t%48*2%10+49:(*t=*t*2-48+c+(c=0));
}

```

# Answer
> 6 votes
# APL (Dyalog Unicode), 15 bytes

More fun if `⎕FR` (**F**loating-point **R**epresentation) is `1287` (128 bit decimal) and `⎕PP` (**P**rint **P**recision) is 34.

```
{∇2×⊃⎕←⍵'+1/'}1

```

Try it online!

`{``}1` apply the following function on the number 1:

`⎕←⍵'+1/'` print the argument and the the string

pick the first one (i.e. the argument)

double that

tail call recursion on that (optimised, so it can be infinitely repeated)

# Answer
> 6 votes
# Jelly, 12 bytes

```
‘;“+1/”ȮḢḤ’ß

```

Try it online!

# Answer
> 6 votes
# Pyth, 10 bytes

```
.V0^2b"+1/

```

Try it online!

# Answer
> 6 votes
# Bash, 33 bytes

```
echo 1;yes|awk '{print"+1/"2^NR}'

```

Try it online!

Change `print` for `printf` and `echo` for `printf` to avoid newline

# Answer
> 6 votes
# dc, ~~19~~ 18 bytes

```
1[rdp+[+1/]Prdx]dx

```

## Explanation

We push `1` and `[rdp+[+1/]Prdx]` onto the stack. We then duplicate and execute `[rdp+[+1/]Prdx]`. The first thing it does is to rotate the stack (`r`) so that the value is on top. `dp+` prints the value and adds itself (to multiply by 2). `[+1/]P` prints the invariant `+1/`, then we rotate the arguments so the saved macro definition is at the top, duplicate it and start again.

## Notes

GNU `dc` will normally wrap at 70 columns. To override that and get an infinite line, add `DC_LINE_LENGTH=0` to your environment variables.

## Output (partial)

```
1
+1/2
+1/4
+1/8
+1/16
+1/32
+1/64
+1/128
+1/256
+1/512
+1/1024
+1/2048
+1/4096
+1/8192
+1/16384
+1/32768
+1/65536
+1/131072
+1/262144
+1/524288
+1/1048576
+1/2097152
+1/4194304
+1/8388608

```

...

```
+1/1042962419883256876169444192465601618458351817556959360325703910069443225478828393565899456512
+1/2085924839766513752338888384931203236916703635113918720651407820138886450957656787131798913024
+1/4171849679533027504677776769862406473833407270227837441302815640277772901915313574263597826048
+1/8343699359066055009355553539724812947666814540455674882605631280555545803830627148527195652096
+1/16687398718132110018711107079449625895333629080911349765211262561111091607661254297054391304192
+1/33374797436264220037422214158899251790667258161822699530422525122222183215322508594108782608384

```

...

```
[encoded data, 45163 characters]

```

...

# Answer
> 5 votes
# JavaScript (ES6), ~~36~~ 34 bytes

```
for(a=1;;a*=2)console.log(a+'+1/')

```

Try it online!

Inspired by Jake Taylor's answer.

Note that this is limited by language since `a` is a floating-point variable, not an integer.

-2 bytes thanks to @Stefnotch.

# Answer
> 4 votes
# GolfScript, 19 bytes

```
1{.'+1/'+puts.+.}do

```

Try it online!

# Answer
> 4 votes
# CJam, 14 bytes

```
1{_o"+1/"o2*}h

```

Try it online!

# Answer
> 4 votes
# \>\<\>, 14 bytes

```
1:n"/1+"ooo2*!

```

Try it online!

# Answer
> 4 votes
# Ruby, ~~27~~ 25 bytes

```
a=1;a*=2while$><<a<<'+1/'

```

Try it online!

# Answer
> 4 votes
# R, ~~35~~ 34 bytes

```
cat(i<-1);repeat cat("+1/",i<-i*2)

```

Spacing is a bit werid but I understand that's ok.

# Answer
> 4 votes
# Pyth, 10 bytes

```
#h~hyZ"+1/

```

`Z` starts out as zero. `~hyZ` post-assigns the value of `2*Z+1` to `Z`. Thus, `Z` becomes `0, 1, 3, 7, 15, ...` over successive iterations. `h` then prints out the value one greater. `#` runs the infinite loop, and `"+1/` gets the formatting right.

# Answer
> 4 votes
# Vim, ~~22~~, 21 bytes/keystrokes

```
qqyiwA+1/<esc>p@"<C-a>@qqxX@q

```

While testing this, you might run into issues with the current register values. To fix this, run

```
:let @q=''
:let @"=''

```

before running this, or by launching vim with

```
vim -u NONE -i NONE

```

# Answer
> 4 votes
# AWK, ~~37~~32 bytes

```
BEGIN{for(;;)printf 2^i++"+1/"}

```

Try it online!

Could remove the `BEGIN` and save 5 bytes if input were allowed. Using exponents definitely cheaper byte-wise than multiplication. :)

Hopefully 2^1023 is close enough to infinity (on my work computer). Unfortunately the TIO link truncates earlier than that (around 921). But 17726622920963562283492833353875882150307419319860869157979152909707315649514250439943889552308992750523075148942386782770807567185698815677056677116184170553481231217950104164393978236130449019315710017470734562946173533283208371259654747728689409291887821024109648618981425152 does seem pretty close to infinity. :)

# Answer
> 3 votes
# PHP, 32 Bytes

```
for(;;)echo bcpow(2,$i++)."+1/";

```

Online Version

-6 Bytes if values like `9.2233720368548E+18` are allowed

```
for(;;)echo 2**$i++."+1/";

```

Try it online!

# Answer
> 3 votes
# Powershell, 34 bytes

```
for([bigint]$i=1;;$i*=2){"$i+1/"}

```

Try it online!

# Answer
> 3 votes
# Go, ~~102~~ 100 bytes

Go can be almost as bad as Java, apparently.

```
import(."fmt"
."math/big")
func main(){n:=NewInt(1);for{Print(n.String()+"+1/");n.Mul(n,NewInt(2))}}

```

Try it online! (*Would be a good idea to avoid running any of these locally.* :P)

# Answer
> 3 votes
# Java, ~~107~~ 102 bytes

```
()->{for(java.math.BigInteger z=null,o=z.ONE,n=o;;n=n.add(n))System.out.print(n.max(o)==o?1:"+1/"+n);}

```

`z=null` exists to shorten the `o=java.math.BigInteger.ONE` into `z=null,o=z.ONE`, saving 12 bytes. `z.ONE` will not throw a `NullPointerException` because we access a static member and not an instance one.

Using `int` shortens the code, but fails to comply after 32 iterations.

## Saves

* 107 -\> 102 bytes: `n.compareTo(o)>0` turned into `n.max(o)==o`, thanks to an idea given by @Shufflepants

# Answer
> 3 votes
# JavaScript (ES6), ~~45~~ ~~43~~ 42 bytes

Saved 2 bytes, thanks @DanielM ! Saved 1 byte, thanks @eush77 for pointing it out.

~~*=console.log;a=1;*(1);for(;;)\_(`+1/${a*=2}`)~~

~~*=console.log;*(a=1);for(;;)\_(`+1/${a*=2}`)~~

```
_=console.log;for(_(a=1);;)_(`+1/${a*=2}`)

```

My first go at Codegolf, go easy!

# Answer
> 3 votes
# C#, ̶6̶8̶ 154 bytes

```
void A(int b=1){System.Console.Write($"1{(b>1?"/"+b:"")}+");A(b*2);}

```

Here is a version not constrained by int

```
using System.Numerics;BigInteger b=new BigInteger(1);void A(){System.Console.Write($"1{(b>1?"/"+b:"")}+");b=BigInteger.Multiply(new BigInteger(2),b);A();}

```

# Answer
> 3 votes
# Befunge 93: 14 bytes

```
1:.2*"/1+",,,#

```

# Answer
> 3 votes
# Jelly, 11 bytes

```
o©1“+1/”Ḥɼß

```

Try it online!

## How it works

Jelly's parsing rules are very complicated and depend on the arities of the link. Usually, links are composed of collections of:

* Dyad-nilad pairs (arities `2, 0`) such as `÷4` (divide by 4)
* Nilad-dyad pairs (arities `0, 2`) such as `3<` (greater than 3)
* Monads (arity `1`) such as `L` (length)
* Dyad-monad and monad-dyads (arities `2, 1` and `1, 2`) such as `+H` or `H+` (both \\$n + \frac n2\\$)

However, sometimes (very rarely), the arity patterns don't make sense. This is referred to an "unparseable" link. One such example is

```
4 H 5 Ḥ

```

Try it online!

The arities here are `0, 1, 0, 1`, and the second nilad doesn't fit into any of the patterns. In this case, `5` is called an "unparseable nilad", and it causes the program to output the previous value (`4H`, or `2`) and discard it, using the `5` as the new link value. This causes the program about to output `210` (`4H` outputs `2` and `5Ḥ` outputs `10` at the end of the program)

The arities of the program above are `2, 0, 0, 0, 1`. The pattern `0, 0, 0` is unparseable, meaning that the third and fourth links (`“+1/”` and `Ḥɼ`) are unparseable nilads

```
o©1“+1/”Ḥɼß - Main link f(n). Initially n = 0
o 1         - Replace 0 with 1
 ©          - Save this value into the register
   “+1/”    - Unparseable nilad; Output 1 and use "+1/" as the argument
        Ḥɼ  - Unparseable nilad; Output "+1/" and use the below result as the argument:
         ɼ  -   Run the previous command on the register, then save the result back into the register:
        Ḥ   -     Unhalve; Yield 2n
          ß - Recurse, yielding f(2n)

```

# Answer
> 2 votes
## QBIC, 18 bytes

```
?1{q=q*2?@+1/`';`q

```

Prints each term on a new line.

Explanation:

```
?1       Prints 1
{        Infinite loop
q=q*2    Doubles q, starts at 1*2=2
?@+1/`  Prints the string +1/
  ';`      without tabs, newlines or other terminators (code literal, ; is a QBIC function)
q        Also prints q
         The infinite loop is auto-closed by QBIC at EOF.

```

We can save a byte with a more liberal output format:

```
{?q,A,┘q=q*2#+1/

```

# Answer
> 2 votes
# Aceto, 20 bytes

```
 pL*
pd12<
p"M"
1+1/

```

Prints the sequence without any spaces. When run, you won't see anything for a little while, because of buffering, run with `-F` to immediately see everything.

1. Pushes and prints a 1, then stores "+1/" in quick storage (the register).
2. Pushes a 1.
3. Multiplies by two, loads from the register, prints, duplicates, and prints.
4. GOTO 3.

# Answer
> 2 votes
# Mathematica, 25 bytes

```
1//.n_:>(n~Print~"+";n/2)

```

# Answer
> 2 votes
## `Haskell` \- ~~66~~ ~~62~~ ~~60~~ ~~51~~ 49 chars

```
import Data.List
main=print$intercalate" + 1/"$map(show.(2^))[0..]

```

This prints the string constructed by printing the string representations of the powers of two starting from 1, separated by the string `" + 1/"`.

The code itself is 49 bytes, the import and newline push it up to 66

## Edit: (62)

Shaved 4 bytes by cutting out the import and defining intercalate with a much shorter name

```
f(x:xs)s=x++s++xs`f`s
main=print$map(show.(2^))[0..]`f`" + 1/"

```

## Edit 2: (60)

Shaved 2 more characters by realizing I didn't need to use the (x:xs) list convention:

```
f(x:y)s=x++s++y`f`s
main=print$map(show.(2^))[0..]`f`" + 1/"

```

## Edit 3: (51)

Reimplemented the definition of f and the map as the body of a fold to save 9 more characters

```
main=print$foldr((++).(++" + 1/").show.(2^))""[0..]

```

## Edit 4: (49)

As was pointed out by Laokoni, I can remove the spaces to cut down 2 more bytes off the total:

```
main=print$foldr((++).(++"+1/").show.(2^))""[0..]

```

# Answer
> 1 votes
# Braingolf, ~~41~~ 37 bytes

*Saved 4 bytes because I realised I don't need the spaces, always read the spec thoroughly kids*

```
1!_V"+/">!@R.[<!_>2*v<!@>R!_v!@R<1+>]

```

Try it online!

Can probably be golfed better, but it works.

# Answer
> 1 votes
# Lua 5.1 \+ BC, 50 bytes

Now works with arbitrary long integers.

I don't usually golf in Lua, so any tips are welcome

```
i=1::a::print(i,'+1/')i=require"bc".mul(i,2)goto a

```

# Answer
> 1 votes
# Fourier, 20 bytes

```
1~io(43a1o47ai*2~io)

```

**Try it online!**

I think this may only work on Try it Online due to differences in how Python and Javascript handle large numbers.

***Explanation Psuedocode:***

```
i = 1
Print i
While i != 0
    Print "+1/"
    i = i * 2
    Print i
End While

```

# Answer
> 1 votes
# **Ruby 46 bytes**

```
i=1;loop{print (i<2?"#{i}":"1/#{i}")+"+";i*=2}

```

any improvement suggestions are welcome -))

# Answer
> 1 votes
# F#, 39 bytes

```
let rec f x=printf"%A+1/"x;x*2I|>f
f 1I

```

Try it online!

# Answer
> 1 votes
# Labyrinth, 25 bytes

```
)
:}!43.4
"     9
*{2.74.

```

Try it online!

# Answer
> 1 votes
# GNU Make, ~~45~~ 57 bytes

Using shell:

```
$(eval 1?=1)$(info $1+1/)$(call $0,$(shell expr $1 \* 2))

```

Using GMSL (a lot slower, calculates in unary), a complete makefile — 66 bytes:

```
include gmsl
P=$(info $1+/)$(call P,$(call double,$1))
$(call P,1)

```

# Answer
> 1 votes
# Common Lisp, 42 bytes

```
(do((x 1(* x 2)))(())(format t"~a+"(/ x)))

```

Try it online (TIO will show you partial output)

### Explanation

```
(do ... )          ;looping
((x 1(* x 2))      ;define x as 1 and then in new interation steps
                   ;as result of 2 * x
(())               ;no ending condition
(format t"~a+"...) ;print argument and "+"
(/ x)              ;divide 1 by x - output is like this: 1, 1/2, 1/4, ...

```

# Answer
> 1 votes
# PHP, 29 bytes

```
for($a=.5;$a*=2;)echo"$a+1/";

```

# Answer
> 1 votes
# Ruby, 24 bytes

```
a=1;a/=2r while$><<a<<?+

```

Try it online!

Heavily based on G B's answer. But rationals are fun :V

# Answer
> 1 votes
# MSX-BASIC, 36 bytes

```
1?"1+":X=2
2?"1/";X;"+":X=X*2:GOTO2

```

It works up to 70368744177664, then it starts displaying the values in exponential notation due to the precision limitation of the language, then it overflows at 1e62.

# Answer
> 1 votes
# Taxi, 916 bytes

```
2 is waiting at Starchild Numerology.'1' is waiting at Writer's Depot.Go to Writer's Depot:w 1 r 3 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.Go to Starchild Numerology:s 1 r 1 l 1 l 2 l.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 l 2 r.[r]Pickup a passenger going to Trunkers.Pickup a passenger going to Multiplication Station.Go to Trunkers:s 1 l.Go to Multiplication Station:e 1 r 4 l.Pickup a passenger going to Cyclone.Go to Cyclone:s 1 r 2 l 2 r.Pickup a passenger going to Multiplication Station.Pickup a passenger going to The Babelfishery.' + 1/' is waiting at Writer's Depot.Go to Writer's Depot:s.Pickup a passenger going to Post Office.Go to The Babelfishery:n 1 r 2 r 1 r.Pickup a passenger going to Post Office.Go to Fueler Up:n.Go to Post Office:s 1 r 1 l.Go to Trunkers:s 1 r 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:w 2 r.Switch to plan "r".

```

Try it online! (TIO will output the first 893 terms (up to ~3.3×10²⁶⁸) before cutting it off.)

Ungolfed:

```
2 is waiting at Starchild Numerology.
'1' is waiting at Writer's Depot.
Go to Writer's Depot: west 1st right 3rd left 2nd left.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.
Go to Starchild Numerology: south 1st right 1st left 1st left 2nd left.
Pickup a passenger going to Cyclone.
Go to Cyclone: east 1st left 2nd right.
[r]
Pickup a passenger going to Trunkers.
Pickup a passenger going to Multiplication Station.
Go to Trunkers: south 1st left.
Go to Multiplication Station: east 1st right 4th left.
Pickup a passenger going to Cyclone.
Go to Cyclone: south 1st right 2nd left 2nd right.
Pickup a passenger going to Multiplication Station.
Pickup a passenger going to The Babelfishery.
' + 1/' is waiting at Writer's Depot.
Go to Writer's Depot: south.
Pickup a passenger going to Post Office.
Go to The Babelfishery: north 1st right 2nd right 1st right.
Pickup a passenger going to Post Office.
Go to Fueler Up: north.
Go to Post Office: south 1st right 1st left.
Go to Trunkers: south 1st right 1st left.
Pickup a passenger going to Cyclone.
Go to Cyclone: west 2nd right.
Switch to plan "r".

```

Explanation:

```
Pickup the string `1` and print it to stdout to get started.
Pickup the number `2` and duplicate it so we have one to keep around and one to print.
Abuse the truncation function to leave a `2` for later.
(It's en route and has a short name so it saves bytes which is really important in Taxi.)
Go multiply the running total by 2.
(The first time, it's just a `2` so it returns itself. After that, it's 2 times the running total.)
Pickup the string ` + 1/`.
Convert the multiplication result from a number to a string.
Get gas.
Print the string ` + 1/` and the string multiplication result to stdout.
Go pickup that `2` from Trunkers, copy it again, and go back to `[r]`.

```

The output has trailing zeros on every number: `1 + 1/2.000000 + 1/4.000000 + ...` but, per a comment by OP, that's OK so long as it's the same number of zeros every time.

# Answer
> 1 votes
# Cubix, 26 bytes

```
oruUroorp"/1+"1>O2uw"wo;;q

```

A fairly linear program. Push characters `/1+` onto the stack, push 1 onto the stack. Start loop, output number, multiply it by 2, push it to the bottom, pop the multipliers, output the characters on the stack and loop.

Try it here

Maps to

```
      o r u
      U r o
      o r p
" / 1 + " 1 > O 2 u w "
w o ; ; q * . . . . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

```

# Answer
> 1 votes
# Clojure, 59 bytes

```
#((fn[n](print(if(= 1M n)1(str 1\/ n))\+)(recur(* n 2)))1M)

```

A function that prints the fraction, doubles the denominator, then recurses.

```
(defn zenos-dichotomy-paradox []
  ; Create an anonymous function...
 ((fn [n]
    ; ... that prints the fraction (or just 1 if (= n 1))...
    (print
      (if (= 1M n) 1 (str 1 \/ n))
      \+)
    ; ..., doubles the denominator, then recurses infinitely.
    ; Will not SO since I'm using recur.
    (recur (* n 2)))
   ; Start the recursive function off with a 1. The M makes it a BigInteger so
   ;  I don't get an IntegerOverflow.
  1M))

```

Outputs

```
1 +1/2 +1/4 +1/8 +1/16 +1/32 +1/64 +1/128 +1/256 +1/512...

```

I can make the spacing more consistent at the cost of 2 bytes if necessary.

I tried to be clever and abuse Clojure's built in Ratio number type, but I got an overflow pretty quickly. `1/1` would have been automatically simplified to `1`, getting rid of `1` as a special case. It would have been nice.

# Answer
> 1 votes
# Husk, 9 bytes

```
J'+ms:1İ½

```

Try it online!

due to a lack of a 0 term, 1 is manually prepended.

# Answer
> 1 votes
# MathGolf, 9 bytes

```
ïóoù+1/q∟

```

Try it online.

**Explanation:**

```
        ∟  # Do-while true without popping:
ï          #  Push the 0-based loop index
 ó         #  Pop and push 2 to the power this index
  o        #  Output it with trailing newline (without popping)
   ù+1/    #  Push string "+1/"
       q   #  Pop and push without trailing newline

```

Unfortunately MathGolf doesn't output implicitly even if it errors when we stop the infinite program, otherwise the `o` and `q` would have been unnecessary, because everything on the stack is joined and output implicitly at the end of a (properly terminating) MathGolf program.

# Answer
> 1 votes
# Perl 5 `-Mbigint`, 26 bytes

```
print 2**$_++,'+1/'while 1

```

Try it online!

Using `bigint` means that this could go on forever without turning into a floating point exponential format, given enough time and RAM. TIO gets to about 1/2<sup>922</sup> before cutting off due to the 128 KiB output limit.

# Answer
> 1 votes
# Stax, 7 bytes

```
â─$∩√Öu

```

Run and debug it

same idea as 05AB1E, but Stax has more convenient output here :)

## Explanation

```
Wi^p"+1/
W        loop forever
 i^      increment counter
   p     print without newline
    "+1/ print "+1/" without newline

```

# Answer
> 1 votes
# Factor, 33 bytes

```
1 [ dup "%u+" printf 2 / t ] loop

```

Try it online!

* `1` Push `1` to the stack.
* `[ ... t ] loop` The shortest infinite loop available in Factor.
* `dup "%u+" printf` Non-destructively write the prettyprinted form of an object with a "+" afterward.
* `2 /` Divide by two. In Factor, `/` produces an exact `ratio` as long as its inputs are rational. Use `/i` for integer division or `/f` to force the result to be a float.

# Answer
> 1 votes
# Zephyr, 52 bytes

```
set i to 1
while 1=1
print i,"+"
set i to i/2
repeat

```

Try it online!

Gotta love built-in rational numbers.

For +3 bytes, output with all spaces (no newlines): Try it online!

# Answer
> 0 votes
# Mathematica, 45 bytes

```
Row@Flatten@Table[{1/2^t,"+"},{t,0,Infinity}]

```

# Answer
> 0 votes
# cQuents, 13 bytes

```
|+1/=1:2^($-1

```

Try it online!

### Explanation

```
|+1/            Set sequence join to "+1/"
    =1          Set first item in sequence to 1
      :         Mode : (sequence)
       2^($-1   Each item in the sequence equals 2 to the power of the index (1-based) of the current item minus 1
             )  Implicit closing parenthesis

```

---
Tags: code-golf, math, rational-numbers
---