title: Partitioning the grid into triangles

text:
# Question
Title: Partitioning the grid into triangles
# Goal

The goal of this challenge is to produce a function of `n` which computes the number of ways to partition the `n X 1` grid into triangles where all of the vertices of the triangles are on grid points.

# Example

For example, there are 14 ways to partition the 2 x 1 grid, so `f(2) = 14` via the following partitions  where the partitions have 2, 2, 2, 2, 4, and 2 distinct orientations respectively.

# Scoring

This is , so shortest code wins.

# Answer
# 05AB1E, 13 bytes

```
·LÉœÙεÅγo;P}O

```

Port of *@Bubbler*'s Jelly answer.

Very slow due to the permutations builtin.

Try it online or verify the first four inputs.

**Explanation:**

```
·                # Double the (implicit) input
 L               # Create a list in the range [1, doubled_input]
  É              # Check for each if they're odd (1 if truthy, 0 is falsey)
                 # We now have a list of n 0s and n 1s (n being the input)
   œ             # Get all permutations of that list
    Ù            # Only leave the unique permutations
     ε     }     # Map each permutation to:
      Åγ         #  Run-length encode the current value (short for `γ€g`)
        o        #  Take 2 to the power for each
         ;       #  Halve each
          P      #  Take the product of the mapped permutation
            O    # Sum all mapped values together (and output implicitly)

```
> 2 votes

# Answer
# Haskell, ~~60 55 54~~ 52 bytes

After a drawing and programming a lot of examples, it occured to me that this is the same as the problem of the rooks:

> On a \\$(n+1) \times (n+1)\\$ chessboard, how many ways are there for a rook to go from \\$(0,0)\\$ to \\$(n,n)\\$ by just moving right \\$+(1,0)\\$ or up \\$+(0,1)\\$?

Basically you have the top and the bottom line of the \\$1 \times n\\$ grid. Now you have to fill in the non-horizontal line. Each triangle must have two non-horizontal lines. Whether one of its sides is part of the top or the bottom line corresponds to the direction and length you'd go in the rooks problem. This is OEIS A051708. As an illustration of this correspondence consider following examples. Here the top line corresponds to up-moves, while the bottom line corresponds to right-moves.

Thanks @PeterTaylor for -6 bytes and @PostLeftGarfHunter for -2 bytes!

```
b 0=1
b 1=2
b n=div((10*n-6)*b(n-1)-9*(n-2)*b(n-2))n

```

Try it online!
> 20 votes

# Answer
# Haskell, 42 bytes

```
0?0=1
a?b=sum[a?i+i?a|i<-[0..b-1]]
f n=n?n

```

Try it online!

A fairly direct implementation that recurses over 2 variables.

Here's how we can obtain this solution. Start with code implementing a direct recursive formula:

**54 bytes**

```
0%0=1
a%b=sum$map(a%)[0..b-1]++map(b%)[0..a-1]
f n=n%n

```

Try it online!

Using flawr's rook move interpretation ,`a%b` is the number of paths that get the rook from `(a,b)` to `(0,0)`, using only moves the decrease a coordinate. The first move either decreases `a` or decreases `b`, keeping the other the same, hence the recursive formula.

**49 bytes**

```
a?b=sum$map(a%)[0..b-1]
0%0=1
a%b=a?b+b?a
f n=n%n

```

Try it online!

We can avoid the repetition in `map(a%)[0..b-1]++map(b%)[0..a-1]` by noting that the two halves are the same with `a` and `b` swapped. The auxiliary call `a?b` counts the paths where the first move decreases `a`, and so `b?a` counts those where the first move decreases `b`. These are in general different, and they add to `a%b`.

The summation in `a?b` can also be written as a list comprehension `a?b=sum[a%i|i<-[0..b-1]]`.

**42 bytes**

```
0?0=1
a?b=sum[a?i+i?a|i<-[0..b-1]]
f n=n?n

```

Try it online!

Finally, we get rid of `%` and just write the recursion in terms of `?` by replacing `a%i` with `a?i+i?a` in the recursive call.

The new base case causes this `?` to give outputs double that of the `?` in the 49-byte version, since with `0?0=1`, we would have `0%0=0?0+0?0=2`. This lets use define `f n=n?n` without the halving that we'd other need to do.
> 8 votes

# Answer
## CJam (24 bytes)

```
{2,*e!{e`0f=:(1b2\#}%1b}

```

Online demo

This uses Bubbler's approach of summing over permutations of `n` 0s and `n` 1s.

### Dissection

```
{         e# Define a block
  2,*     e#   Given input n, create an array of n 0s and n 1s
  e!      e#   Generate all permutations of that array
  {       e#   Map:
    e`    e#     Run-length encode
    0f=:( e#     Extract just the lengths and decrement them
    1b    e#     Sum
    2\#   e#     Raise 2 to the power of that sum
  }%
  1b      e#  Sum the mapped values
}

```

---

## Alternative approach (28 bytes)

```
{_1aa{_2$,f{j}@@,f{j}+1b}2j}

```

Online demo

### Dissection

The triangles all have one horizontal edge and two edges which link the horizontal lines. Label the non-horizontal edges by a tuple of their two x-coords and sort lexicographically. Then the first edge is `(0,0)`, the last edge is `(n,n)`, and two consecutive edges differ in precisely one of the two positions. This makes for a simple recursion, which I've implemented using the memoised recursion operator `j`:

```
{            e# Define a block
  _          e#   Duplicate the argument to get n n
  1aa        e#   Base case for recursion: 0 0 => 1
  {          e#   Recursive body taking args a b
    _2$,f{j} e#     Recurse on 0 b up to a-1 b
    @@,f{j}  e#     Recurse on a 0 up to a b-1
    +1b      e#     Combine and sum
  }2j        e#   Memoised recursion with 2 args
}

```

### Note

This is not the first time I've wanted `fj` to be supported in CJam. Here it would bring the score down to 24 bytes also. Perhaps I should try to write a patch...
> 7 votes

# Answer
# Charcoal, ~~44~~ 31 bytes

crossed out 44 is still regular 44

```
Ｆ⊕θ«≔⟦⟧ηＦ⊕θ⊞ηΣ∨⁺ηＥυ§λκ¹⊞υη»Ｉ⊟⊟υ

```

Try it online! Explanation: Works by calculating the number of ways to partition a trapezium of opposite side lengths `m,n` into triangles which all lie on integer offsets. This is simply a general case of the rectangle of size `n` in the question. The number of partitions is given recursively as the sums of the numbers of partitions for all sides `m,0..n-1` and `n,0..m-1`. This is equivalent to generalised problem of the rooks, OEIS A035002. The code simply calculates the number of partitions working from `0,0` up to `n,n` using the previously calculated values as it goes.

```
Ｆ⊕θ«

```

Loop over the rows `0..n`.

```
≔⟦⟧η

```

Start with an empty row.

```
Ｆ⊕θ

```

Loop over the columns in the row `0..n`.

```
⊞ηΣ∨⁺ηＥυ§λκ¹

```

Take the row so far and the values in the previous rows at the current column, and add the sum total to the current row. However, if there are no values at all, then substitute `1` in place of the sum.

```
⊞υη»

```

Add the finished row to the list of rows so far.

```
Ｉ⊟⊟υ

```

Output the final value calculated.
> 4 votes

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

```
Ø.xŒ!QŒɠ€’§2*S

```

Try it online!

-1 byte based on Peter Taylor's comment.

Uses flawr's illustration directly, instead of the resulting formula.

### How it works

```
Ø.xŒ!QŒɠ€’§2*S    Main link (monad). Input: positive integer N.
Ø.x               Make an array containing N zeros and ones
   Œ!Q            All unique permutations
      Œɠ€         Run-length encode on each permutation
         ’§       Decrement and sum each
           2*S    Raise to power of 2 and sum

```

Take every possible route on a square grid. The number of ways to move L units in one direction as a rook is `2**(L-1)`. Apply this to every route and sum the number of ways to traverse each route.
> 4 votes

# Answer
# JavaScript (ES6),  ~~45 44~~  42 bytes

Uses the recursive formula found by Peter Taylor and flawr.

```
f=n=>n<2?n+1:(10-6/n)*f(--n)+9/~n*f(--n)*n

```

Try it online!
> 2 votes

# Answer
# Pari/GP, 43 bytes

According to OEIS, the generating function of this sequence is

$$\frac{1}{2}\left(\sqrt{\frac{1-x}{1-9x}}+1\right)$$

```
n->Vec(sqrt((1-x)/(1-9*x)+O(x^n++))+1)[n]/2

```

Try it online!
> 2 votes

# Answer
# Python 3, 51 bytes

```
lambda n:-~n*(n<2)or(10-6/n)*f(n-1)-(9-18/n)*f(n-2)

```

Try it online!

Port of flawr's answer
> 1 votes

---
Tags: code-golf, geometry, combinatorics, grid
---


title: Let's play Peg Solitaire

text:
# Question
Title: Let's play Peg Solitaire
Peg solitaire is a popular game usually played alone. The game consists of some number of pegs and a board which is divided into a grid - usually the board is not rectangular but for this challenge we will assume so.

Each valid move allows one to remove a single peg and the goal is to play in a way, such that there is a single peg left. Now, a valid move has to be in a single direction (north, east, south or east) and jump over one peg which can be removed.

## Examples

Let `.` be empty spaces on the board and numbers are pegs, the following move will move `1` one to the right and remove `2` from the board:

```
.....     .....
.12..  -> ...1.
.....     .....

```

A move will always have to jump over a single peg, so the following is **not** valid:

```
......    ......
.123.. -> ....1.
......    ......

```

Here are some valid configurations after one move each:

```
...1...        ...1...        ..71...        ..71...
.2.34.5  --->  .24...5  --->  .2....5  --->  ......5
.678...  (4W)  .678...  (7N)  .6.8...  (2S)  ...8...
.......        .......        .......        .2.....

```

## Challenge

Given an initial board configuration and some other configuration, output whether the other configuration can be reached by successively moving pegs around as described above.

## Rules

* Input will be a \\$n \times m\\$ matrix/list of lists/... of values indicating an empty space (eg. zero or false) or pegs (eg. non-zero or true)
    + you may assume \\$n \geq 3\\$ and \\$m \geq 3\\$
    + you may use true/non-zero to indicate empty spaces and vice-versa if it helps
* Output will be two distinct (one of the values might differ) values indicating whether the end-configuration can be reached (eg. *falsy*/*truthy*, `[]`/`[list of moves]` ..)

## Test cases

```
initial  goal -> output
[[1,0,0],[1,1,0],[0,1,0]]  [[0,0,0],[0,1,0],[1,1,0]] -> True
[[1,0,0],[1,1,0],[0,1,0]]  [[0,0,1],[0,1,1],[0,0,0]] -> False
[[0,0,0],[1,0,0],[0,0,0]]  [[0,0,0],[0,0,1],[0,0,0]] -> False
[[0,0,0],[1,1,0],[0,0,0]]  [[0,0,0],[0,1,1],[0,0,0]] -> False
[[0,0,0,0],[1,1,1,0],[0,0,0,0]]  [[0,0,0,0],[0,0,0,1],[0,0,0,0]] -> False
[[1,0,0],[1,1,0],[1,1,1],[1,1,1]]  [[0,0,1],[0,1,0],[1,0,0],[0,0,1]] -> True
[[1,0,0],[1,1,0],[1,1,1],[1,1,1]]  [[1,0,0],[0,0,0],[0,0,0],[0,0,0]] -> False
[[1,0,1,1],[1,1,0,0],[1,1,1,0],[1,0,1,0]]  [[0,0,1,0],[1,0,0,0],[1,0,1,0],[1,0,0,1]] -> True
[[1,0,1,1],[1,1,0,0],[1,1,1,0],[1,0,1,0]]  [[0,0,0,0],[0,0,0,0],[0,0,1,0],[0,0,0,0]] -> False
[[1,0,0,0],[1,1,0,0],[1,1,1,0],[1,0,1,0]]  [[0,0,0,0],[0,0,0,0],[0,0,1,0],[0,0,0,0]] -> True
[[0,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,0]]  [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] -> False
[[0,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,0]]  [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] -> False
[[0,0,0,1,0,0,0],[0,1,0,1,1,0,1],[0,1,1,1,0,0,0],[0,0,0,0,0,0,0]]  [[0,0,0,1,0,0,0],[0,1,0,1,1,0,1],[0,1,1,1,0,0,0],[0,0,0,0,0,0,0]] -> True
[[0,0,0,1,0,0,0],[0,1,0,1,1,0,1],[0,1,1,1,0,0,0],[0,0,0,0,0,0,0]]  [[0,0,0,1,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0]] -> True
[[0,0,1,1,1,0,0],[0,0,1,1,1,0,0],[1,1,1,1,1,1,1],[1,1,1,0,1,1,1],[1,1,1,1,1,1,1],[0,0,1,1,1,0,0],[0,0,1,1,1,0,0]]  [[0,0,1,1,1,0,0],[0,0,1,1,1,0,0],[1,1,1,1,1,1,1],[1,1,1,1,0,0,1],[1,1,1,1,1,1,1],[0,0,1,1,1,0,0],[0,0,1,1,1,0,0]] -> True
[[0,0,1,1,1,0,0],[0,0,1,1,1,0,0],[1,1,1,1,1,1,1],[1,1,1,0,1,1,1],[1,1,1,1,1,1,1],[0,0,1,1,1,0,0],[0,0,1,1,1,0,0]]  [[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,1,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0]] -> True

```

# Answer
> 2 votes
# JavaScript (ES6),  ~~184 178~~  173 bytes

Takes input as `(initial_board)(target_board)`. Returns \\$0\\$ or \\$1\\$.

```
a=>g=b=>a+''==b|a.some((r,y)=>r.some((v,x,A,X,R)=>[-1,0,1,2].some(h=>(A=a[y+(R=~-h%2)]||0)[X=x+(h%=2)]&v>(R=a[y+R*2]||0)[h+=x+h]&&g(b,A[X]=r[x]=R[h]++)&(A[X]=r[x]=R[h]--))))

```

Try it online!

(removed the last two test cases that take too much time for TIO)

### Commented

```
a =>                             // main function taking the initial board a[]
  g = b =>                       // g = recursive function taking the target board b[]
    a + '' == b |                // yield a truthy result if a[] is matching b[]
    a.some((r, y) =>             // for each row r[] at position y in a[]:
      r.some((v, x, A, X, R) =>  //   for each value v at position x in r[]:
        [-1, 0, 1, 2]            //     list of directions (West, North, East, South)
        .some(h =>               //     for each direction h:
          ( A =                  //       A = a[y + dy]
            a[y + (R = ~-h % 2)] //       R = dy
            || 0                 //       use a dummy row if we're out of the board
          )[X = x + (h %= 2)]    //       h = dx, X = x + dx
          &                      //       yield 1 if there's a peg on the skipped cell
          ( R =                  //       R = target row
            a[y + R * 2]         //         = a[y + 2 * dy]
            || 0                 //       use a dummy row if we're out of the board
          )[h += x + h]          //       h = x + 2 * dx = target column
          < v                    //       yield 1 if there's no peg on the target cell
          &&                     //       and there's a peg on the source cell (0 < 1)
          g(                     //       if the above result is true, do a recursive call:
            b,                   //         pass b[] unchanged
            A[X] = r[x] =        //         clear the source and skipped cells
            R[h]++               //         set the target cell
          ) & (                  //       and then restore the board to its initial state:
            A[X] = r[x] =        //         set the source and skipped cells
            R[h]--               //         clear the target cell
          )                      //
        )                        //     end of some() over directions
      )                          //   end of some() over columns
    )                            // end of some() over rows

```

# Answer
> 1 votes
# Clean, 232 bytes

```
import StdEnv,Data.List
r=reverse
@[a:t=:[b,c:u]]=[[a:v]\\v<- @t]++take(a*b-c)[[0,0,1:u]];@l=[]

```

#

```
flip elem o\c=limit(iterate(nub o concatMap\l=[l]++[f(updateAt i p(f l))\\f<-[id,transpose],q<-f l&i<-[0..],p<- @q++(map r o@o r)q])[c])

```

Try it online!

This is one of the rare occasions in which I can utilize composition and currying while saving bytes.

Explained:

`@ :: [Int] -> [[Int]]` is a helper function used to generate the different potential *new* rows/columns that could result from a move being made. It avoids needing to special-case `[1,1,0:_]` by noticing that `a*b-c>0` only when `[a,b,c]=[1,1,0]`, and so `take(a*b-c)...` gives `[]` by taking `-1` or `0` elements for all configurations that aren't a valid move.

`flip elem o...` reverses the order of arguments to `elem` (making it "does x contain a y" instead of "is x a member of y") and applies the anonymous function on `c` to the first argument.

`\c=limit(iterate(nub o concatMap ...)[c])` generates every potential board that can result from the `c` by joining the current set of boards with all the moves that can happen on all of the boards and removing the duplicates, until the result stops changing.

`\l=[l]++...` prepends the board `l` to the list of all potential new boards one-move distance away, generated by applying `@` to the rows of each orientation of the board (0, 90, 180, 270-degree rotations) and replacing the corresponding changed row with the new row.

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


title: How frustrating is my movie?

text:
# Question
Title: How frustrating is my movie?
My parents have an home theater device. The remote is broken making it incredibly difficult to navigate rightwards in a menu. Most the time it doesn't work but when it does it moves rightwards incredibly quickly.

This is obviously frustrating but it is most frustrating when you want to enter a movie title which requires navigating a keyboard that looks like this:

```
a b c d e f
g h i j k l
m n o p q r
s t u v w x
y z 1 2 3 4
5 6 7 8 9 0

```

Your task is to take as input a movie title and calculate how "frustrating" it is to type that movie title. The frustration number of a particular string is the number of letters that require moving right from the letter before them. We don't care how far right they are, since if we start moving right we pretty much instantly go to the end of the line, and we don't care about up, down or leftwards movement because they are easy.

For example if we wanted to type in

```
keyboard

```
* We start at `k` for free.
* `e` is just above `k` so we don't need to move right.
* `y` is all the way left so no need to move right.
* `b` however is on the next column rightwards so we need to move right to get to it.
* `o` is on the next column over so we have to move rightwards to get to it.
* `a` is back in the first column so we move left to get to it.
* `r` is all the way on the right so we move right to it.
* `d` is two columns to the left of `r`'s column.

The characters that need to move to the right are `bor` meaning that this is frustration 3.

## Additional rules

This is a challenge so your answers will be scored in bytes with fewer bytes being better. The input will always consist of alphanumeric characters, you can support either capital or lowercase letters and you only need to support one. The input will never be empty.

## Testcases

```
keyboard -> 3
2001aspaceodyssey -> 6
sorrytobotheryou -> 8
thinblueline -> 5
blast2 -> 3

```

# Answer
> 8 votes
# JavaScript (Node.js), ~~61~~ ~~55~~ 54 bytes

*Saved 1 byte thanks to @nwellnhof*

Takes input as an array of characters.

```
s=>s.map(p=c=>r+=p>(p=(+c?~c:1-Buffer(c)[0])%6),r=0)|r

```

Try it online!

### How?

For all characters but digits greater than \\$0\\$, the 0-indexed column \\$x\\$ is given by:

$$x=(c-1)\bmod 6$$

where \\$c\\$ is the ASCII code of the character.

For positive digits \\$n\\$, we need to do instead:

$$x=(n+1)\bmod 6$$

*Examples:*

```
"a" --> (97 - 1) mod 6 = 96 mod 6 = 0
"b" --> (98 - 1) mod 6 = 97 mod 6 = 1
"0" --> (48 - 1) mod 6 = 47 mod 6 = 5
"3" --> ( 3 + 1) mod 6 =  4 mod 6 = 4

```

### Commented

```
s =>                       // s = input string (as array)
  s.map(p =                // initialize p to a non-numeric value
  c =>                     // for each character c in s:
    r +=                   //   update the result r:
      p > (                //   compare p with
        p = (              //   the new value of p defined as:
          +c ?             //     if c is a positive digit:
            ~c             //       -(int(c) + 1)
          :                //     else:
            1-Buffer(c)[0] //       -(ord(c) - 1)
        ) % 6              //     apply modulo 6
      ),                   //   yields 1 if the previous value is greater than the new one
    r = 0                  //   start with r = 0
  ) | r                    // end of map(); return r

```

# Answer
> 7 votes
# Jelly, 11 bytes

```
⁾04yO‘%6<ƝS

```

A monadic Link accepting a list of (uppercase) characters.

**Try it online!**

### How?

First replaces any `'0'`s with `'4'`s (so the rest of the code treats them as being in the rightmost column). Then casts to ordinals, adds one and modulo's by `6` to get 0-based column indices. Then compares neighbours with is-less-than and sums the result.

```
⁾04yO‘%6<ƝS - Link: list of characters         e.g. "BLAST20"
⁾04         - list of characters = ['0', '4']
   y        - translate                             "BLAST24"
    O       - ordinals                              [66,76,65,83,84,50,52]
     ‘      - increment                             [67,77,66,84,85,51,53]
       6    - literal six
      %     - modulo                                [ 1, 5, 0, 0, 1, 3, 5]
         Ɲ  - neighbourly:
        <   -   less than?                          [  1, 0, 0, 1, 1, 1  ]
          S - sum                                   4

```

# Answer
> 3 votes
# Perl 6, ~~45~~ 39 bytes

```
{sum .[1..*]Z<$_}o{(2 X-.ords)X%46 X%6}

```

Try it online!

Works with uppercase letters. `(2-ord(c))%46%6` computes the reversed x coordinate.

# Answer
> 1 votes
# K (ngn/k), ~~32 31~~ 28 bytes

```
+/>':6!(,/"a10"+!'26 9 1)?0+

```

Try it online!

# Answer
> 1 votes
# Japt `-x`, 14 bytes

```
®rT4 c Ä u6Ãä<

```

Try it online!

Port of this Jelly answer. Takes input as an array of characters, with letters uppercase.

Explanation:

```
®rT4 c Ä u6Ãä<    :
®          Ã      :Map each character through:
 rT4              : Replace 0 with 4
     c            : Get the char-code
       Ä          : Increment it
         u6       : Modulo 6
            ä<    :Replace with 1 if you had to move right, 0 otherwise
                  :Implicitly sum and output

```

# Answer
> 1 votes
# Clean, 85 bytes

```
import StdEnv
(\s=sum[1\\a<-s&b<-tl s|b>a])o map(\e=(toInt e+if(e-'1'>'/')1 -1)rem 6)

```

Try it online!

# Answer
> 1 votes
# Ruby, 56 bytes

```
->s{w=9;s.count{|c|w<w=[*?a..?z,*?1..?9,?0].index(c)%6}}

```

Try it online!

Preliminary naive version, will be golfed.

# Answer
> 1 votes
# 05AB1E, ~~12~~ 11 bytes

-1 byte thanks to @Kevin Cruijssen

```
¾4:Ç>6%¥1@O

```

Another port of Jonathan Allan's Jelly answer. Takes input in uppercase.

Explanation:

```
¾4:Ç>6%¥1@O   //full program
¾4:           //replace all '0's with '4's
   Ç          //get ASCII code points
    >         //increment
     6%       //modulo 6
       ¥      //get deltas
        1@    //is >= 1
          O   //sum

```

Try it online!

# Answer
> 1 votes
# Java (OpenJDK 8), 73 bytes

Not a bad solution for Java! That zero being on the right-hand side cost me several bytes.

```
t->{int a=9,c=0;for(int d:t)c+=a<(a=(--d+(d/48==1?2:0))%6)?1:0;return c;}

```

Try it online!

**Explained**

```
t -> {                          // Lambda taking a char array as input
    int a=9,                    // Initialise last column value
        c=0;                    // Initialise frustration count
    for(int d:t)                // Loop through all chars in title
        c+=                     // increment the frustration count if...
          a<                    // The last column is smaller than the current column
            (a=                 // Set last column to current column
              (--d+             // Decrement ascii value of char
                  (d/48==1      // If ascii decremented ascii value is between 48 and 95
                    ?2:0)       // increment by 2 (1 total) or 0 (-1 total)
                )%6)            // Mod 6 to retrieve column index
            ?1:0;               // Increment if to right hand side
    return c;                   // return calculated frustration count
}

```

# Answer
> 0 votes
# Retina 0.8.2, 46 bytes

```
T`l1-90`1-61-61-61-61-61-6
.
;$&$*
&`;(1+);1\1

```

Try it online! Link includes test cases. Explanation:

```
T`l1-90`1-61-61-61-61-61-6

```

List the alphabet and digits in the order on the OSK and map each one to a (1-indexed) column number.

```
.
;$&$*

```

Convert each column number to unary.

```
&`;(1+);1\1

```

Count the number of columns that are followed by a larger (i.e. rightwards) column. The `&`` allows the matches to overlap.

# Answer
> 0 votes
# Python 2, 84 bytes

```
def f(s,k=6):j=(ord(s[0])+('0'<s[0]<':')*2-1)%6;return(j>k)+(~-len(s)and f(s[1:],j))

```

Try it online!

# Answer
> 0 votes
# Mathematica, 102 bytes

```
Differences[Last@@Join[Alphabet[],ToString/@Range@9,{"0"}]~Partition~6~Position~#&/@#]~Count~_?(#>0&)&

```

Pure function. Takes a list of characters as input and returns a number as output. This is a pretty naive solution, golfing suggestions welcome.

# Answer
> 0 votes
# C (gcc),  ~~82 79~~  77 bytes

```
o;c(i){i+=i<60&i>48?1:5;i%=6;}f(char*s){for(o=0;*++s;o+=c(*s)>c(s[-1]));o=o;}

```

Try it online!

This function will only support lowercase inputs

---

# Ungolfed and commented:

```
o; //Used for output
c(i){             //Calculates the column of given character
     i+=          //Correct i to get the correct column
        i<60      //If i is a digit...
        & i>48   //... but not '0'
        ?1           //Then move it one column on the right
        :5;          //Else move it five columns on the right
     i%=6;        //Get the column number
}
f(char*s){                        // The actual "frustrating" function
          for(                    //Loop for each character
              o=0;                //reinitialize output
              *++s;               //move to next character / while this is not '\0'
              o+=c(*s)>c(s[-1])  //Increment if current character is on the right of the previous one
             );
           o=o;                   // Outputs result
}

```

---

If my function is allowed to accept wide character strings, it can be reduced to **76 bytes** with:

```
o;c(i){i+=i<60&i>48?1:5;i%=6;}f(int*s){for(o=0;*++s;o+=c(*s)>c(s[-1]));o=o;}

```

Try it online!

This version just accept input as `int*` instead of `char*`

---

# Edits:

* Golfed 3 bytes in the calculation of the column (function `c`)
* Golfed 2 bytes thanks to ceilingcat

# Answer
> 0 votes
# PHP, ~~74 81~~ 77 bytes

```
for(;$o=ord($argn[$i]);$i++&&$f+=$p<$x,$p=$x)$x=(--$o/48^1?$o:$o+2)%6;echo$f;

```

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

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


title: Convert an Excel date code to a "date"

text:
# Question
Title: Convert an Excel date code to a "date"
Given a non-negative integer Excel-style date code, return the corresponding "date" in any reasonable form that clearly shows year, month, and "day".

Trivial, you may think. Did you notice the "scare quotes"? I used those because Excel has some quirks. Excel counts days with number 1 for January 1st, 1900, but as if 1900 had a January 0th and a February 29th, so be very careful to try all test cases:

```
 Input → Output (example format)
     0 → 1900-01-00    Note: NOT 1899-12-31
     1 → 1900-01-01
     2 → 1900-01-02
    59 → 1900-02-28
    60 → 1900-02-29    Note: NOT 1900-03-01
    61 → 1900-03-01
   100 → 1900-04-09
  1000 → 1902-09-26
 10000 → 1927-05-18
100000 → 2173-10-14

```

# Answer
> 13 votes
# Excel, 3(+7?)

```
=A1

```

with format

```
yyy/m/d

```

Pure port

# Answer
> 6 votes
# k (kdb+ 3.5), ~~55~~ ~~54~~ ~~51~~ 50 bytes

```
{$(`1900.01.00`1900.02.29,"d"$x-36526-x<60)0 60?x}

```

to test, paste this line in the q console:

```
k)-1@{$(`1900.01.00`1900.02.29,"d"$x-36526-x<60)0 60?x}'0 1 2 59 60 61 100 1000 10000 100000;

```

the output should be

```
1900.01.00
1900.01.01
1900.01.02
1900.02.28
1900.02.29
1900.03.01
1900.04.09
1902.09.26
1927.05.18
2173.10.14

```

`{` `}` is a function with argument `x`

`0 60?x` index of `x` among `0 60` or 2 if not found

`ˋ1900.01.00ˋ1900.02.29` a list of two symbols

`,` append to it

`"d"$` converted to a date

`x-36526` number of days since 1900 (instead of the default 2000)

`- x<60` adjust for excel's leap error

`(ˋ1900.01.00ˋ1900.02.29,"d"$x-36526-x<60)`@`0 60?x` juxtaposition means indexing - the "@" in the middle is implicit

`$` convert to string

# Answer
> 3 votes
# Python 2, 111 bytes

```
from datetime import*
n=input()
print('1900-0'+'12--0209'[n>9::2],date(1900,1,1)+timedelta(n+~(n>59)))[0<n!=60]

```

Try it online!

-5 thanks to ngn.

# Answer
> 3 votes
# JavaScript (ES6),  ~~89 82~~  77 bytes

*Saved  ~~7~~  12 bytes thanks to @tsh*

```
n=>(p=n>60?'':19)+new Date(p*400,0,n-!p||1).toJSON().slice(p/9,10-!n)+(n&&'')

```

Try it online!

# Answer
> 2 votes
# Clean, ~~205~~ 189 bytes

```
import StdEnv
a=30;b=31;c=1900;r=rem
@m=sum(take m(?c))
?n=[b,if(n>c&&(r n 4>0||r n 100<1&&r n 400>0))28 29,b,a,b,a,b,b,a,b,a,b: ?(n+1)]
$n#m=while(\m= @m<n)inc 0-1
=(c+m/12,1+r m 12,n- @m)

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog Classic), 31 bytes

Anonymous tacit prefix function. Returns date as `[Y,M,D]`

```
(¯3↑×-60∘≠)+3↑2⎕NQ#263,60∘>+⊢-×

```

Try it online!

`×` sign of the date code

`⊢-` subtract that from the argument (the date code)

`60∘>+` increment if date code is above sixty

`2⎕NQ#263,` use that as immediate argument for "Event 263" (IDN to date)
IDN is just like Excel's date code, but without Feb 29, 1900, and the day before Jan 1, 1900 is Dec 31, 1899

`3↑` take the first three elements of that (the fourth one is day of week)

`(``)+` add the following to those:

`60∘≠` 0 if date code is 60; 1 if date code is not 60

`×-` subtract that from the sign of the date code

`¯3↑` take the last three elements (there is only one) padding with (two) zeros

developed together with @Adám in chat

# Answer
> 1 votes
# Japt, 43 bytes

Ended up with a part port of Arnauld's solution.

Output is in `yyyy-m-d` format.

```
?U-#<?Ð#¾0TUaU>#<)s7:"1900-2-29":"1900-1-0"

```

Try it online or test 0-100

# Answer
> 1 votes
# C# (.NET Core), ~~186~~ 185 bytes

```
using System;class P{static void Main(){var i=int.Parse(Console.ReadLine());Console.Write((i==0|i==60)?$"1900-{i%59+1}-{i%31}":DateTime.FromOADate(i+(i<60?1:0)).ToString("yyyy-M-d"));}}

```

Try it online!

---

-1 byte by replacing OR operator(||) with binary OR operator(|).

# Answer
> 0 votes
# Perl 6, 81 bytes

```
{$_??$_-60??Date.new-from-daycount($_+15018+(60>$_))!!'1900-02-29'!!'1900-01-00'}

```

Try it online!

# Answer
> 0 votes
# T-SQL, ~~141 95~~ 94 bytes

```
SELECT IIF(n=0,'1/0/1900',IIF(n=60,'2/29/1900',
FORMAT(DATEADD(d,n,-IIF(n<60,1,2)),'d')))FROM i

```

Line break is for readability only.

Input is taken via pre-existing table **i** with integer field **n**, per our IO standards.

SQL uses a similar (but corrected) 1-1-1900 starting point for its internal date format, so I only have to offset it by 1 or 2 days in the `DATEADD` function.

SQL can't output a column containing a mix of date and character values, so I can't leave off the `FORMAT` command (since it would then try to convert `1/0/1900` to a date, which is of course invalid).

What's nice about SQL is that I can load up all the input values into the table and run them all at once. My (US) locality defaults to a `m/d/yyyy` date format:

```
n       output
0       1/0/1900
1       1/1/1900
2       1/2/1900
59      2/28/1900
60      2/29/1900
61      3/1/1900
100     4/9/1900
1000    9/26/1902
10000   5/18/1927
43432   11/28/2018
100000  10/14/2173

```

**EDIT**: Saved 46 bytes by changing to a nested `IIF()` instead of the much more verbose `CASE WHEN`.

**EDIT 2**: Saved another byte by moving the `-` in front of the `IIF`.

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


title: ASCII Ball in Box Animation

text:
# Question
Title: ASCII Ball in Box Animation
Write a program that displays a moving ASCII ball `*` inside a rectangle (20 by 10 chars including border). The ball must not cross the rectangle, e.g. bump off when it hits the wall. The scene must be cleared and redrawn every 0.1 seconds and the ball must move 1 char in x and y direction every frame. The shortest program written in any language wins.

**Example output (frame 1)**

```
+------------------+
|*                 |
|                  |
|                  |
|                  |
|                  |
|                  |
|                  |
|                  |
+------------------+

```

**Example output (frame 2)**

```
+------------------+
|                  |
| *                |
|                  |
|                  |
|                  |
|                  |
|                  |
|                  |
+------------------+

```

**Example output (frame 8)**

```
+------------------+
|                  |
|                  |
|                  |
|                  |
|                  |
|                  |
|                  |
|       *          |
+------------------+

```

**Example output (frame 9)**

```
+------------------+
|                  |
|                  |
|                  |
|                  |
|                  |
|                  |
|        *         |
|                  |
+------------------+

```

# Answer
## Ruby 1.9, 115 characters

The movement logic is quite similar to Danko's answer.

This version has been tested on Linux only.

```
p=0
loop{u=(?|+?\s*18+"|
")*8
u[165-21*(7-p%14).abs-(17-p%34).abs]=?*
p+=1
puts"\e[2J",r=?++?-*18+?+,u,r
sleep 0.1}

```
> 7 votes

# Answer
## Powershell, 144 characters

Based on Joey's excellent answer, using the fact that the ball coordinates are a function of the frame index (i), so if you have something like `x=n-abs(n-(i mod (2*n)))`, x will go from 0 to n, back to 0, and so on...

```
for(){cls
($l="+$('-'*18)+")
7..0|%{$j=$_
"|$(-join(17..0|%{'* '[$j-[Math]::abs(7-$i%14)-or$_-[Math]::abs(17-$i%34)]}))|"}
$l;$i++;sleep -m 100}

```
> 4 votes

# Answer
## Ruby (179 174 147)

**EDIT** got rid of some more chars:

```
l=?++?-*18+?++?\n
c=?|+?\s*18+?|+?\n
p=22
u=v=1
loop{f=l+c*8+l
f[p]=?*
puts"\e[2J"+f
p+=(u=f[p+u]==' '?u:-u)+21*(v=f[p+21*v]==' '?v:-v)
sleep 0.1}

```

**EDIT** shaved off some chars, now 174:

```
l="+#{'-'*18}+\n";f=l+"|#{' '*18}|\n"*8+l;x=y=u=v=1
loop{f[21*y+x]='*';$><<"\e[2J\e[f"+f;f[21*y+x]=' '
u=f[21*y+x+u]==' '?u:-u;v=f[21*(y+v)+x]==' '?v:-v
x+=u;y+=v;sleep 0.1}

```

Ungolfed:

```
l="+#{'-'*18}+\n"           # top and bottom lines
f=l+"|#{' '*18}|\n"*8+l     # complete box as string
x=y=u=v=1                   # x,y position; u,v next move
loop {                      #
  f[21*y+x]='*'             # add ball to box
  $> << "\e[2J\e[f"+f       # clear screen and print box with ball
  f[21*y+x]=' '             # remove ball from box
  u=f[21*y+x+u]==' '?u:-u   # next move in x direction
  v=f[21*(y+v)+x]==' '?v:-v # next move in y direction
  x+=u                      # perform move
  y+=v                      # --"--
  sleep 0.1                 # .zZZ...
}                           #

```
> 3 votes

# Answer
## Python 2, 234

I'm sure this can be golfed more, but I gotta go so here's what I have sofar. will work more on it later

```
import os,time
a,b,c,d,e,n='+- |*\n'
w=d+c*18+d+n
s=a+b*18+a+n
x,y=0,0
g,h=17,7
j,k=1,1
while 1:
 if 0>x or x>g:j*=-1;x+=j
 if 0>y or y>h:k*=-1;y+=k
 os.system('cls');print s+w*y+d+c*x+e+c*(g-x)+d+n+w*(h-y)+s;x+=j;y+=k;time.sleep(0.1)

```

note: works on Windows command console. Other operating systems may use a different command than `cls` to clear the screen, such as `clear`
> 3 votes

# Answer
## JavaScript (275 283)

```
s=Array(19).join(' ');n='\n';z=Array(9).join('|'+s+'|'+n).split(n,8);
x=y=0;a=b=1;t='+'+s.replace(/ /g,'-')+'+';
setInterval(function(){u=z[y];z[y]=u.replace(eval('/( {'+x+'}) /'),'$1*');
$('#o').text(t+n+z.join('\n')+n+t);z[y]=u;x+=a;y+=b;if(!x|x==17)a=-a;if(!y|y==7)b=-b},100)

```

Demo: http://jsfiddle.net/eKcfu/2/

I wrote this up pretty quickly so I'm sure there's still quite a bit of room for improvement. Suggestions are welcome :)

**Edit 1**: Remove unnecessary separate function call, embed directly in `setInterval`.
> 2 votes

# Answer
### PowerShell, 184 ~~185~~ ~~215~~

Only semi-golfed as my brain isn't working properly when I'm sick ...

A few nice tricks in it, though.

```
for($a=$b=1){cls
($l="+$('-'*18)+")
0..7|%{$j=$_
"|$(-join(0..17|%{'* '[$j-$y-or$_-$x]}))|"}
$l
$x+=$a;$y+=$b
if(-1,18-eq$x){$a*=-1;$x+=2*$a}if(-1,8-eq$y){$b*=-1;$y+=2*$b}sleep -m 100}

```

\[Edit\]: Looping over the field is much shorter.
> 2 votes

# Answer
## Haskell, 212 characters

```
import System
main=mapM_ f$s 19`zip`s 9
s n=[2..n]++[n-1,n-2..3]++s n
f p=r"clear">>putStr(unlines[[" |-+*"!!(19#i+2*(9#j)+4*e((i,j)==p))|i<-[1..20]]|j<-[1..10]])>>r"sleep 0.1"
b#n=e$n<2||n>b
e=fromEnum
r=system

```

Uses a more functional approach for calculating the coordinates, by making the infinite sequence for each coordinate separately and then zipping them together (lines 2 and 3). The rest is drawing code.
> 2 votes

# Answer
## QBasic (QB64), ~~178~~ 173 bytes

```
a$="+------------------+
?a$
for c=1to 8
?"|                  |
next
?a$
do
x=19-abs(17-(i mod 34))
y=9-abs(7-(i mod 14))
locate y,x
?"*
_delay .1
locate y,x
?" "
i=i+1
loop

```

-5 bytes thanks to DLosc
> 2 votes

# Answer
## Perl 5, 141 characters

```
print"\e[H\e[2J",$h="+"."-"x18 ."+
",(map{"|".$"x$q,(abs$t%14-7)-$_?$":"*",$"x(17-$q),"|
"}0..7),$h,select'','','',0.1while$q=abs$t++%34-17,1

```

Does not start on the upper left corner as the example output does, but that is not stated as a requirement.
> 1 votes

# Answer
## Ruby 1.9, 162 characters

35 chars shy of @Ventero's answer, but I was impressed that I could get it down this far while still using a relatively straightforward approach to the actual logic. The ^\[ is a literal ESC (1 char).

```
x=y=0
v=h=1
s=' '
loop{puts"^[[2J"+b="+#{?-*18}+",*(0..7).map{|i|"|#{i!=y ?s*18:s*x+?*+s*(17-x)}|"},b
y+=v
y+=v*=-1if y<0||y>7
x+=h
x+=h*=-1if x<0||x>17
sleep 0.1}

```
> 1 votes

# Answer
## R, 233 characters

```
s=c("\n+",rep("-",18),"+");for (j in 1:8){cat(s,sep="");cat(rep(c("\n|",rep("",17),"|"),j-1));cat(c("\n|",rep(" ",j-1),"*",rep(" ",18-j),"|"),sep="");cat(rep(c("\n|",rep("",17),"|"),8-j));cat(s,sep="");Sys.sleep(0.1);system("clear")}

```
> 1 votes

# Answer
**Another bash entry - ~~213~~ 204 chars**

Not really a prize winner, but it was fun nonetheless. It uses vt100 char sequences for the drawing. (the code reported here uses 215 chars for readability, 2 chars can be removed by escaping, e.g. '\*' -\> \\\*

```
e(){ printf "\e[$1";}
e 2J;e H
h='+------------------+'
echo $h
for((;++j<9;));do printf '|%18s|\n';done
echo $h
e '3;2H*'
while :;do
e 'D '
((i/17%2))&&e D||e C
((++i/7%2))&&e A||e B
e 'D*'
sleep .1
done

```
> 1 votes

# Answer
# Powershell, 139 bytes

*Inspired by Danko Durbić's answer.*

```
for(){cls
,"+$('-'*18)+
"*2-join("|$(' '*18)|
"*8-replace"^(\W{$(21*[Math]::abs(7-$i%14)+[Math]::abs(17-$i++%34))}.) ",'$1*')
sleep -m 100}

```

This script uses the `-replace` operator to draw `*` inside the rectangle.

Less golfed script to explain how it works:

```
for(){
    cls
    $y=[Math]::abs(7-$i%14)
    $x=[Math]::abs(17-$i++%34)
    $b="+$('-'*18)+`n"
    $m="|$(' '*18)|`n"*8-replace"^(\W{$(21*$y+$x)}.) ",'$1*'
    ,$b*2-join($m)          # draw it
    sleep -m 100
}

```
> 1 votes

# Answer
### Bash 278  300, 296

```
h="+------------------+"
w="|                  |"
g(){
echo -e "\e[$2;$1H$3"
}
g 1 1 $h
for i in {1..8}
do
echo "$w"
done
echo $h
x=4
y=4
p=1
q=1
for((;;))
do
((x==19&&p==1||x==2&&p==-1))&&p=-$p
((y==9&&q==1||y==2&&q==-1))&&q=-$q
x=$((x+p))
y=$((y+q))
g $x $y \*
sleep .1
g $x $y " "
done

```

The \e in the line `echo -e "\e[$2;$1H$3"` can be produced by

```
echo -e "\x1b"

```

to replace it. As binary 0x1b it is 3 chars shorter; I count just 1 for "\e", because only the layouting software forces me to use `\e`.
> 0 votes

# Answer
# TI Basic, ~~169~~ 167 bytes

```
1→X
1→Y
1→S
1→T
While 1
ClrHome
Output(Y,X,"*
S(X>1 and X<20)+(X=1)-(X=20→S
T(Y>1 and Y<10)+(Y=1)-(Y=10→T
X+S→X
Y+T→Y
For(N,1,20,19
For(O,1,10,9
Output(O,N,"+
End
End
For(N,2,19
For(O,1,10,9
Output(O,N,"-
End
End
For(O,2,9
Output(O,1,"|
Output(O,20,"|
End
End

```

Horribly slow, but it works.
> 0 votes

# Answer
# PHP, ~~196 186~~ 148 bytes

I removed avoiding an integer overflow to save 6 bytes. It will run for 29 billion years before overflow; still 6.8 years on a 32 bit system. I´d say that´s acceptable.

Calculating the position instead of adjusting it saved a lot, preparing the complete template at once another lot.

```
for(;++$i;$s[-3-21*abs($i%14-7)-abs($i%34-17)]="*",print$f(_,9e5,"
").$s.$z,usleep(1e5))$s=($f=str_pad)($z=$f("+",19,"-")."+
",189,$f("|",19)."|
");
").$z;

```

Run with `-nr`. Requires PHP 7.1.

**breakdown**:

```
for(;++$i;      # infinite loop:
                    # 2. set asterisk at appropriate position
    $s[-3-21*abs($i%14-7)-abs($i%34-17)]="*";
                    # 3. clear screen: print 900k newlines
    print$f(_,9e5*0+2,"\n")
            .$s.$z, # 4. print field
    usleep(1e5))    # 5. sleep 100000 microseconds
                    # 1. create template
    $s=($f=str_pad)($z=$f("+",19,"-")."+\n",189,$f("|",19)."|\n");

```
> 0 votes

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


title: Lazy word problems

text:
# Question
Title: Lazy word problems
# Summary

A teacher was told to prepare word problems for the students. She is given a list of equations and told to write them as the corresponding word problem. However, she is very lazy, so she doesn't put much creativity into it. Instead, she simply writes it literally. For example, when she reads `1+1`, she writes `one plus one`, `47 * 2` would turn into `forty seven times two`, and `56.2 / 7.4` would become `fifty six point two divided by seven point four`.

Write some code to help this lazy teacher out.

## Details

* Numbers may include a decimal point and a negative sign.
* Numbers should be written in the short scale. (i.e., `1,000,000,000` is `one billion`)
* Numbers can go up to 999,999,999,999,999,999 (`nine hundred ninety nine quadrillion...nine hundred ninety nine`).
* Groups of zeros must be left out. e.g. `1,000,000` is `one million` not `one million zero thousand zero hundred`.
* There can be arbitrarily many digits past the decimal point.
* Digits after the decimal point must be listed digit by digit. e.g. `12.34` is `twelve point three four` not `twelve point thirty four`.
* Two numbers are always separated by an operator.
* The valid operators are plus (`+`), minus (`-`), times (`*`), and divided by (`/`).
* There are no parentheses.
* Numbers such as `1234` may optionally include an `and` in their output, as in `one thousand two hundred *and* thirty four`.
* Commas and whitespace on the input may be ignored.

## Examples

Input: `24 + 65`
Output: `twenty four plus sixty five`

Input: `3.33333 - 0`
Output: `three point three three three three three minus zero`

Input: `3.6 * 18.18 / 999.0`
Output: `three point six times eighteen point one eight divided by nine hundred ninety nine point zero`

Input: `1-1`
Output: `one minus one`

Input: `1+-1`
Output: `one plus negative one`

Input: `1,000,000,000 + 0.2`
Output: `one billion plus zero point two`

Input: `123,000,456,789,012,345.6789`
Output: `one hundred twenty three quadrillion four hundred fifty six billion seven hundred eighty nine million twelve thousand three hundred forty five point six seven eight nine`

Input: `-4.3 * 7`
Output: `negative four point three times seven`

Input: `-1-1--1`
Output: `negative one minus one minus negative one`

# Answer
# JavaScript (ES6), ~~552~~ 532 bytes

This filthy monster comes straight from the depths of code-golfing hell.

Expects an input string without any whitespace.

```
S=>S[R='replace'](/[\d.,]+|./g,s=>1/s[0]?a(+s[S=0]&&14)+s[R](/(\D?)(\d+)/g,(_,s,n)=>s>','?' point'+n[R](/./g,a):j--*n?(u=a(n%10||14),n>99?a(n[0])+' hundred':'')+((n%=100)<13?a(n||14):n<20?(a(n)||u)+'teen':(a(n/10+18)||a(n/10))+'ty'+u)+a(j+27)+(j>1?'illion':''):'',j=s.split`,`.length):a(S='+-*/'.indexOf(s=='-'&&S||s)+34),a=n=>(s='zero0one0two0three0four0five0six0seven0eight0nine0ten0eleven0twelve0thir00fif000eigh00twen0thir0for0fif000eigh00thousand0m0b0tr0quadr0negative0plus0minus0times0divided by'.split`0`[n|0])&&' '+s).trim()

```

Try it online!
> 15 votes

# Answer
# Perl 6, ~~434 401 387~~ 359 bytes

```
{~S:g/\d+/{n($//100+64184)x($/>100),$/%100>19&&(n($//10%10+64175),n($!=$/%10)x?$!)||n($/%100+7679),[$,"thousand",|(<m b tr quadr>X~"illion")][+$/.postmatch.words[0].comb(',')]if +$/} /.trans("+,-/*"=><<plus''minus"divided by"times>>).words}o{S:g/\.(\d)+/ point {$0>>.&n}/}o{S:g/[\s|^]0/ zero/}o{S:g/\-(\d)/negative $0/}
my&n=(*+1632+|0).uniname.lc.words[2..*]

```

Try it online!

Definitely room for improvement here. I say that, but I keep noticing edge cases I haven't handled `:(`. Assumes that the input has operators separated by whitespace and the negative of a number isn't separated.

### Explanation:

```
my&n=(*+1632+|0).uniname.lc.words[2..*]  # Define a helper function
           # This gets the unicode name, e.g ARABIC-INDIC DIGIT ZERO
           #                              or AEGEAN NUMBER ONE HUNDRED
           # And returns the 3rd word onwards in lowercase e.g. 'zero' or 'one hundred'
{S:g/\-(\d)/negative $0/}  # Turn dashes before numbers to negative
{S:g/[\s|^]0/ zero/}       # Handle zeros
{S:g/\.(\d)+/ point {$0>>.&n}/}  # Replace decimals
{~S:g/\d+/        # Replace series of numbers with
    n($//100+64184)x($/>100)  # The hundreds if the num is bigger than 100
    $/%100>19&&               # If the number is bigger than 19
      (
      n($//10%10+64175),         # The tens number
      n($!=$/%10)x?$!            # And the singles number (if it's not zero)
      )
    ||                        # Else
      n($/%100+7679)             # The name of the number below 20
    ,                      # Then
    [$,"thousand",|(<m b tr quadr>X~"illion")][   # Index into the list of postfixes
      +                         .comb(',')   # The number of commas
       $/.postmatch.words[0]  # in the rest of the number
  if +$/           # All if the number is not 0
.trans("+,-/*"=><<plus''minus"divided by"times>>)  # Translate operators
                                                   # And remove commas
.words}     # And remove all the excess spaces between words

```
> 6 votes

# Answer
# Ruby + Swift 4, ~~283~~ ~~279~~ 270 bytes

```
$_=gsub(/(?<=\d)-/,"minus ").gsub(/[*-\/]/,?.=>"point ",?-=>"negative ",?+=>"plus ",?*=>"times ",?/=>"divided by ").gsub(/(?<=^|[^t] )\d+|\d/){`echo "import Foundation
var f=NumberFormatter()
f.numberStyle = .spellOut
print(f.string(from:#$&)!)">.a
swift .a`.tr'-
',' '}

```

Try it online!

I must be mad to propose such a Frankenstein solution, but on one hand, it is very tempting to use Swift's built-in functionality for this task, and on the other hand, processing strings with Regexes in Swift looks to be a golfing catastrophe.

Therefore, I decided to do basic string processing in Ruby, but to spell out numbers, I store them in a Swift source file, run Swift in a shell command, and collect the output.

I turns out that Swift's "spellOut" number formatter does almost exactly what we need, except inserting unnecessary hyphens for two-digit numbers, as in `twenty-two`. In fact, even the floating point output in the format of `integer part point digit digit...` is good, but here comes the caveat - there is no infinite precision, and with large enough numbers or a lot of decimal digits, the results go wrong. Therefore, I had to separate the integer and fractional parts and to feed the fraction digit by digit.
> 5 votes

# Answer
# Clean, ~~766~~ ... 687 bytes

```
import StdEnv,Text
m=""
z="zero"
@ =digitToInt
r=reverse
l k=(!!)k o@
^s=l[s:split" ""one two three four five six seven eight nine"]
g s=l[m,m,"twen","thir",s,"fif","six","seven","eigh","nine"]
~['0':t]= ~t
~[a,b,c]= ^""a+" hundred "+ ~[b,c]
~[b,c]|b>'1'=g"for"b+"ty "+ ^""c|c>'2'=g"four"c+"teen"=["ten","eleven","twelve"]!!(@c)
~[c]= ^""c
~_=m
$[]=m
$[x:y]#(h,t)=span(\e=e>'/'||e==',')if(x<'1')y[x:y]
=trim(join" "((case x of'0'=[z];'-'=["negative",$h];'.'=["point":map(^z)h];_=(r[u+v\\u<-r(map~(split[',']h))&v<-[m," thousand":[" "+k+"illion"\\k<-["m","b","tr","quadr"]]]|u>m]))++[?t]))
?['-':t]="minus "+ $t
?['+':t]="plus "+ $t
?['/':t]="divided by "+ $t
?['*':t]="times "+ $t
?t= $t

```

Try it online!

Expects a string without whitespace.
> 4 votes

# Answer
# sfk, 853 bytes

```
xed -i
"_*_ [part1]_"
+xed
_+_plus_
_\*_times_
"_/_divided by_"
"_- _minus _"
"_-_negative _"
+xed
"_,[keep][19 chars of 0-9,]_quadr@ _"
"_,[keep][15 chars of 0-9,]_tr@ _"
"_,[keep][11 chars of 0-9,]_b@ _"
"_,[keep][digits],[digits],_b@ _"
"_,[keep][digits],_m@ _"
"_,_ thousand _"
+xed
"_ 000[chars]@__"
"_ 000__"
"_ 00[keep][digit]_ _"
"_ 0[keep][2 digits]_ @_"
"_ [digit][keep][2 digits]_[part2]hundred @_"
"_ [ortext] 0[digit]0_ @[part2]_"
"_ [keep][2 digits]_ @_"
"_@_illion _"
+xed
_@11_eleven_
_@12_twelve_
_@1[digit]_@[part2]teen_
_@1_ten_
_@4_forty_
_@[digit]_@[part2]ty_
+xed
_@2_twen_
_@3_thir_
_@4_four_
_@5_fif_
_@6_six_
_@7_seven_
_@8_eigh_
_@9_nine_
+xed
"_0_ zero _"
"_1_ one _"
"_2_ two _"
"_3_ three _"
"_4_ four _"
"_5_ five _"
"_6_ six _"
"_7_ seven _"
"_8_ eight _"
"_9_ nine _"
"_._ point _"
+xed
"_[white]_ _"
+xed
"_[lstart] __"

```

Try it online!

Requires operators and numbers be separated by at least one space character.
> 4 votes

# Answer
# Python 2, ~~790~~ 774 bytes

```
lambda T:B("([+/*-])",lambda m:dict(zip("+/*-",S("z"," plus z divided by z times z minus ")))[m.group(0)],B("([+/*-]|^)-",r"\1negative ",B("[^+/*-]+","{}",T))).format(*[J([g[int(S("\.",j)[0])]+S("z",B("y","illion","z thousandz myz byz tryz quadry"))[len(S(",",m))+~i]+(" point "+J(s[int(c)]for c in S("\.",j)[-1]))*("."in j)for i,j in E(S(",",m))if 0<float(j)+(m<"1")])for m in S("[+/*-]+",T)[T[0]=='-':]])
from re import*
E,S,B,P=enumerate,split,sub," ";J=P.join
s,e=S(P,"zero one two three four five six seven eight nine"),[B("urty","rty",j)for i,j in E(c+d for d in S(P,"teen ty")for c in S(P,"twen thir four fif six seven eigh nine"))]
g=s+S(P,"ten eleven twelve")+e[1:8]+[a+(P+b)*(i>0)for a in e[8:]for i,b in E(s)]
g=[(j+" hundred ")*(i>0)+k for i,j in E(s)for k in g]

```

Try it online!

So many bad practices. This almost hurt to write....

Expects a non-unicode string with no whitespace as input.

**Explanation:**

```
# import all functions from re (python regex library)
from re import*

# rename some repeatedly-used functions/variables for reduced bytecount
E,S,B,P=enumerate,split,sub," ";J=P.join

# list the names of 0-9
s=S(P,"zero one two three four five six seven eight nine")
# generate "twenteen" through nineteen and twenty though ninety, changing "fourty" to forty
# using enumerate (E) even though i is not required b/c it's shorter than range(len(x))
# using re.split (S) instead of string.split since it's shorter
e=[B("urty","rty",j)for i,j in E(c+d for d in S(P,"teen ty")for c in S(P,"twen thir four fif six seven eigh nine"))]
# generate 0-999
# 0-9
g=s+
   # 10, 11, 12
   +S(P,"ten eleven twelve")+
                            # remove "twenteen", 13-19
                            +e[1:8]+
                                   # tens' place + ones' place, if ones' place is not zero
                                   +[a+(P+b)*(i>0)                               ]
                                                   # for each tens' place in 20-90
                                                   for a in e[8:]
                                                                  # for each index, value in ones' places 0-9
                                                                  for i,b in E(s)

# hundreds' place if at least 100, plus tens' and ones' place (already calculated and stored in g from before)
g=[(j+" hundred ")*(i>0)+k                          ]
                           # (s) stores names for 0-9, need index to avoid "zero hundred"
                           for i,j in E(s)
                                          # for each hundred, iterate over all values (0-99) already in g
                                          for k in g

# actual function to call. uses previously declared global variable g.
def f(T):
    # gets the numbers in the supplied string (T) by splitting (T) on any operator character
    # remove first item if blank (only happens when staring with a - for negative numbers)
    n=S("[+/*-]+",T)[T[0]=='-':]

    # triply-nested set of re.subs to convert (T) to a sting of where the operators are replaced by their names and numbers are replaced by "{}"
    # EX: "-1-1--1" -> "-{}-{}--{}" -> "negative {}-{}-negative {}" -> "negative {} minus {} minus negative {}"
    # this sub happens last
    # re.sub (B) any operator, with the operators in a group "()" so that they return in match.group
    T=B("([+/*-])",                                                                                )
                  # an anonymous function to accept match objects (m) from re.sub's search.
                  ,lambda m:
                            # create a dictionary from the combination of operators and their names
                            # like {"+":" plus ",...}
                            # operator names are surrounded by spaces since number names are NOT
                            dict(zip("+/*-",S("z"," plus z divided by z times z minus ")))
                                                                                # from the constructed dictionary, select the operator matched by re.sub's search and return it for replacement
                                                                                [m.group(0)],
                                                                                # this substitution is second
                                                                                # re.sub (B) any operator followed by a minus (-), OR a minus at the beginning of the string
                                                                                # operators/start are grouped, trailing minus is not
                                                                                ,B("([+/*-]|^)-",                                    )
                                                                                # replace match with the grouped items plus the word "negative"
                                                                                # EX: "-1-1--1" -> "-{}-{}--{}" -> "negative {}-{}-negative {}"
                                                                                ,r"\1negative ",
                                                                                # this substitution is done first
                                                                                # replace any sequence of NON-operators with "{}"
                                                                                # this removes numbers so the names can be inserted later
                                                                                # EX: "-1-1--1" -> "-{}-{}--{}"
                                                                                ,B("[^+/*-]+","{}",T))

    # technically the previous construction of (T) and (n) can be placed here to save 5 bytes but my poor eyes can't handle that.
    # insert constructed names back into original string.
    # EX: "-1-1--1" -> "negative {} minus {} minus negative {}" -> "negative one minus one minus negative one"
    print T.format(                                                                                )
                   # string.format needs items in array unpacked, or it will attempt to insert the string representation of the array itself
                   *[                                                                                ]
                     # for each number pulled from (T), generate names and join generated items back together with spaces
                     # EX: "1,456" -> ["1", "456"] -> ["one thousand", "four hundred fifty six"] -> "one thousand four hundred fifty six"
                     J(                                                                                )for m in n
                       # split j on periods (.) and take the first item
                       # convert that item into an integer and find the item at that index in g (0-999)
                       [g[int(S("\.",j)[0])]+                                                                                ]
                                            # insert prefix for millions +, split string on "z" (spaces must be preserved for proper separation)
                                            +S("z",B("y","illion","z thousandz myz byz tryz quadry"))
                                                                                # left is largest, so take the item at index (total # of groups - current place - 1)
                                                                                [len(S(",",m))+~i]+
                                                                                # if group had a period, split string on period and take last item
                                                                                # replace every character in group with number 0-9 name
                                                                                # join them with spaces and add back to rest of group
                                                                                +(" point "+J(s[int(c)]for c in S("\.",j)[-1]))*("."in j)
                                                                                # split number into groups by comma
                                                                                # EX: "123,456" -> ["123","456"]
                                                                                # only return item if j != 0 (avoids returning empty string which will result in too many joined spaces)
                                                                                # OR if m == 0 (avoids not returning anything when should return "zero")
                                                                                for i,j in E(S(",",m))if 0

```

I reduced by about 150 bytes while writing the explanation. Let it never be said that commenting/reviewing your code isn't helpful!
> 2 votes

# Answer
# 05AB1E, ~~315~~ ~~295~~ ~~282~~ 276 bytes

```
"+-*/"DˆS¡εDõQi'¢…ë'.¡VYнD_i\'¡×ðë',¡DgUε0›i.•6b©•ð“†ìˆÈŒšï¿Ÿ¯¥Š“©'tKJ#'…§«…€µ‚•„í#®#«…—¿áÓÁÏ#«ìD9£©.•4º»Ÿć'Rþн•ŽH$S£“Œšï¿Ÿ¯¥Š“'tK#«„ty«sõšâðý«õšD®'°¡ðì«sâðý«yèð.•cG3₅¦„¥F•8ô'¾ß«…¡›‡È±°#«õªRXN-<èJëõ}}ðý}Yg<i®'¡×šYθSè'…®šðý}}J}s¯`Ãε“‰´Øè„Æºß“#¤… by«¸s¨ì¯`ykè}.ιðý„  ð:„¢…Øè'¢…:

```

Takes input without any spaces.

Try it online or verify all test cases.

**Explanation:**

```
"+-*/"                    # Push string "+-*/"
Dˆ                        # Duplicate it, pop the copy, and push it to the global array
S¡                        # Split the input by any "+", "-", "*", or "/"
ε                         # Map each number to:
 DõQi                     #  If the item is empty (happens for negative numbers)
     '¢…                 '#   Push string "negative"
 ë                        #  Else:
  '.¡                    '#   Split by "."
  VY                      #   Store it in variable `Y`
  н                       #   Take the first number (the integer part)
  D                       #   Duplicate this integer part
  _i                      #   If the integer part is exactly 0:
    \                     #    Discard the duplicated integer part
    '¡×                  '#    Push string "zero"
    ð                     #    Push a space " "
  ë                       #   Else:
   ',¡                   '#    Split by ","
   DgU                    #    Pop and store the amount of items in variable `X`
      ε                   #    Map each part to:
       0›i                #     If it's larger than 0:
          .•6b©•          #      Push string "thir"
          ð               #      Push a space " "
          “†ìˆÈŒšï¿Ÿ¯¥Š“  #      Push string "four five six seven eight nine"
          ©               #      Store it in the register (without popping)
           'tK           '#      Remove all "t" (so "eight" becomes "eigh")
          J               #      Join it together with the "thir" and space
          #               #      Split by spaces
          '…§            '#      Push string "teen"
             «            #      And append it to every string in the list
                          #      (We now have ["thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"])
          …€µ‚•„í         #      Push string "one two three"
                 #        #      Split by spaces
          ®               #      Push the string from the register ("four" through "nine")
           #«             #      Split by spaces, and merge both lists together
          …—¿áÓÁÏ         #      Push string "ten eleven twelve"
                 #«       #      Split by spaces, and also merge both lists together
          ì               #      Prepend "one" through "twelve" before "thirteen" through "nineteen"
          D9£             #      Duplicate it, and take the first nine ("one" through "nine")
             ©            #      Store it in the register (without popping)
          .•4º»Ÿć'Rþн•   '#      Push string "twenthirforfif"
          ŽH$             #      Push integer 4433
             S            #      Split to digits: [4,4,3,3]
              £           #      And split the to parts of that size: ["twen","thir","for","fif"]
          “Œšï¿Ÿ¯¥Š“      #      Push string "six seven eight nine"
                    'tK  '#      Remove all "t" (so "eight" becomes "eigh")
                       #« #      Split by spaces, and merge both lists together
          „ty             #      Push string "ty"
             «            #      And append it to every string in the list
                          #      (We now have ["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"])
          s               #      Swap so the list "one" through "nine" is at the top again
           õš             #      Prepend an empty string to that list
             â            #      Create every possible pair of "one" through "nine" with "twenty" through "ninety"
              ðý          #      Join each pair with a space delimiter
          «               #      Merge the "twenty" through "ninety nine" list with "one" through "nineteen"
           õš             #      Prepend an empty string to that list
          D               #      Duplicate the entire list
          ®               #      Push the string from the register ("one" through "nine")
          '°¡            '#      Push string "hundred"
             ðì           #      Prepend it with a space " "
               «          #      Append it to every string in the list
                          #      (We now have ["one hundred","two hundred",...,"nine hundred"])
          s               #      Swap the two lists
           â              #      Create every possible pair of "one hundred" through "nine hundred" with "" through "ninety nine"
            ðý            #      Join each pair with a space delimiter
              «           #      Merge the "one" through "ninety nine" with "one hundred " through "nine hundred ninety nine"
                          #      (We now have ["","one",...,"nine hundred ninety nine"])
          y               #      Get the current number of the map
           è              #      And index it into this list
          ð               #      Push a space " "
          .•cG3₅¦„¥F•     #      Push string "quadrilltrill"
                     8ô   #      Split into pieces of size 8: ["quadrill","trill"]
          '¾ß            '#      Push string "ion"
             «            #      Append it to every string in the list
          …¡›‡È±°         #      Push string "billion million thousand"
                 #        #      Split by spaces
                  «       #      And merge both lists together
          õª              #      Append an empty string
            R             #      Reverse the list
                          #      (We now have ["","thousand","million","billion","trillion","quadrillion"])
          X               #      Push variable `X`
           N-             #      Subtract the map-index from it
             <            #      Subtract an additional 1
              è           #      And index it into the list
          J               #      Join the stack together
       ë                  #     Else:
        õ                 #      Push an empty string ""
       }                  #     Close the if-else
      }                   #    Close the map
      ðý                  #    Join the mapped values with space delimiter
  }                       #   Close the if-else
  Y                       #   Push variable `Y`
  g<i                     #   If its length is exactly 2:
     ®                    #    Push the string from the register ("one" through "nine")
     '¡×                 '#    Push "zero"
        š                 #    Prepend it to the list
      Yθ                  #    Push variable `Y` again, and leave the second number (the decimal part)
        S                 #    Split it to digits
         è                #    And index each into the list
      '…®                '#    Push string "point"
         š                #    Prepend it in front of that list
      ðý                  #    Join the list with space delimiter
  }                       #   Close the if
 }                        #  Close the if-else
 J                        #  Join the stack together
}                         # Close the map
s                         # Swap to take the (implicit) input again
¯`                        # Push the global array, and dump it's content (string "+-*/")
  Ã                       # Only keep all "+", "-", "*", and "/", and remove everything else
ε                         # Map each to:
 “‰´Øè„Æºß“               #  Push string "plus minus times divided"
           #              #  Split by spaces
 ¤                        #  Take the last item (without popping the list)
  … by«                   #  Append it with string " by"
       ¸                  #  Wrap it to a list: ["divided by"]
 s                        #  Swap to take the list again
  ¨                       #  Remove the last item
   ì                      #  Prepend it in front of the list: ["plus","minus","times","divided by"]
 ¯`                       # Push the global array, and dump it's content (string "+-*/")
   yk                     #  Push the index in this string for the current map-value `y`
     è                    #  And use that index to index into the string-list
}                         # Close the map
.ι                        # Interweave the list of numbers and list of operators
  ðý                      # Join everything with space delimiter
„  ð:                     # Replace every two spaces for a single space
„¢…Øè'¢…:                '# And replace every "negative minus" with "negative"
                          # (and output the result implicitly)

```

See this 05AB1E tip of mine (sections *How to use the dictionary?*, *How to compress strings not part of the dictionary?*, and *How to compress large integers?*) to understand why:

* (*How to use the dictionary?*) -- `'¢…` is `"negative"`; `'¡×` is `"zero"`; `“†ìˆÈŒšï¿Ÿ¯¥Š“` is `"four five six seven eight nine"`; `'…§` is `"teen"`; `…€µ‚•„í` is `"one two three"`; `…—¿áÓÁÏ` is `"ten eleven twelve"`; `'°¡` is `"hundred"`; `'¾ß` is `"ion"`; `…¡›‡È±°` is `"billion million thousand"`; `'…®` is `"point"`; and `“‰´Øè„Æºß“` is `"plus minus times divided"`.
* (*How to compress strings not part of the dictionary?*) -- `.•6b©•` is `"thir"`; `.•4º»Ÿć'Rþн•` is `"twenthirforfif"`; and `.•cG3₅¦„¥F•` is `"quadrilltrill"`.
* (*How to compress large integers?*) -- `ŽH$` is `4433`.
> 1 votes

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


title: Rosencrantz and Guildenstern are Code

text:
# Question
Title: Rosencrantz and Guildenstern are Code
In the absurdist play *Rosencrantz and Guildenstern are Dead*, the two main characters **Rosencrantz** and **Guildenstern**(or are they?) are always mixing up which of them is who—or sometimes which of their own body parts is which—because of a perceived lack of individual identity. Wouldn't it be absurd if they even shuffled around their names?

Your task it to write a function which takes in a string of an **even** length(and by design, a multiple of 4) that is greater than 7 characters, split it, and shuffle it.

*The splitting shall be as follows*: the string will be of format `"abscd"`, with s acting as a seperator character. The first section and the separator, `abs` will be the first half of the string, whereas the second half will be `cd`

The length of `a` will be `(string length / 4) - 1`

The length of `b` will be `(string length / 4)`

The length of `s` will be `1`

The length of `c` will be `(string length / 4) + 1`

The length of `d` will be `(string length / 4) - 1`

This may be really confusing, so let me show you with some examples

```
("a" + "bb" + "s" + "ccc" + "d").length //8
  1     2      1      3      1
|-------4--------|  |----4-----| <--- (4 is half of 8)

("rosen" + "crantz" + "&" + "guilden" + "stern").length  //24
    5         6        1        7          5

("foo" + "barr" + "?" + "barry" + "foo").length
   3       4       1      5         3

```

**Finally:**

You then shuffle the parts around, outputting `adscb`

ex. `"rosencrantz&guildenstern" --> "rosenstern&guildencrantz"`

`"foobarr?barryfoo" --> "foofoo?barrybarr"`

# Rulez:

1. Standard Loopholes are prohibited
2. Acceptable answers: a function which takes input through one input string and returns one output string
3. If the input string doesn't match the requirements provided above, your code MUST error out(doesn't matter what kind of `Exception` or `Error`)
4. This is `code-golf`, so the shortest(valid)answer (in each language) wins!
5. **Bonus points for a one-liner** :-) (Not really tho, just cool points)

# Answer
# K (oK), ~~35~~ ~~34~~ 33 bytes

```
{$[8>#x;.;<x!4!-&4#-1 0 2+-4!#x]}

```

Try it online!

# Without input validation (for ngn's bounty), ~~25~~ ~~24~~ 23 bytes

```
{<x!4!-&4#-1 0 2+-4!#x}

```

Try it online!

Quickly learned a bit of K and, looking at the list of verbs, I thought an alternative approach (*not* using cut) could work here. And it worked perfectly.

### How it works

```
{<x!4!-&4#-1 0 2+-4!#x}
                 -4!#x    Length divided by four (floor division)
        4#-1 0 2+         Generate lengths (x/4-1, x/4, x/4+2, x/4-1)
       &                  Generate that many 0, 1, 2, 3's
    4!-                   Negate and modulo 4; effectively swap 1 and 3
 <x!                      Sort the original string by above

{$[8>#x;.; <code> ]}  Input validation
 $[8>#x           ]   If the length is less than 8
        .             Dynamically generate an error
           <code>     Otherwise, run the main code

```
> 11 votes

# Answer
# Python 3, 103 102 101 97 88 86 84 bytes

```
def f(s):l=len(s);l//=4*(l%4<1<l/4);return s[:l-1]+s[1-l:]+s[2*l-1:1-l]+s[l-1:2*l-1]

```

Try it online!

Not really a one-liner, but `;` is one less byte per line than linebreak and indent.

Throws `ZeroDivisionError` if input string length is less than 8 or not an integer multiple of 4.

Also works in Python 2.

-4 bytes thanks to Jo King

-9 bytes thanks to ovs

-2 bytes thanks to Jonathan Frech

-2 bytes thanks to Bubbler
> 3 votes

# Answer
# Perl 6, ~~60~~ 58 bytes

*-2 bytes thanks to Jo King*

```
{[~] .rotor($_/4 X-1,0,+^-$_+>2,-1,1)[0,4,2,3,1;*]}o*.comb

```

Try it online!

Throws "Rotorizing sublist length is out of range" in case of error.

### Explanation

```
{               # Anonymous block
 [~]            # Join
   .rotor(      # Split into sublists of specific length
     $_/4 X-    # Subtract from len/4
     1,
     0,
     +^-$_+>2,  # (len-1)>>2
                #   subtraction yields 1 if len is multiple of 4
                #   otherwise a value less than 1 causing an error
     -1,
     1)
   [0,4,2,3,1;*]  # Rearrange sublists and take inner elements
}o*.comb          # Split into characters and feed into block

```
> 3 votes

# Answer
# , ~~36~~ 35 bytes

```
5;@A.](<;.2~;)1<@{."+~1 0 _2 1-4%~#

```

Try it online!

-1 byte by `{.` \+ negative lengths & `;.2` which cuts on ones as "ending" markers instead.

## Original answer, 36 bytes

```
5;@A.](<;.1~;)1<@{."+~_1 0 2 _1+4%~#

```

Try it online!

ngn mentioned "cut" on a comment to an earlier K answer, and it made me try J which has the same "cut" (I have no idea how K works).

### How it works

```
5;@A.](<;.1~;)1<@{."+~_1 0 2 _1+4%~#  Monadic train.
                                4%~#  Length divided by four
                      _1 0 2 _1+      Generate the four segment lengths
              1<@{."+~  Generate [1 0 0...] boxed arrays of those lengths
      (     ;)          Raze; unbox and concatenate
     ] <;.1~            Cut the input string on ones as starting marker, then box each
5  A.  Rearrange the boxes in the order 0 3 2 1
 ;@    Raze again

```

Note that this function automatically handles invalid inputs:

* If the input length is not a multiple of four, `{.` throws `domain error` since its length argument has to be integers.
* If the input length is 4, the cut produces only two segments, and `5 A.` throws `index error`.
* If the input length is 0, the two arguments to cut don't have the same length, so `length error` is thrown.
> 3 votes

# Answer
# K (ngn/k), 120 113 103 99 95 bytes

```
{$[(r>7)&0=4!r:#:x;{g:(s:*|(y*2)#x)\x;((y-1)#*g),((-y-1)#*|g),s,((y+1)#*|g),(-y)#*g}[x;r%4];l]}

```

Hopefully can be golfed down more, included an extra function for testing if string length is divisible by four, outputs error with reference to undeclared variable if input is invalid

EDIT: Missed condition on length greater than 7, included

EDIT: Combined into one function, removed redundant variable declarations

Try it online!
> 2 votes

# Answer
# Perl 6, 78 bytes

```
*.comb[0..*/4-2,3* */4+1..*,*/2-1/(*>7)..3* */4,*/4-1/(*%%4)..*/2-2].flat.join

```

Try it online!

Anonymous code block that takes a string and returns the modified string if valid, else returns a division by zero error. I know I can modify an array directly, so I could swap the two sections of the string, but I can't quite figure it out.
> 2 votes

# Answer
# Ruby, 64 bytes

```
->s{a=s.size/4;s[1-a,a],s[a-1,a]=s[a-1,a],s[1-a,a];s[a*4]?1/0:s}

```

Try it online!
> 2 votes

# Answer
# C (gcc) with `-Dx=memcpy` and `-DL=(l-1)`, 154 158 160 bytes

Returns NULL if the input string length is not divisible by 4 or shorter than 8 characters.

Thanks to Rogem and Jonathan Frech for the suggestions.

EDIT: Moved preprocessor defines to the command line and made the string dynamically-allocated to strictly conform with the puzzle.

```
f(s,t,l)char*s,*t;{l=strlen(s);l%4|l<8?t=0:(t=malloc(l+1),l/=4,x(t,s,L),x(t+L,s+3*l+1,L),x(t+2*L,s+L+l,l+2),x(t+3*l,s+L,l),t[4*l]=0);l=t;}//-Dx=memcpy -DL=(l-1)

```

Try it online!
> 1 votes

# Answer
# Retina 0.8.2, 58 or 73 or 83 or 93 bytes

```
((((.)))*?)(.(?<-2>.)+)(...(?<-3>.)+)((?<-4>.)+)$
$1$7$6$5

```

Try it online! Explanation:

```
((((.)))*?)

```

Capture `a` in `$1`, and make it as short as possible `*?`. `$#2`, `$#3` and `$#4` end up as the length of `a`.

```
(.(?<-2>.)+)

```

Capture `b` in `$4`. The `(?<-2>.)+` captures up to the length of `a`, while the other `.` adds 1 to its length as required.

```
(...(?<-3>.)+)

```

Capture `s` and `c` in `$6`. Their combined length is three more than the length of `a`.

```
((?<-4>.)+)

```

Capture `d` in `$7`. Its length is no more than the length of `a`.

```
$

```

We made `a` as short as possible, but we still want to reach the end of the input.

```
$1$7$6$5

```

Exchange `b` and `d`.

The above stage does not validate its input. As Retina has no run-time errors, there are a number of options for input validation:

```
G`^(....){2,}$

```

Outputs nothing if the length is less than 8 or not a multiple of 4. (+15 bytes)

```
^(?!(....){2,}$).*
Error

```

Outputs `Error` if the length is less than 8 or not a multiple of 4. (+25 bytes)

```
+`^(....)*..?.?$|^(....)?$
.....$1

```

Hangs if the length is less than 8 or not a multiple of 4. (+35 bytes)
> 1 votes

# Answer
# JavaScript (ES6), ~~97~~ 89 bytes

*Saved 8 bytes thanks to @l4m2*

```
s=>(l=s.length/4)<2||l%1?Z:s.replace(eval(`/(.{${l}})(.{${l+2}})(.{${l-1}})$/`),'$3$2$1')

```

Try it online!
> 1 votes

# Answer
# Jelly, 28 bytes

```
L7»4ḍİ×L:4;;ĖÄƲFÄœṖ⁸⁽%[D¤ị$F

```

(If a full program is allowed we can remove the trailing `F`)
If the length is less than 8 or not divisible by four a `ValueError` is raised during integer division of `inf` (a float) by `4` -- the division yields `NaN` (also a float) which then cannot be cast to an `int`.

**Try it online!**

### How?

```
L7»4ḍİ×L:4;;ĖÄƲFÄœṖ⁸⁽%[D¤ị$F - Link: list of characters
L                            - length
 7                           - literal seven
  »                          - maximum (of length & 7)
   4ḍ                        - divisible by four? (yields 1 for good inputs; 0 otherwise)
     İ                       - inverse (1 yields 1; 0 yields inf)
      ×L                     - multiply by length (length or inf)
        :4                   - integer divide by 4 (errors given inf)
              Ʋ              - last four links as a monad (f(x)):
          ;                  -   concatenate -> [x,x]
            Ė                -   enumerate -> [1,x]
           ;                 -   concatenate -> [x,x,[1,x]]
             Ä               -   cumulative sum (vectorises at depth 1) -> [x,x,[1,1+x]]
               F             - flatten -> [x,x,1,1+x]
                Ä            - cumulative sum -> [x,2x,2x+1,3x+2]
                   ⁸         - chain's left argument (the input)
                 œṖ          - partition at indices (chops up as per requirements)
                          $  - last two links as a monad (f(z)):
                        ¤    -   nilad followed by link(s) as a nilad:
                    ⁽%[      -     10342
                       D     -     decimal digits -> [1,0,3,4,2]
                         ị   -   index into z (rearranges the pieces as per requirements)
                           F - flatten (back to a list of characters)

```
> 1 votes

# Answer
# Jelly, 25 bytes

```
L:4’+“¡¢¢£¡‘Ṡ3¦ÄṬk⁸Ṛ2,5¦Ẏ

```

Try it online!

The  can be removed to make this into a full program.
> 1 votes

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

```
s=>(g=s.substr.bind(s))(0,l=s.length/4-1)+g(-l)+g(l-~l,l+3)+g(l,l+1,l<1==l%1||Z)

```

Try it online!

# JavaScript (Node.js), 84 bytes

```
s=>(g=(a,b)=>s.substr(a,b))(0,l=s.length/4-1)+g(-l)+g(l-~l,l+3)+g(l,l+1,l<1==l%1||Z)

```

Try it online!

# JavaScript (Node.js), 87 bytes

```
s=>(l=s.length/4)<2||l%1?Z:(g=(a,b)=>s.substr(a,b))(0,l-1)+g(1-l)+g(l+l-1,l+2)+g(l-1,l)

```

Try it online!

Shorter than RegExp
> 1 votes

# Answer
# Java 8, 135 bytes

```
s->{int l=s.length();l=l>7&l%4<1?l/4:l/0;return s.substring(0,l-1)+s.substring(3*l+1)+s.substring(2*l-1,3*l+1)+s.substring(l-1,2*l-1);}

```

Throws `ArithmeticException` (divides by zero) if the input string does not match requirements. Try it online here.

Ungolfed:

```
s -> { // lambda function taking a String argument and returning a String
    int l = s.length(); // take the length of the input ...
    l = l > 7 &         // ... if it's  greater than 7 and ...
        l % 4 < 1       // ... a multiple of 4 ...
      ? l / 4           // ... divide by 4; otherwise ...
      : l / 0;          // ... error out (division by zero throws ArithmeticException)
    return // concatenate and return:
           s.substring(0, l - 1)             // a
         + s.substring(3 * l + 1)            // d
         + s.substring(2 * l - 1, 3 * l + 1) // sc
         + s.substring(l - 1, 2 * l - 1);    // b
}

```
> 0 votes

# Answer
# C (gcc), 129 bytes

Returns by modification. Compile with:

```
-Df(s)=({char t[l=strlen(s)];l%4|l<8?0:(l/=4,x(t,s+l*2-1,l-~l),x(x(x(s+l*3,s+l-1,l)-l-2,t,l+2)-l+1,t+l+2,l-1),s);}) -Dx=memcpy

```

Source file:

```
l;

```

Try it online!

## Degolf

```
-Df(s)=({ // Function-like macro f. Takes a char* as a parameter.
          // Return value is a pointer to s if successful, and to NULL if string was invalid.
     char t[l=strlen(s)]; // Allocate a local temp string.
     l%4|l<8?0: // Detect invalid strings. Return 0 (NULL) on invalid string.
         (l/=4, // We're only really concerned with floor(len/4), and this will yield that.
             memcpy(t,s+l*2-1,l-~l), // Copy the second half of chars to the temp storage.
             memcpy( // Because memcpy returns the address of the destination, we can chain
                     // the calls to save quite a few bytes, even after x->memcpy substitution.
                 memcpy(memcpy(s+l*3,s+l-1,l) // Next, copy the second quarter to the end.
                     -l-2,t,l+2) // After that, we copy back the third quarter to its place.
                          -l+1,t+l+2,l-1) // Finally, copy the fourth quarter to where the second
                                          // quarter was.
                      ,s);}) // And return the pointer.

```
> 0 votes

---
Tags: code-golf
---


title: ASCII art H trees

text:
# Question
Title: ASCII art H trees
An H tree is a fractal tree structure that starts with a line. In each iteration, T branches are added to all endpoints. In this challenge, you have to create an ASCII representation of *every second* H tree level.

The **first level** simply contains three hyphen-minus characters:

```
---

```

The next levels are constructed recursively:

* Create a 2x2 matrix of copies from the previous level, separated by three spaces or lines.
* Connect the centers of the copies with ASCII art lines in the form of an H. Use `-` for horizontal lines, `|` for vertical lines, and `+` whenever lines meet each other.

### Second level

```
-+-   -+-
 |     |
 +-----+
 |     |
-+-   -+-

```

### Third level

```
-+-   -+-   -+-   -+-
 |     |     |     |
 +--+--+     +--+--+
 |  |  |     |  |  |
-+- | -+-   -+- | -+-
    |           |
    +-----------+
    |           |
-+- | -+-   -+- | -+-
 |  |  |     |  |  |
 +--+--+     +--+--+
 |     |     |     |
-+-   -+-   -+-   -+-

```

## Rules

* Input is an integer representing the level of the ASCII art H tree as described above (*not* the actual H tree level), either zero- or one-indexed.
* Output is flexible. For example, you can print the result or return a newline-separated string, a list of strings for each line, or a 2D array of characters.
* You must use `-`, `|`, `+` and space characters.
* Trailing space and up to three trailing white-space lines are allowed.

This is code golf. The shortest answer in bytes wins.

# Answer
> 7 votes
# Canvas, ~~20~~ 19 bytes

```
ø⁸«╵［↷Ｌ⇵；ｌ⇵└┌├-×╋‼│

```

Try it here!

Explanation:

```
ø                    push an empty canvas
 ⁸«╵[              repeat input*2 + 1 times
     ↷               rotate clockwise
      L⇵             ceil(width/2)
        ;l⇵          ceil(height/2); leaves stack as [ ⌈½w⌉, canvas, ⌈½h⌉ ]
           └┌        reorder stack to [ canvas, ⌈½w⌉, ⌈½h⌉, ⌈½w⌉ ]
             ├       add 2 to the top ⌈w÷2⌉
              -×     "-" * (2 + ⌈w÷2⌉)
                ╋    in the canvas, at (⌈w÷2⌉; ⌈h÷2⌉) insert the dashes
                 ‼   normalize the canvas (the 0th iteration inserts at (0; 0) breaking things)
                  │  and palindromize horizontally

```

# Answer
> 7 votes
# Charcoal, 22 bytes

```
Ｐ-²ＦＮＦ²«⟲Ｔ²+×⁺²κＸ²ι←‖Ｏ

```

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

```
Ｐ-²

```

Print the initial three `-`s, leaving the cursor in the middle.

```
ＦＮ

```

Repeat for the number of times given.

```
Ｆ²«

```

Repeat twice for each `H`. Each loop creates a slightly bigger `H` from the previous loop, but we only want alternate `H`s.

```
⟲Ｔ²

```

Rotate the figure.

```
+×⁺²κＸ²ι←

```

Draw half of the next line.

```
‖Ｏ

```

Reflect to complete the step.

The result at each iteration is as follows:

```
---

|   |
+---+
|   |

-+-   -+-
 |     |
 +-----+
 |     |
-+-   -+-

|   |   |   |
+-+-+   +-+-+
| | |   | | |
  |       |
  +-------+
  |       |
| | |   | | |
+-+-+   +-+-+
|   |   |   |

-+-   -+-   -+-   -+-
 |     |     |     |
 +--+--+     +--+--+
 |  |  |     |  |  |
-+- | -+-   -+- | -+-
    |           |
    +-----------+
    |           |
-+- | -+-   -+- | -+-
 |  |  |     |  |  |
 +--+--+     +--+--+
 |     |     |     |
-+-   -+-   -+-   -+-

```

# Answer
> 1 votes
# Python 2, 227 bytes

```
L=len
def f(n):
 if n==1:return[['-']*3]
 m=[l+[' ']*3+l for l in f(n-1)];w=L(m[0]);y=L(m)/2;x=w/4-1;m=map(list,m+[' '*w,' '*x+'-'*(w-x-x)+' '*x,' '*w]+m)
 for i in range(y,L(m)-y):m[i][x]=m[i][w+~x]='|+'[m[i][x]>' ']
 return m

```

Try it online!

# Answer
> 1 votes
# Perl 6, 118 bytes

```
{map ->\y{map {' |-+'.comb[:2[map {$^b%%1*$b&&6>=$^a/($b+&-$b)%8>=2},$^x/¾,y/2,y,$x/3-$_]]},2..^$_*6},2..^$_*4}o*R**2

```

Try it online!

0-indexed. Returns a 2D array of characters. The basic idea is that the expression

```
b = y & -y   // Isolate lowest one bit
b <= x % (4*b) <= 3*b

```

generates the pattern

```
--- --- --- ---
 -----   -----
--- --- --- ---
   ---------
--- --- --- ---
 -----   -----
--- --- --- ---

```

### Explanation

```
{ ... }o*R**2  # Feed $_=2**$n into block
map ->\y{ ... },2..^$_*4  # Map y=2..2**n*4-1
map { ... },2..^$_*6      # Map $x=2..2**n*6-1
' |-+'.comb[:2[ ... ]]    # Choose char depending on base-2 number from two Bools
map { ... }  # Map coordinates to Bool
  # Horizontal lines
  ,$^x/¾  # Modulo 8*¾=6
  ,y/2    # Skip every second row
  # Vertical lines
  ,y      # Modulo 8
  ,$x/3   # Skip every third column
   -$_    # Empty middle column
# Map using expression
$^b%%1*$b&&  # Return 0 if $b is zero or has fractional part
6>=$^a/($b+&-$b)%8>=2  # Pattern with modulo 8

```

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


title: Number in Number-squared

text:
# Question
Title: Number in Number-squared
Consider a sequence of natural numbers for which N appears as a substring in N^2. A018834

Output the `n`th element of this sequence.

### Rules

Program takes only `n` as input and outputs just one number - `N`.

The sequence can be 0-indexed or 1-indexed.

```
Sequence: 1 5 6 10 25 50 60 76 100 250 376 500 600 625 760 ...
Squares:  1 25 36 100 625 2500 3600 5776 10000 62500 141376 250000 360000 390625 577600 ...

```

This is **code-golf** so shortest code wins.

# Answer
# Perl 6, ~~33~~ 31 bytes

*-2 bytes thanks to nwellnhof*

```
{(grep {$^a²~~/$a/},1..*)[$_]}

```

Try it online!

### Explanation:

```
{                            }  # Anonymous code block that returns
 (                      )[$_]   # The nth index of
  grep {          },1..*        # Filtering from the natural numbers
        $^a²                    # If the square of the number
            ~~/$a/              # Contains the number

```
> 4 votes

# Answer
# 05AB1E, 6 bytes

1-indexed

```
µNNnNå

```

Try it online!

**Explanation**

```
µ         # loop over increasing N until counter equals input
 N        # push N (for the output)
  Nn      # push N^2
    N     # push N
     å    # push N in N^2
          # if true, increase counter

```
> 4 votes

# Answer
# JavaScript (ES6), 43 bytes

```
f=(n,k=0)=>n?f(n-!!(++k*k+'').match(k),k):k

```

Try it online!

---

# Non-recursive version, 47 bytes

```
n=>eval("for(k=0;n-=!!(++k*k+'').match(k););k")

```

Try it online!
> 3 votes

# Answer
# MathGolf, 8 bytes (works for any input in theory, but only for `n<10` in practice)

```
úrgÉ²ï╧§

```

Try it online!

## Alternative (works for `n<49` in practice and theory)

```
►rgÉ²ï╧§

```

The only difference is that instead of creating a list with `10^(input)` values, I create a list with `10^6` items. This takes a while to run, so you could swap the first byte to any other 1-byte literal to test it out.

## Explanation

```
ú          pop(a), push(10**a)
 r         range(0, n)
  g        filter array by...
   É       start block of length 3
    ²      pop a : push(a*a)
     ï     index of current loop
      ╧    pop a, b, a.contains(b)
           Block ends here
       §   get from array

```

The reason why this solution doesn't handle large input is that I noticed that the sequence grows less than exponentially, but more than any polynomial. That's why I used the `10**n` operator (I wanted to use `2**n` but it failed for input 1). That means that I create an extremely large array even for small inputs, just to filter out the vast majority of it, and then take one of the first elements. It's extremely wasteful, but I couldn't find another way to do it without increasing the byte count.
> 3 votes

# Answer
# Common Lisp, 95 bytes

```
(lambda(n)(do((i 0))((= n 0)i)(if(search(format()"~d"(incf i))(format()"~d"(* i i)))(decf n))))

```

Try it online!
> 3 votes

# Answer
# Japt, ~~12~~ 11 bytes

```
@aJ±X²søY}f

```

Try it

```
È²søY «U´}a

```

Try it
> 2 votes

# Answer
# Clean, 83 bytes

```
import StdEnv,Text

```

#

```
(!!)[i\\i<-[1..]|indexOf(""<+i)(""<+i^2)>=0]

```

Try it online!

```
(!!)                               // index into the list of
 [ i                               // i for every
  \\ i <- [1..]                    // i from 1 upwards
  | indexOf (""<+i) (""<+i^2) >= 0 // where i is in the square of i
 ]

```
> 2 votes

# Answer
# Java 8, ~~66~~ ~~65~~ 63 bytes

```
n->{int r=0;for(;!(++r*r+"").contains(r+"")||--n>0;);return r;}

```

-1 byte thanks to *@Shaggy*.
-2 bytes thanks to *@Arnauld*.

1-indexed.

Try it online.

**Explanation:**

```
n->{                // Method with integer as both parameter and return-type
  int r=0;          //  Result-integer, starting at 0
  for(;             //  Loop as long as:
       !(++r*r+"")  //    (increase result `r` by 1 first with `++r`)
                    //    If the square of the result `r` (as String)
        .contains(  //    does not contain
          r+"")||   //    the result `r` itself (as String):
       --n>0;);     //     (decrease input `n` by 1 first with `--n`)
                    //     And continue looping if input `n` is not 0 yet
  return r;}        //  Return the result `r`

```
> 2 votes

# Answer
# Jelly, 6 bytes

```
1ẇ²$#Ṫ

```

1-indexed.

**Try it online!**

### How?

Finds the first `n` of the sequence as a list and then yields the tail, `N`.

```
1ẇ²$#Ṫ - Link: integer, n (>0)
1      - initialise x to 1
    #  - collect the first n matches, incrementing x, where:
   $   -   last two links as a monad:
  ²    -     square x
 ẇ     -     is (x) a substring of (x²)?
       -     (implicitly gets digits for both left & right arguments when integers)
     Ṫ - tail

```

---

If `0` were considered a Natural number we could use the 1-indexed full-program `ẇ²$#Ṫ` for 5.
> 2 votes

# Answer
# Ruby, 45 bytes

```
->n,i=1{/#{i+=1}/=~"#{i*i}"&&n-=1while n>0;i}

```

Try it online!
> 2 votes

# Answer
# Clojure, 81 bytes

```
(fn[n](nth(filter #(clojure.string/includes?(str(* % %))(str %))(range))n))

```

Try it online! (Unfortunately, TIO doesn't seem to support Clojure's standard string library)

If Clojure had shorter importing syntax, or had a `includes?` method in the core library, this could actually be somewhat competitive. `clojure.string/includes?` alone is longer than some answers here though :/

```
(defn nth-sq-subs [n]
  (-> ; Filter from an infinite range of numbers the ones where the square of
      ;  the number contains the number itself
    (filter #(clojure.string/includes? (str (* % %)) (str %))
            (range))

    ; Then grab the "nth" result. Inc(rementing) n so 0 is skipped, since apparently
    ;  that isn't in the sequence
    (nth (inc n))))

```

Since the TIO link is broken, here's a test run. The number on the left is the index (`n`), and the result (`N`) is on the right:

```
(mapv #(vector % (nth-sq-subs %)) (range 100))
=>
[[0 1]
 [1 5]
 [2 6]
 [3 10]
 [4 25]
 [5 50]
 [6 60]
 [7 76]
 [8 100]
 [9 250]
 [10 376]
 [11 500]
 [12 600]
 [13 625]
 [14 760]
 [15 1000]
 [16 2500]
 [17 3760]
 [18 3792]
 [19 5000]
 [20 6000]
 [21 6250]
 [22 7600]
 [23 9376]
 [24 10000]
 [25 14651]
 [26 25000]
 [27 37600]
 [28 50000]
 [29 60000]
 [30 62500]
 [31 76000]
 [32 90625]
 [33 93760]
 [34 100000]
 [35 109376]
 [36 250000]
 [37 376000]
 [38 495475]
 [39 500000]
 [40 505025]
 [41 600000]
 [42 625000]
 [43 760000]
 [44 890625]
 [45 906250]
 [46 937600]
 [47 971582]
 [48 1000000]
 [49 1093760]
 [50 1713526]
 [51 2500000]
 [52 2890625]
 [53 3760000]
 [54 4115964]
 [55 5000000]
 [56 5050250]
 [57 5133355]
 [58 6000000]
 [59 6250000]
 [60 6933808]
 [61 7109376]
 [62 7600000]
 [63 8906250]
 [64 9062500]
 [65 9376000]
 [66 10000000]
 [67 10050125]
 [68 10937600]
 [69 12890625]
 [70 25000000]
 [71 28906250]
 [72 37600000]
 [73 48588526]
 [74 50000000]
 [75 50050025]
 [76 60000000]
 [77 62500000]
 [78 66952741]
 [79 71093760]
 [80 76000000]
 [81 87109376]
 [82 88027284]
 [83 88819024]
 [84 89062500]
 [85 90625000]
 [86 93760000]
 [87 100000000]
 [88 105124922]
 [89 109376000]
 [90 128906250]
 [91 146509717]
 [92 177656344]
 [93 200500625]
 [94 212890625]
 [95 250000000]
 [96 250050005]
 [97 289062500]
 [98 370156212]
 [99 376000000]]

```

This should be able to support any value of `n`; providing you're willing to wait for it to finish (finding the 50th to 100th integers in the sequence took like 15 minutes). Clojure supports arbitrarily large integer arithmetic, so once numbers start getting huge, it starts using `BigInt`s.
> 2 votes

# Answer
## **Edit (response to comments): Python 2, 76 bytes**

Wanted to try for a non recursive method. (New to golfing, any tips would be great!)

```
def f(c,n=0):
    while 1:
        if`n`in`n*n`:
            if c<2:return n
            c-=1
        n+=1

```

Thanks both BMO and Vedant Kandoi!
> 1 votes

# Answer
# Charcoal, 25 bytes

```
Ｎθ≔¹ηＷθ«≦⊕η¿№Ｉ×ηηＩη≦⊖θ»Ｉη

```

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

```
Ｎθ

```

Input `n`.

```
≔¹η

```

Start `N` at 1. (Or, this could start counting at `0` which would make the input 1-indexed.)

```
Ｗθ«

```

Repeat until we have found `n` numbers in the sequence.

```
≦⊕η

```

Increment `N`.

```
¿№Ｉ×ηηＩη

```

If `N*N` contains `N`, then...

```
≦⊖θ»

```

... decrement `n`.

```
Ｉη

```

Print `N`.

My attempts at golfing this further were stymied by Charcoal a) not having an `if..then` except at the end of a block (which costs 2 bytes) b) not having a `Contains` operator (converting the output of `Find` or `Count` into a boolean that I could subtract from `n` again costs 2 bytes).
> 1 votes

# Answer
# Python 2, ~~47~~ 43 bytes

<sup>-4 bytes thanks to Dennis (adding 1 to recursive call instead of returning `n-1`)</sup>

```
f=lambda c,n=1:c and-~f(c-(`n`in`n*n`),n+1)

```

Try it online!

## Explantion/Ungolfed

Recursive function taking two arguments \\$c,n\\$; \\$n\\$ is counts up \\$1,2,3\dots\\$ and everytime \\$n \texttt{ in } n^2\\$ it decrements \\$c\\$. The recursion ends as soon as \\$c = 0\\$:

```
# Enumerating elements of A018834 in reverse starting with 1
def f(counter, number=1):
    # Stop counting
    if counter == 0:
        return 0
    # Number is in A018834 -> count 1, decrement counter & continue
    elif `number` in `number ** 2`:
        return f(counter-1, number+1) + 1
    # Number is not in A018834 -> count 1, continue
    else:
        return f(counter, number+1) + 1

```
> 1 votes

# Answer
## Haskell, 60 bytes

```
([n^2|n<-[1..],elem(show n)$words=<<mapM(:" ")(show$n^2)]!!)

```

Try it online!

```
      n<-[1..]              -- loop n through all numbers starting with 1
 [n^2|        ,    ]        -- collect the n^2 in a list where
     elem(show n)           -- the string representation of 'n' is in the list
       words ... (show$n^2) -- which is constructed as follows:

            show$n^2        -- turn n^2 into a string, i.e. a list of characters
          (:" ")            -- a point free functions that appends a space
                            -- to a character, e.g.  (:" ") '1' -> "1 "
        mapM                -- replace each char 'c' in the string (n^2) with
                            -- each char from (:" ") c and make a list of all
                            -- combinations thereof.
                            -- e.g. mapM (:" ") "123" -> ["123","12 ","1 3","1  "," 23"," 2 ","  3","   "]
      words=<<              -- split each element into words and flatten to a single list
                            -- example above -> ["123","12","1","3","1","23","2","3"]

(                      !!)  -- pick the element at the given index

```
> 1 votes

# Answer
# APL (Dyalog Extended), ~~31~~ 30 bytes

```
1∘{>⍵:⍺-1⋄(⍺+1)∇⍵-∨/(⍕⍺)⍷⍕⍺×⍺}

```

Try it online!

0-indexed.
> 1 votes

# Answer
# Perl 5 `-p`, 33 bytes

```
map{1while++$\**2!~/${\}/}1..$_}{

```

Try it online!
> 1 votes

# Answer
# Lua, 137 123 79 bytes

*-thanks @Jo King for 44 bytes*

```
n=io.read()i=0j=0while(i-n<0)do j=j+1i=i+(n.find(j*j,j)and 1or 0)end
print(j*j)

```

Try it online!
> 1 votes

# Answer
# Tcl, 82 bytes

```
proc S n {while 1 {if {[regexp [incr i] [expr $i**2]]&&[incr j]==$n} {return $i}}}

```

Try it online!
> 1 votes

# Answer
# Tidy, 24 bytes

```
{x:str(x)in'~.x^2}from N

```

Try it online!

Returns a lazy list which, when called like a function, returns the `n`th element in the series.

## Explanation

```
{x:str(x)in'~.x^2}from N
{x:              }from N       select all natural numbers `x` such that
   str(x)                      the string representation of `x`
         in                    is contained in
           '~.x^2              "~" + str(x^2)

```
> 0 votes

---
Tags: code-golf, sequence
---