title: Is it a still-life?

text:
# Question
Title: Is it a still-life?
# The Problem:

You receive a (section of) a Conway's Game of Life grid. Your task is to output whether it represents a still-life (subsequent generations are identical to the current grid), a oscillator of period up to 4 (every nth generation is identical to the current grid), or something else.

The remainder of the infinite grid consists of dead cells.

## Rules of the Game of Life

If a dead cell is next to exactly three living cells, it becomes alive. Otherwise, it remains dead. If a living cell is next to 2 or 3 living cells, it stays alive. Otherwise, it dies.

## Input/Output formats

Input and output can be by any reasonable method - list of locations of living cells, array of bools, one or more strings, etc. You cannot assume that dead cells are stripped from the edge of the input grid. Outputs must be any three consistent values (\[still-life: 0, oscillator: 1, other: 2\], for instance).

For oscillators of period 5 or greater, output of "Oscillator" or "Other" are both acceptable.

## Examples

(1 is living, 0 is dead)

```
INPUT          OUTPUT
0 0 0 0
0 1 1 0        Still-Life
0 1 1 0
0 0 0 0

INPUT          OUTPUT
1 1
1 0            Other

INPUT          OUTPUT
0 0 0 1 1 0
0 0 0 1 0 1    Still-Life
0 0 0 0 1 0

INPUT          OUTPUT
0 1 0
0 0 1          Other
0 1 0

INPUT          OUTPUT
0 1
0 1            Oscillator (period 2)
0 1

INPUT          OUTPUT
1 1 0 0
1 1 0 0        Oscillator (period 2)
0 0 1 1
0 0 1 1

INPUT                  OUTPUT
0 1 1 0 0 0 0 0
0 0 0 1 0 0 0 0        Oscillator (period 3)
1 0 0 0 0 0 0 0
1 0 0 0 1 0 0 0
1 0 0 0 1 1 1 1
0 0 1 0 0 0 0 0

INPUT                 OUTPUT
1 1 0 0 0 1 1
0 1 0 1 0 1 0
0 1 1 0 1 1 0         Oscillator (period 4)
0 1 0 1 0 1 0
1 1 0 0 0 1 1

INPUT          OUTPUT
1 1 1
1 0 0          Other (This is a glider - the same shape will repeat, but it will be shifted)
0 1 0

```

This is - the shortest answer in each language wins.

# Answer
> 14 votes
# APL (Dyalog Extended), ~~61 56 48 40 37 36 35 33~~ 32 bytes

```
6∧+/w∘≢¨⊢∘⌂life\5/⊆w←0,∘⌽∘⍉⍣16⊢⎕

```

Try it online!

Outputs 0 for still-life, 6 for oscillators, and 12 for other.

Expects a binary matrix.

-5 bytes from ovs using a train for the left-most dfn.

-8 bytes from user by omitting `traj` and using  instead.

-8 more bytes from user.

-3 bytes simplifying user's idea.

-1 more byte from user(how did they do it?!).

-2 more bytes, converting to a full program.

-1 more more byte from user.

## Explanation

```
 6∧+/w∘≡¨⊢∘⌂life\5/⊆w←0,∘⌽∘⍉⍣16⊢⎕
                            ⍣16⊢⎕ apply the following to the input 16 times:
                      0,∘⌽∘⍉      rotate 90 degrees and prepend a column of zeroes
                    w←            store padded input in w
                 5/⊆              copy it 5 times
         ⊢∘⌂life\                 scan using life function
     w∘≡¨                         check which ones match w
   +/                             sum to get number of truthies
 6∧                               lcm(6,truthies)

```

# Answer
> 11 votes
# MATL, ~~42~~ ~~38~~ ~~31~~ 29 bytes

*2 bytes saved thanks to @Neil!*

```
4thYaXJ4:"3Y6QZ+5:7mtJX=w]xvu

```

Input is a binary matrix. Output is

* Still life: `1`
* Oscillator: `0` *newline*`1`
* Other: `0`.

Try it online! Or verify all test cases.

### Explanation

```
4th      % Push 4, duplicate, concatenate horizontally. Gives [4 4]
Ya       % Implicit input. Padarray. Adds a 2D frame of width 4. This is the
         % initial grid state. The padding ensures that results will be correct
         % for 4 iterations even if only this finite region is considered
XJ       % Copy that into clipboard J
4:"      % Push 4, range, for each (this loop runs for 4 iterations)
  3Y6    %   Push [1 1 1; 1 0 1; 1 1 1] (Moore neighbourhood)
  Q      %   Add 1, element-wise. Gives [2 2 2; 2 1 2; 2 2 2]
  Z+     %   2D convolution, maintaining size. Newly active cells correspond to
         %   values 5 = 1+2*2 (active cell with 2 active neighbours), 6 = 0+2*3
         %   (inactive cell with 3 active neighours) or 7 = 1+2*3 (active cell
         %   with 3 active neighours)
  5:7    %   Push range from 5 to 7, that is, [5 6 7]
  m      %   Ismember. This gives the new grid state
  tJX=   %   Duplicate. Push copy of initial state. Are both arrays equal? Gives
         %   true (1) or false (0) (*)
  w      %   Swap. This moves the latest grid state to top, for the next iteration
]        % End
x        % Delete last grid state. The stack contains the results of (*) for each
         % iteration
v        % Concatenate stack contents vertically. Gives a column vector containing
         % true (1) or false (0). The only possibilities are: [1; 1; 1; 1]
         % (still life), [0; 1; 0; 1] (period 2), [0; 0; 1; 0] (period 3),
         % [0; 0; 0; 1] (period 4) and [0; 0; 0; 0] (other)
u        % Unique: removes duplicates, maintaining order. Gives 1, [0; 1] or 0
         % Implicit display

```

# Answer
> 9 votes
# JavaScript (ES6), 191 bytes

Expects a binary matrix. Returns `false` for *still-life*, `true` for *oscillator* or `0` for *other*.

```
m=>(M=m=(h=a=>[v,v,v,v,...a,v,v,v,v])(v=m.map(h,v=0),v=v.map(_=>0)),g=k=>(m=m.map((r,y)=>r.map((v,x)=>m.reduce(n=>d?n>>(m[~-(y+--d/3)]||[])[x+d%3-1]:n,v*16+8,d=9)&1)))+''!=M?k&&g(k-1):k<4)(4)

```

Try it online!

### Commented

The helper function `h` expands an array `a[]` with 4 leading and 4 trailing values `v`:

```
h = a => [v, v, v, v, ...a, v, v, v, v]

```

We use it to expand the original matrix horizontally and vertically. A copy of the updated matrix is saved in `M`:

```
M = m = h(v = m.map(h, v = 0), v = v.map(_ => 0))

```

We then invoke the main recursive function `g` with `k = 4`:

```
g = k =>                         // k = counter
  ( m =                          // update m[]:
    m.map((r, y) =>              //   for each row r[] at position y in m[]:
      r.map((v, x) =>            //     for each value v at position x in r[]:
        m.reduce(n =>            //       for each entry in m[]:
          d ?                    //         if d is not equal to 0:
            n >> (               //           right-shift n if the cell at:
              m[~-(y + --d / 3)] //             Y = floor(y + --d / 3) - 1
              || []              //
            )[x + d % 3 - 1]     //             X = x + (d mod 3) - 1
                                 //           is set
          :                      //         else:
            n,                   //           leave n unchanged
          v * 16 + 8,            //         starting with n = v * 16 + 8
                                 //         (0b1000 if v = 0, or 0b11000 if v = 1)
          d = 9                  //         and d = 9
        )                        //       end of reduce()
        & 1                      //       isolate the least significant bit
      )                          //     end of inner map()
    )                            //   end of outer map()
  ) + '' != M ?                  // coerce m[] to a string; if it's not equal to M[]:
    k && g(k - 1)                //   unless k = 0, do a recursive call with k - 1
  :                              // else:
    k < 4                        //   test whether there was at least 2 iterations

```

# Answer
> 8 votes
# APL (Dyalog Extended), ~~31~~ ~~27~~ 26 bytes

```
(6∧⌂life⍣(1…4)⍳⊂)(⌽0,⍉)⍣16

```

Try it online!

APL has emerged victorious again. My work here is finally done; now I can rest.

This borrows heavily from Razetime's answer, but I thought it was sufficiently different as to merit its own answer. Also, I wanted to get some rep from this :) **@ngn** also helped on this new train version.

Returns 0 for still-life, 6 for oscillators, and 12 for other. Requires zero-indexing.

is niladic and reads from the input.

`(⌽0,⍉)⍣16` pads 4 layers of zeroes on all sides of the input. , the power operator, applies `(⌽0,⍉)` 16 times. `0,` adds one row of zeroes, and `⌽⍉` rotates 90 degrees.

`life⍣(1…4)⍳⊂` is a fork. On the right side,  boxes the padded grid. On the left side, `⌂life⍣(1…4)` makes a range from 1 to 4 (`1…4`) and for every x in that range, it applies the `⌂life` function to the padded matrix x times. Basically, it gives us a vector of the padded matrix over 4 generations. Then,  finds the index of the padded matrix inside the vector of generations. If it's a still-life, this will be 0, the first element; if it's an oscillator, it will be 1, 2, or 3, and if it's something else, it will be 4 (outside the vector).

`6∧` just bring the different oscillator indices together finding the lcm with 6. Still-life (0) remains 0, oscillator (1,2,3) become 6, and other (4) becomes 12.

# Answer
> 7 votes
# Jelly, ~~32~~ 31 bytes

```
Ż€UZ
Ç⁴¡µÇ4¡+3\Z$⁺_|=3µ4Ð¡Ḋiµ’Ṡ

```

Try it online!

Outputs `0` for still life, `1` for oscillator, and `-1` for other.

```
Ż€UZ                          Monadic helper link: pad row with zeroes and rotate
Ż€                            Prepend a 0 to each row,
  U                           reverse each row,
   Z                          transpose.

Ç⁴¡µÇ4¡+3\Z$⁺_|=3µ4Ð¡Ḋiµ’Ṡ    Main link:
Ç⁴¡                           Repeat helper 16 times (pad the input four times).
   µ             µ4Ð¡         Repeat four times, collecting each result
                     Ḋ        (not including the 0th iteration):
    Ç4¡                       pad the grid once,
       +3\                    sum every neighborhood of three elements,
          Z                   transpose,
           $⁺                 sum and transpose again,
             _                subtract the previous grid values,
              |               bitwise OR with the previous grid values,
               =3             is each equal to 3?
                      i       Find the index in the results (or 0 if not found)
Ç4¡µ                          of the quadruple-padded input,
                       µ      then
                        ’     decrement
                         Ṡ    and take the sign.

```

`µ’` could be `_1`, ~~and `Ż€UZµ4¡` was originally `Ż€UZƊ4¡`~~, but if I'm already using ~~two~~ one `µ`~~s~~ then I may as well use ~~two~~ one more!

`Ç4¡+3\Z$⁺` computes the sum of each Moore neighborhood including the centers, which in the case of a cell which should be alive in the next generation is 3 or 4, but not 4 if the cell is dead, so while `_|` leaves sums for dead cells unchanged, it decrements the sums for alive cells, such that cells which should survive have values 2 or 3, then sets the ones bit so that 2 becomes 3, 3 remains 3, and no other value becomes 3.

# Answer
> 6 votes
# Wolfram Language (Mathematica), 65 bytes

```
⌊CellularAutomaton["GameOfLife",p=#~ArrayPad~4,4]~Count~p/2⌋&

```

Try it online!

Returns `2` for still-life, `1` for oscillators, and `0` for other.

# Answer
> 5 votes
# 05AB1E, 43 bytes

```
8Fø¾δ.ø}©4FÐ2Fø¾δ.ø}2F€ü3ø}OO·α567såD®Qˆ}¯Ù

```

Inspired by *@LuisMendo*'s MATL answer, just with less convenient builtins.. challenges aren't really 05AB1E's strong suit.

Outputs `[1]` for still-life; `[0,1]` for oscillator; and `[0]` for other.

Try it online or verify all test cases.

**Explanation:**

```
# Pad the input with four layers of 0s:
8F            # Loop 8 times:
  ø           #  Zip/transpose, swapping rows/columns
              #  (which uses the implicit input in the first iteration)
    δ         #  Loop over each row:
   ¾ .ø       #   And surround it with a leading and trailing 0
}©            # After the loop: store the padded input in variable `®` (without popping)

# Now we'll do a Game of Life cycle, four iterations in total:
4F            # Loop 4 times:
  D           #  Duplicate the current matrix
   2Fø¾δ.ø}   #  Pad it with a single layer of 0s similar as above
   2F         #  Loop 2 times:
     €        #   Map over each row:
      ü3      #    Create overlapping triplets of the current row
     ø        #   Zip/transpose; swapping rows/columns
   }          #  After this loop, we'll have a list of 3x3 blocks
    OO        #  Sum all values in a single 3x3 block together
      ·       #  Then double each sum
       α      #  Take the absolute difference (at the same positions) with the current
              #  matrix we've duplicated earlier
        567så #  Check for each value in this matrix if it's in the integer 567
              #  (1 if truthy; 0 if falsey)
  D           #  Duplicate the resulting matrix
   ®Q         #  Check if it's equal to matrix `®` (1 if truthy; 0 if falsey)
     ˆ        #  Pop and add this check to the global array
}             # After the loop:

# Create the result based on these four iterations:
¯             # Push the global array
 Ù            # Uniquify it
              # (after which the result is output implicitly)

```

# Answer
> 4 votes
# Python 3, ~~413~~ \\$\cdots\\$ ~~375~~ 354 bytes

Saved 13 bytes thanks to Danis!!!

```
def f(w,t=0,u=[0],R=range):
 l=len(w[0])+12;d=len(w);m=[u*l for i in u*6]+[u*6+w[i]+u*6for i in R(d)]+[u*l for i in u*6];n=[u*l for j in m];q=R(-1,2)
 while t<6and any(w[r]!=n[r+6][6:-6]for r in R(d)):
  for r in R(1,11+d):
   for c in R(1,l-1):n[r][c]=sum(m[r+i][c+j]for i in q for j in q)in(3+m[r][c],3)
  m=[[*r]for r in n];t+=1
 return t>5and 2or t>1

```

Try it online!

Verbose but it works! :)))

Inputs the grid as a list of lists of \\$1\\$s and \\$0\\$s.
Returns `False` if it's a *still-life*, `True` if its an *oscillator*, or \\$2\\$ if it's an *other*.

# Answer
> 3 votes
# Charcoal, 90 bytes

```
≔⁰θ≔⟦⟧ηＷＳ«Ｆ⌕Ａι1⊞η⟦θκ⟧≦⊕θ»≔ηθＦ⁴«≔⟦⟧ζＦ³Ｆ³Ｆ⊕⌈↔⊖⟦κλ⟧Ｆθ⊞ζ⊖Ｅν⁺ξ⎇πλκ≔Φζ∧⁼λ⌕ζκ›²↔⁻⁶№ζκθ⊞υθ»Ｉ⌈⟦¹⌕υη

```

Try it online! Link is to verbose version of code. Input is a newline-terminated list of strings and output is `-1` for other, `0` for stable and `1` for oscillator. Explanation:

```
≔⁰θ≔⟦⟧ηＷＳ«Ｆ⌕Ａι1⊞η⟦θκ⟧≦⊕θ»≔ηθ

```

Input the grid, push the coordinates of all the `1`s to a list, and keep a copy of that list.

```
Ｆ⁴«

```

Iterate the game of life 4 times.

```
≔⟦⟧ζＦ³Ｆ³Ｆ⊕⌈↔⊖⟦κλ⟧Ｆθ⊞ζ⊖Ｅν⁺ξ⎇πλκ

```

Make a new list consisting of all the cells in the original list plus two repetitions for each neighbouring cell.

```
≔Φζ∧⁼λ⌕ζκ›²↔⁻⁶№ζκθ

```

Extract all cells that appear between 5 and 7 times. 5 represents a live cell with 2 neighbours, while 6 and 7 represent cells with 3 neighbours.

```
⊞υθ

```

Save a copy of the new iteration.

```
»Ｉ⌈⟦¹⌕υη

```

Print the index of the original position in the list of iterations, limited to 1.

---
Tags: code-golf, classification, game-of-life
---


# Question
Title: Iterate over the neighborhood of a string
## Input

A string S of length between 2 and 30. The only letters in the string will be `a` or `b`.

## Output

All strings within Levenshtein distance 2 of S. You must output all the strings without duplicates but in any order you like.

## Example

If `S = aaa` then the output would be (in any order):

```
aa
abab
ab
aabba
aaaa
abaa
bbaaa
aba
bbaa
babaa
bba
abaaa
abaab
baaa
baab
baaaa
baba
aabaa
ba
abba
aaba
aabb
abbaa
abb
aabab
aaaaa
aaaab
baaba
a
aaaba
aaabb
aaa
aab
ababa
aaab
bab
baa
baaab

```

## Constraints

Your code must be fast enough that it would run to completion on TIO when S is of length 30. This is only to stop brute force solutions.

# Answer
> 3 votes
# Haskell, ~~115~~ 109 bytes

* -6 thanks to Unrelated String

```
import Data.List
f=nub.(=<<)g.g
g=(=<<)h.(zip.inits<*>tails)
h(x,y)=[x++b++c|b<-["a","b",""],c<-[y,drop 1 y]]

```

Try it online!

Explanation:

```
f :: String -> [String]
f=nub    -- delete duplicates
 .(=<<)g -- apply g to every result (get all words with distance <= 2)
 .g      -- apply g once to the input (get all words with distance <= 1)

g :: String -> [String]
g=(=<<)h               -- apply h to every split and flatten the resulting list
 .(zip.inits<*>tails)  -- split the string at every possible position

{- |
h takes a pair of Strings (x,y the input split at some point) and returns all
combinations of x, one of a, b or nothing, and y with the first letter present
or removed
("he","llo") -> ["heallo","healo","hebllo","heblo","hello","helo"]
drop 1 is basically the same as tail with the difference that drop 1 [] returns
[] instead of throwing an error
-}
h :: (String,String) -> [String]
h(x,y)=[x++b++c|b<-["a","b",""],c<-[y,drop 1 y]]

```

# Answer
> 2 votes
# Charcoal, 66 bytes

```
⊞υθ≔⟦θ⟧ηＦη«≔⟦⟧ζＦＬιＦabＦ³⊞ζ⭆ι⎇⁻ξκν…⁺λνμＦab⊞ζ⁺ικＦζ¿¬№υκ«⊞υκ¿⁼ιθ⊞ηκ»»υ

```

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

```
⊞υθ

```

Push the input to the predefined empty list as the first result.

```
≔⟦θ⟧ηＦη«

```

Start a breadth-first search using the input.

```
≔⟦⟧ζ

```

Start collecting potential new results.

```
ＦＬιＦabＦ³

```

Loop over each index, each potential insert/edit, and each operation (0=delete, 1=edit, 2=insert).

```
⊞ζ⭆ι⎇⁻ξκν…⁺λνμ

```

Apply the specified operation to the appropriate index of the current string.

```
Ｆab⊞ζ⁺ικ

```

Also consider appending either of `a` and `b` to the current string.

```
Ｆζ¿¬№υκ«

```

For each string that has not been seen before, ...

```
⊞υκ

```

... push it to the result string, ...

```
¿⁼ιθ⊞ηκ

```

... and if we're modifying the original input then also push it to the search space.

```
»»υ

```

Finally print all the results.

# Answer
> 2 votes
# Python 2, 113 bytes

Takes input as a singleton list containing the string.

```
s="{k[:i]+c+k[i+w:]for k in %sfor i in range(len(k)+1)for c in['','a','b']for w in(0,1)}"
print eval(s%s%input())

```

Try it online!

---

# Python 3, 114 bytes

```
f=lambda s,d=2,i=0:d*s[i-1:]and{k[:i]+c+k[i+w:]for k in f(s,d-1)for c in['','a','b']for w in(0,1)}|f(s,d,i+1)or{s}

```

Try it online!

**Commented**:

```
f=lambda s,d=2,i=0:      # a recursive function with arguments:
                         #  - s, the input string
                         #  - d, the maximal Levensthein distance to s
                         #  - i, the index of the current operation
  d*s[i-1:]and ... or{s} # if d==0 or i>len(s) return a set containing s
                         # otherwise:
  {k[:i]+c+k[i+w:]       #  apply an operation
   for k in f(s,d-1)     #   on every string with maximal Levensthein distance d-1
   for c in['','a','b']  #   insert / replace with any of '', 'a', 'b'
   for w in(0,1)}        #   w==0: c=='': no operation, c!='': insertion
                         #   w==1: c=='': deletion,     c!='': replacement
  | f(s,d,i+1)           #  union this to the result of applying an operation at a larger index

```

# Answer
> 1 votes
# JavaScript (ES6),  ~~137 134 131~~  123 bytes

Expects a string with `0`/`1` instead of `a`/`b`. Returns an Object whose keys (and values) are the output strings.

```
f=(s,k=2,o={},p='')=>[...o[s]=s].map((c,i)=>k&&[p+(q=s.slice(i+1)),p+(C=c^1)+q,(p+=c)+0+q,p+1+q,C+s].map(s=>f(s,k-1,o)))&&o

```

Try it online!

### Commented

This is a naive and rather lengthy implementation that just builds all the strings recursively.

```
f = (                         // f is a recursive function taking:
  s,                          //   s = input string
  k = 2,                      //   k = counter
  o = {},                     //   o = an object used to store the results
  p = ''                      //   p = current prefix
) =>                          //
  [...o[s] = s]               // save s into o and split s
  .map((c, i) =>              // for each character c at position i in s:
    k &&                      //   abort if k = 0
    [                         //   otherwise, build an array:
      p +                     //     remove c by concatenating the prefix p
      (q = s.slice(i + 1)),   //     with the suffix q
      p + (C = c ^ 1) + q,    //     modify c
      (p += c) + 0 + q,       //     insert '0' after c (and update p)
      p + 1 + q,              //     insert '1' after c
      C + s                   //     prepend the modified c at the beginning
                              //     (this case is not covered by the insertions)
    ]                         //   end of array
    .map(s => f(s, k - 1, o)) //   do a recursive call for each string in there
  )                           // end of map()
  && o                        // return o

```

# Answer
> 1 votes
# Ruby 2.7, ~~115~~ 109 bytes

*Port of ovs's answer in Python!*

```
f=->s,d=2,i=0{d>0&&s[i-1]?['',?a,?b].product(f[s,d-1],[0,1]).map{_2[...i]+_1+"#{_2[i+_3..]}"}|f[s,d,i+1]:[s]}

```

Try it online!

TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves 3 bytes, and we've begin-less `...i` and end-less `i+_3..` ranges, which saves 3 more bytes!

# Answer
> 1 votes
# Haskell, 89 bytes

```
import Data.List
nub.(g=<<).g
g(h:t)=t:((:)<$>"ab"<*>[h:t,t])++map(h:)(g t)
g _=["a","b"]

```

Try it online!

The helper function `g` recursively generates all strings at Levenshtein distance 1.

# Answer
> 0 votes
# K (ngn/k), 78 bytes

```
{?"ab"@?,/e'e"b"=x}
e:{?,/(~+x==#x;{y,x,z}.',/0 1,/:\:(0,'!1+#x)_\:x;x_/:!#x)}

```

Try it online!

---
Tags: code-golf, string, restricted-time
---


title: Squarefree Palindromes

text:
# Question
Title: Squarefree Palindromes
Create the shortest function, program, or expression that calculates a sequence of squarefree palindromic numbers.

A squarefree number is one which is not evenly divisible by a square number (i.e. does not contain a repeated prime factor). For example, \\$44 = 2^2 \times 11\\$ is not squarefree, whereas \\$66 = 2\times3\times11\\$ is.

You can find a list of the numbers from this link. The list goes as such: `1, 2, 3, 5, 6, 7, 11, 22, 33, 55, 66, 77, 101, 111, 131, 141, 151, 161, 181, 191...`

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

```
n=0
while 1:
 n+=1
 if`n`[::-1]==`n`*all(n%i**2for i in range(2,n)):print n

```

**Try it Online!**

If this was a decision problem (54 bytes):

```
lambda n:`n`[::-1]==`n`*all(n%i**2for i in range(2,n))

```

### Explanation:

```
`n`[::-1]==`n`                     # If n is a palindrome. `n` is repr(n).
                                   # We check that it's the same
                                   # backwards and forwards.
              *                    # Multiplplying 2 booleans is AND
all(n%i**2for i in range(2,n))     # Check that squares of all #'s < n do not divide n

```
> 4 votes

# Answer
# Brachylog, 5 bytes

Generates the sequence

```
ḋ≠&↔?

```

Try it online!

```
ḋ≠&↔? (the input's)
ḋ     prime decomposition
 ≠    has only unique elements
  &   and the input
   ↔  reversed
    ? is the input
      (and also the output)

```
> 2 votes

# Answer
# Husk, 8 bytes

```
foS=upİ↔

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES7),  ~~81~~  76 bytes

Returns the n-th term, 1-indexed.

```
f=(n,i)=>(g=d=>i[d]&&i[d]-i[k++]?1:i%d--**2?g(d):d)(i+=k='')||n--?f(n,-~i):i

```

Try it online!

## Commented

### Helper function

The helper function **g** checks simultaneously whether **i** is palindromic and squarefree. The variable **d** is used as a counter to test the divisors and as a decreasing digit index. The variable **k** is used as an increasing digit index. Both **i** and **k** are defined in the wrapper.

```
g = d =>            // g is a recursive function taking a counter d
  i[d] &&           //   if i[d] is defined
  i[d] - i[k++] ?   //   and it's not equal to i[k] (increment k afterwards):
    1               //     i is not palindromic: force a truthy result
  :                 //   else:
    i % d-- ** 2 ?  //     if d² is not a divisor of i (decrement d afterwards):
      g(d)          //       do a recursive call
    :               //     else:
      d             //       return d (0 if i is squarefree)

```

### Wrapper

The main function decrements **n** whenever **g** returns **0** and stops when **n = 0**.

```
f = (n, i) =>       // f is a recursive function taking an index n
  g(i += k = '') || //   set k to a zero'ish empty string,
                    //   coerce i to a string
                    //   and invoke g with d = i
  n-- ?             //   if the above call was truthy or n is not equal to 0:
    f(n, -~i)       //     do a recursive call with i + 1
  :                 //   else:
    i               //     success: return i

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 52 bytes

```
Do[If[SquareFreeQ@n&&PalindromeQ@n,Print@n],{n,∞}]

```

Try it online!
> 1 votes

# Answer
# Jelly, 10 bytes

```
1ÆfQƑ×ŒḂƲ#

```

Try it online!

Returns the first `n` squarefree palindromes

## How it works

```
1ÆfQƑ×ŒḂƲ# - Main link. Takes no arguments
        Ʋ  - Group the previous 4 links into a monad f(k):
 Æf        -   Prime factorisation of k (with repeats)
    Ƒ      -   Is this invariant under:
   Q       -     Deduplication
      ŒḂ   -   Is k a palindrome?
     ×     -   Both conditions are true?
1        # - Read an integer n from STDIN. Count up k = 1, 2, 3, ...
             until n such k return true under f(k). Return those k

```
> 1 votes

# Answer
# 05AB1E, 8 bytes

Prints the infinite sequence.

```
∞ʒÂQyÓà*

```

Try it online!

**Commented**:

```
∞        # push the list of natural numbers [1, 2, ...]
 ʒ       # keep the values for which the following is 1:
  Â      #   push the number and its reverse
   Q     #   are both equal?
    y    #   push the number again
     Ó   #   push the exponents of the prime factorisation
      à  #   take the maximum
       * #   multiply both numbers

```
> 1 votes

# Answer
# Perl 5 `-MList::Util=all`, 52 bytes

```
$_-$r||(all{$r%$_**2}2..$_)&&say while$r=reverse++$_

```

Try it online!
> 0 votes

---
Tags: code-golf, sequence, palindrome, factoring
---


title: The Random Walker Printer

text:
# Question
Title: The Random Walker Printer
Draw a program or function that will write to `STDOUT` `n` times (each for one step) a string that contains a dot `.` at the location of the walker. The program also needs to write a line every `s` seconds (or wait `s` seconds after each line).

A random walk is a mathematical formalization of a path that consists of a succession of random steps (wiki), such that every new step will be the last step plus a new value, so any `t`step value is just the sum of all the random values before ir plus the initial value.

The program should take 2 inputs and will use only spaces `" "` and dots `"."` on the output. The start value of the walker will be `20` such that the output should be a dot after 19 spaces.

```
                  . #19 spaces then a dot

```

Every new step the value will be the last value of the walker plus one of these`[-2-1,0,1,2]`(20% chance each). After the new position is printed the program should wait `s` seconds and the go to the next step. If the step takes the walker outsite the range `1 to 40` it should be just ignored and the walker position stays the same. The number of spaces will always be a number from 0 to 39.

### Example

```
#input
Mywalk(s = 0.1, n = 30)

#output
                     .
                    .
                      .
                        .
                          .
                           .
                            .
                          .
                         .
                          .
                           .
                            .
                           .
                          .
                           .
                           .
                         .
                         .
                          .
                            .
                           .
                          .
                           .
                           .
                           .
                         .
                          .
                         .
                          .
                          .

```

### Considerations

* You may take the input as any reasonable format
* The shortest code wins
* It's okay if your program only accept the seconds as integers

# Answer
# Pyth, 39

```
J19VEK+.d0QW<.d0K)+*d=JhtS[Z39-+O5J2)\.

```

Takes `s` as the first line of input and `n` as the second. Works on the command line but not with the online interpreter. My first Pyth program ever! Golfing tips are appreciated.
> 6 votes

# Answer
# Matlab, 112

The core idea is generating a list of possible next positions and then uniformly drawing one of them. If we are e.g. at position $l=1$ the possible steps would be `[-1,0,1,2,3]` Of course if we would chose `-1` that would be invalid and we would have to stay at the same position. Thats why we replace the *invalid* positions with the current position, `[1,0,1,2,3]`, and then randomly chose an element from this updated list.

The OP asked us tho *draw* the program, so here we go:

The transcription:

```
function c(n,s);
l=19;                             %initialize position
for k=1:n;
    disp([ones(1,l)*32,'.']);     %print the line
    z=(-2:2)+l;                   %get vector of possible next steps (for l=1 we get [-1,0,1,2,3])
    z(z<0)=l;                     %prune invalids: here we just replace the the invalid positions with the current position
    z(z>39)=l;                    %   this ensures the same behaivour as staying in the same spot when going outside of the range
    l=z(randi(5));                %draw random sample of those
    pause(s);
end

```
> 13 votes

# Answer
# Perl, ~~136~~ ~~128~~ ~~116~~ ~~106~~ ~~101~~ ~~90~~ 86

```
$p=19;map{say$"x$p.".";sleep $ARGV[0];$x=rand(5)+$p-2;$p=$x>0&&$x<40?$x:$p}1..$ARGV[1]

```

Requires the seconds to be an integer.

Run with `perl <filename> <second delay> <number of steps>`.

There may be more golfing potential here, although honestly, I'm surprised it got this far. (Come on, only 6 more bytes to beat the bash answer...)

**Changes**

* Saved 8 bytes by removing unneeded parentheses and spelling out ARGV (it's actually shorter that way)
* Saved 12 more bytes by removing `$s` and `$n` and just using the plain `$ARGV[0]` and `$ARGV[1]`
* Saved another 10 bytes when I realized I could use `$"` and didn't need to specifically define `$u` as `$undef`.
* Saved 5 more bytes by rearranging the ternary and how `$x` is used and by using `map` instead of `for`.
* Saved 11 bytes by no longer accepting the seconds as decimals (challenge spec says it's OK.)
* Saved another 5 bytes by using `say` instead of `print`.
> 8 votes

# Answer
# Python 2, ~~124~~ 119 bytes

@janrn and @Steve Eckert: I don't have enough reputation to comment your answer but here's essentially your version shortened down. The task is to draw a program or a *function*, so by using `f(s,x)` you can save quite some bits, as well you can use `max(0,min(x,39))` to avoid an extra `if` clause. Got it down to:

```
import time,random as r
def f(s,x):
 n=19
 while x:print' '*n+'.';time.sleep(s);n=max(0,min(n+r.randint(-2,2),39));x-=1

```
> 6 votes

# Answer
# Bash, 81

```
for((s=20;i++<$1;t=s,s+=RANDOM%5-2,s=s<0|s>39?t:s)){
printf %${s}s.\\n
sleep $2
}

```

Edit: *If the step takes the walker outsite the range 1 to 40 it should be just ignored and the walker position stays the same* handled correctly.

Input from command-line options. E.g.:

```
$ ./randwalk.sh 5 0.5
                    .
                     .
                    .
                  .
                 .
$

```
> 5 votes

# Answer
# Processing, ~~150~~ 147

```
void w(int n,int s){int x=20,i,y,c=0;for(;c<n;c++){x+=y=int(random(5)-2);if(x>40||x<0)x-=y;for(i=1;i<x;i++)print(" ");println(".");delay(s*1000);}}

```

Usage:

```
void setup() {
    w(10,1);
}

```

Note: `1000` can't be changed to `1e3` for type reasons.
> 4 votes

# Answer
## Python 2.7, ~~198~~ ~~162~~ ~~143~~ 133

```
import time,random as r;p=20;s=0;d=input();w=input()
while s<d:
 print' '*p+'.';s+=1;p=max(1,min(p+r.randint(-2,2),40));time.sleep(w)

```

When calling the script with `python script.py`, the first input is the amount of steps, second input the time between steps (accepts float or int). Any suggestions for improving?

**Edits**

* saved 36 bytes due to now using `print ' '*p+'.'`, thanks to @corsiKlause Ho Ho Ho
* down another 19 bytes by removing tab indents, replaced them with one space or `;` where possible
* 10 bytes less thanks to @Bruce\_Forte idea with `p=max(1,min(p+r.randint(-2,2),40))` (I can't comment on your answer as well, but thanks; don't want to copy it completely)
> 4 votes

# Answer
## Ruby, 84

```
def w(s,n)q=19;n.times{puts ' '*q+'.';sleep s;q+=rand(5)-2;q=[[q,0].max,39].min};end

```
> 4 votes

# Answer
# Lua, 140 Bytes

Note: This program requires the LuaSocket package.

```
require"socket"p=19 for i=1,arg[2]+0 do print((" "):rep(p)..".")p=p+math.random(-2,2)p=p<0 and 0 or p>39 and 39 or p socket.sleep(arg[1])end

```
> 3 votes

# Answer
# Perl 6, 92 bytes

```
my (\n,\s)=@*ARGS;$/=19;for (-2..2).roll(n) {put ' 'x($/+=(40>$/+$_>=0??$_!!0)),'.';sleep s} # 92

```

```
my (\n,\s)=@*ARGS;
$/=19;
for (-2..2).roll(n) {
  put ' 'x($/+=(40>$/+$_>=0??$_!!0)),'.';
  sleep s
}

```

Usage:

```
$ perl6 -e 'my (\n,\s)=@*ARGS;$/=19;for (-2..2).roll(n) {put " "x($/+=(40>$/+$_>=0??$_!!0)),".",;sleep s}' 10 0.001
                  .
                .
               .
              .
               .
                .
               .
                .
                  .
                 .

```
> 3 votes

# Answer
## Mathematica, ~~122~~ 117 bytes

```
$RecursionLimit=∞;If[#2>0,Print[Indent[a=Min[#3+RandomInteger@{-2,2},39]~Max~0],"."];Pause@#;#0[#,#2-1,a]]&[##,19]&

```

Recursive anonymous function, takes input in the order specified. Could probably be golfed further.
> 3 votes

# Answer
# JavaScript (ES6), 125 bytes

```
(s,n)=>(t=setTimeout)(c=`console.log(" ".repeat(p)+".");p+=m=Math.random()*5|0;p-=p>41|p<2?m:2;--i&&t(c,d)`,d=s*1e3,p=19,i=n)

```

## Explanation

```
(s,n)=>
  (t=setTimeout)(                     // set inital timeout
    c=`                               // c = code for timeout to execute
      console.log(" ".repeat(p)+"."); // print the current line
      p+=m=Math.random()*5|0;         // move walker 0 - 4 positions to the right
      p-=p>41|p<2?                    // if walker was moved out of bounds (2 - 41 instead
                                      //     of 0 - 39 because the random move of 0 - 4 to
                                      //     the right has not had the 2 subtracted yet)
        m:                            // undo the move
        2;                            // else subtract 2 to make the move -2 to 2
      --i&&t(c,d)                     // while we have steps remaining schedule next one
    `,
    d=s*1e3,                          // d = milliseconds to wait between steps
    p=19,                             // p = position of walker (0 indexed)
    i=n                               // i = steps remaining (needed to make n global)
  )

```

## Test

```
console.log = s => result.textContent += s + "\n";
var solution = (s,n)=>(t=setTimeout)(c=`console.log(" ".repeat(p)+".");p+=m=Math.random()*5|0;p-=p>41|p<2?m:2;--i&&t(c,d)`,d=s*1e3,p=19,i=n)
```

```
<input type="number" id="seconds" value="0.1" /><br />
<input type="number" id="steps" value="30" /><br />
<button onclick="solution(+seconds.value,+steps.value)">Go</button>
<pre id="result"></pre>
```
> 3 votes

# Answer
# k4, 61 characters

```
f:{y{-1((y:1|40&y+-2+*1?5)#" "),".";."\\sleep ",$x;y}[x]\20;}

```

sample run:

```
  f[.1]30
                      .
                    .
                    .
                   .
                   .
                  .
                  .
                   .
                   .
                     .
                    .
                  .
                  .
                    .
                   .
                   .
                 .
                .
               .
               .
              .
            .
          .
         .
         .
          .
            .
              .
              .
                .

```
> 3 votes

# Answer
# Python 3, 154 bytes

```
import time
from random import*
w=int(input())
z=int(input())
g=19
c=6
s=" "
while c:
    c-=1
    s+=s
while z:
    z-=1
    if -1<g<40:
        print(s[:g]+'.')
    time.sleep(w)
    g+=randint(-2,2)

```

Generate a string of spaces greater than the maximum required length, then print that string ONLY up to the char at index 'g', then print a '.'. Finish by incrementing g by a random value in the range \[-2:2\], and repeat.

If anyone could help me golf down that horrific input block, I'd appreciate it.
> 2 votes

# Answer
# C funtion, 114

```
s=20,i,t;w(int n,float f){for(;i++<n;t=s,s+=rand()%5-2,s=s<0||s>39?t:s,usleep((int)(f*1e6)))printf("%*c.\n",s,0);}

```

Pretty much a direct translation of my bash answer.

### Full test program:

```
s=20,i,t;w(int n,float f){for(;i++<n;t=s,s+=rand()%5-2,s=s<0||s>39?t:s,usleep((int)(f*1e6)))printf("%*c.\n",s,0);}

int main (int argc, char **argv) {
  w(10, 0.2);
  return 0;
}

```
> 1 votes

# Answer
# APL (Dyalog Unicode), 35 bytes

```
⍬⊣⎕{⎕←⌽⍵↑'.'⋄1⌈40⌊⍵+3-?5⊣⎕DL⍺}⍣⎕⊢20

```

Try it online!

A full program which takes n as first input and s as the second.

```
⍬⊣⎕{⎕←⌽⍵↑'.'⋄1⌈40⌊⍵+3-?5⊣⎕DL⍺}⍣⎕⊢20
   {                         }⍣⎕    do the following n times
  ⎕                                 with s as constant left argument ⍺
                                ⊢20 and 20 as right argument ⍵
       ⍵↑'.'                        take ⍵ characters from '.'
      ⌽                             reverse to pad with spaces
    ⎕←                              and display it
                         ⎕DL⍺       delay s seconds
                        ⊣           suppress it's return value with
                      ?5            a random number in 1-5
                    3-              subtract from 3 to get negative possibilities
                  ⍵+                add current ⍵ to it
               40⌊                  minimum of that and 40
             1⌈                     maximum of that and 1
⍬⊣                                  suppress the final return value.

```
> 0 votes

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


title: Shortest way to get a TypeError

text:
# Question
Title: Shortest way to get a TypeError
It's simple, simply write the shortest code to raise a `TypeError`.

In Python you can do:

```
raise TypeError

```

However it should be shorter with a code that gives a `TypeError` without raising it.

# Answer
```
for chr1 in range(32, 128):
  for chr2 in range(32, 128):
    for chr3 in range(32, 128):
      code = chr(chr1) + chr(chr2) + chr(chr3)
      try:
        output = exec(code, {})
      except TypeError:
        print(code)
      except:
        pass

```

Try it online!

A naive search may result that you cannot trigger a TypeError within 2 characters. You may get a TypeError with 3 characters. All solutions including:

## 1. Math operator, non-numeric types

* Math operator including `+`, `-`, `~`
* Non-numeric types including `""`, `()`, `[]`, `id`, `{}`

```
+[]
-""
~id
```

## 2. Invoke number as function

```
0()

```

## 3. Matrix multiplication between numbers

`@` is `__matmul__` in python, read more here

```
0@0

```

## 4. Binary operator with float / complex number

```
~0.
~.0
~0j

```

## 5. Iterate over number

Thanks to @Dennis to point out this.

You may iterate some variable by star operator. And `()` for a tuple may be omitted.

```
*0,

```
> 16 votes

# Answer
# JavaScript (V8), 4 bytes

```
1.()

```

Try it online!

# \[Output\]

`.code.tio:1: TypeError: 1 is not a function
1.()
 ^
TypeError: 1 is not a function
 at .code.tio:1:3`
> 3 votes

# Answer
# Python 3, 3 bytes

```
+''

```

Try it online!
> 2 votes

# Answer
## Python, 3 bytes

This is self-explanatory. The unary - operator does not take a string argument. This was covered in @tsh's solution above.

```
-""

```

Try it online!

Another one:

```
~id

```

Try it online!
> 2 votes

# Answer
# Japt, 1 byte

Throws `TypeError: U.í is not a function`

```
í

```

Test it (Errors are displayed below the output field)

---

Or, a bit less trivial:

## Japt, 2 bytes

Throws `TypeError: (U++) is not a function`

```
°(

```

Test it
> 2 votes

# Answer
# Python 3, 3 bytes

```
+[]

```

It gives an `TypeError: bad operand type for unary +: 'list`
> 1 votes

# Answer
# Python 3, 3 bytes

```
0()

```

raises a `TypeError`
> 0 votes

---
Tags: code-golf, python, error-message
---


title: Chess murder mystery

text:
# Question
Title: Chess murder mystery
*You know how many and which kinds of chess pieces were murdered. Can you come up with* any *possibility for who killed whom and how?*

## Background

During the course of a game of chess, there are between 2 and 32 pieces on the board. Call the collection of all pieces on the board (both white and black), without regard to position, the **material content** of the board.

The game begins with 16 pieces per side, often represented together as `KQRRBBNNPPPPPPPPkqrrbbnnpppppppp`. (Capital letters represent white, lowercase letters represent black. The pieces are **K**ing, **Q**ueen, **R**ook, **B**ishop, k**N**ight, and **P**awn.)

## The challenge

Write a program that receives as input a possible *material content* of the board, and produces as output a *legal sequence of moves* that achieves this content at the end of the sequence of moves.

The program need only work for *subcollections* of the initial 32 pieces (that include the white king `K` and the black king `k`). In other words, there is no need to consider crazy situations like multiples queens per side. That also means that promotion is not *necessary*, but it is still allowed.

## Input format

You may take input in a format convenient to you. For example, the following formats are acceptable:

1. A string like `KQRRBBNPPPPPPPPkqrrbbnpppppp` or `QRRBBNPPPPPPPPqrrbbnpppppp` (kings implied).

2. A list like `['Q', 'R', 'R', 'B', 'B', 'N', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'q', 'r', 'r', 'b', 'b', 'n', 'p', 'p', 'p', 'p', 'p', 'p']`.
3. A tuple of piece counts like \\$(1,2,2,1,8,1,2,2,1,6)\\$ representing \\$(Q,R,B,N,P,q,r,b,n,p)\\$ or like \\$(1,1,2,2,2,2,1,1,8,6)\\$ representing \\$(Q,q,R,r,B,b,N,n,P,p)\\$.
4. A dictionary of piece counts like `{'K': 1, 'Q': 1, 'R': 2, 'B': 2, 'N': 1, 'P': 8, 'k': 1, 'q': 1, 'r': 2, 'b': 2, 'n': 1, 'p': 6}` (or without the implied kings).
5. A string like `Nnpp` (or list `['N','n','p','p']`, or tuple \\$(0,0,0,1,0,0,0,0,1,2)\\$, or dictionary) representing which pieces are *missing*, or in line with the title, have been *murdered*!

## Output format

The output format is also flexible, but it must be parseable by a standard game engine. That means that the following are acceptable formats:

1. Standard algebraic notation, like `Nf3 e5 Nxe5 Ne7 Nxd7 Nec6 Nxb8 Nxb8`.
2. "UCI" long algebraic notation, like `g1f3 e7e5 f3e5 g8e7 e5d7 e7c6 d7b8 c6b8`.

(These sample outputs are solutions to the sample inputs before. These games appear to leave the original pieces in their starting squares, but this is not necessary nor in fact the case here.)

The output can be a string or a list, or it can be output to the screen. There is no need to number your moves, but you may if you want. (However, they must of course alternate between white and black, as well as follow other rules of chess!)

## Scoring

This is almost a standard question, meaning that submissions are scored by the length of the program in bytes.

However, in case not all subcollections are solved correctly (whether intentionally or unintentionally), that does not invalidate a submission. Instead, an additional one byte penalty will be assessed **per** subcollection of pieces that is not solved correctly.

Note that because white could have 0 or 1 queens; 0, 1, or 2 rooks; and so forth, there are \\$2\cdot 3\cdot 3\cdot 3\cdot 9 = 486\\$ possible material contents per color, and thus \\$486^2 = 236196\\$ total possible material content inputs. Thus it is strongly advisable to solve the vast majority of inputs correctly! The following program enumerates the possible inputs, and also produces the various example input formats listed above:

```
count = 0
for Q in range(2):
  for R in range(3):
    for B in range(3):
      for N in range(3):
        for P in range(9):
          for q in range(2):
            for r in range(3):
              for b in range(3):
                for n in range(3):
                  for p in range(9):
                    s1 = ("K" + "Q" * Q + "R" * R + "B" * B + "N" * N + "P" * P +
                          "k" + "q" * q + "r" * r + "b" * b + "n" * n + "p" * p)
                    s2 = ("Q" * Q + "R" * R + "B" * B + "N" * N + "P" * P +
                          "q" * q + "r" * r + "b" * b + "n" * n + "p" * p)
                    l1 = [piece for piece in s1]
                    l2 = [piece for piece in s2]
                    t1 = (Q, R, B, N, P, q, r, b, n, p)
                    t2 = (Q, q, R, r, B, b, N, n, P, p)
                    d1 = {"K": 1, "Q": Q, "R": R, "B": B, "N": N, "P": P,
                          "k": 1, "q": q, "r": r, "b": b, "n": n, "p": p}
                    d2 = {"Q": Q, "R": R, "B": B, "N": N, "P": P,
                          "q": q, "r": r, "b": b, "n": n, "p": p}
                    murders = ("Q" * (1-Q) + "R" * (2-R) + "B" * (2-B) +
                               "N" * (2-N) + "P" * (8-P) +
                               "q" * (1-q) + "r" * (2-r) + "b" * (2-b) +
                               "n" * (2-n) + "p" * (8-p))
                    murderl = [piece for piece in murders]
                    murdert1 = (1-Q, 2-R, 2-B, 2-N, 8-P,
                                1-q, 2-r, 2-b, 2-n, 8-p)
                    murdert2 = (1-Q, 1-q, 2-R, 2-r, 2-B, 2-b,
                                2-N, 2-n, 8-P, 8-p)
                    murderd = {"Q": 1-Q, "R": 2-R, "B": 2-B, "N": 2-N, "P": 8-P,
                               "q": 1-q, "r": 2-r, "b": 2-b, "n": 2-n, "p": 8-p}
                    count += 1
print(count)

```

## Verifier

The following Python3.7+ sample demonstrates how to check that a game achieves a given collection of pieces:

```
import chess
import chess.pgn
import io

pieces = "KQRBNPkqrbnp"
def piece_key(x):
  return pieces.find(x)
def sort_pieces(ps):
  return sorted(ps, key=piece_key)
def only_pieces(s):
  return filter(lambda x: piece_key(x) >= 0, s)
def final_pieces(moves):
  board = chess.Board()
  for move in moves:
    board.push(move)
  return "".join(sort_pieces(only_pieces(str(board))))
def moves_from_pgn_string_parser(s):
  pgn = io.StringIO(s)
  game = chess.pgn.read_game(pgn)
  return game.main_line()
def moves_from_uci_list(l):
  return [chess.Move.from_uci(x) for x in l]
def moves_from_uci_string(s):
  return moves_from_uci_list(s.split())

print(final_pieces(moves_from_pgn_string_parser(
    "1. Nf3 e5 2. Nxe5 Ne7 3. Nxd7 Nec6 4. Nxb8 Nxb8")))
# KQRRBBNPPPPPPPPkqrrbbnpppppp
print(final_pieces(moves_from_uci_list(
    ["g1f3", "e7e5", "f3e5", "g8e7", "e5d7", "e7c6", "d7b8", "c6b8"])))
# KQRRBBNPPPPPPPPkqrrbbnpppppp

```

## Potential clarifications

* Pieces with the same name and color, such as the two white rooks, are indistinguishable. That is, you need not ensure that the a1 rook specifically be killed.
* The input format is quite flexible. If you wish to have the black pieces before the white, or the pieces in alphabetical order, you're welcome to.
* The output games need not be the simplest or shortest possible in any sense; they must merely be legal. Intricacies like the fifty-move/seventy-five-move rule, draw by threefold/fivefold repetition, and insufficient material may be ignored. Key rules like *check*, *checkmate*, and *stalemate* may not be ignored.
* The output game need not terminate with mate. It can just end after an arbitrary move.
* You *may* use chess libraries available in your language or platform.

# Answer
> 9 votes
# JavaScript (ES10),  ~~499~~  450 bytes

Expects `[[q,r,b,n,p], [Q,R,B,N,P]]`, where each variable is the number of missing pieces. Returns an array of strings in standard algebraic notation.

```
M=>M.map((a,w)=>a.map(h=(v,i)=>v--?[(q=[...'002//2770/222/2772/220/000//27n0/0n02/b77/277b/20/2n22/b7b/b0b'.split`/`[i*2+v]].map(d=>"abcdefgh"[y=(s+=parseInt(d,36)-17)>>3,s%8]+(w?1+y:8-y),s=52),c=q.pop())?[...q,"x"+c,q.reverse(),w?'e7':'e2']:q,h(v,i)]:[]).flat(10).map((s,i)=>o+=w?(i&1?"Ne2N":"Ng1N")+s:"N"+s+(i&1?S:"Ng8")),o=S="Ne7")&&`a3a6c4c5e3e6g4g5h3h6Ne2${o}Ng3Ng6Nf5Nf4${b=M[1][3]>1?'Ne2Kxe2':'',M[0][3]>1?S+b+`Kxe7`:'Ng3'+b}`.split(/(?<=\d)/)

```

Try it online!

### How?

1. We first play **1. a3 a6 2. c4 c5 3. e3 e6 4. g4 g5 5. h3 h6 6. Ne2 Ne7**:
2. The White king's knight follows some pre-computed paths to capture each Black piece except the Black king's knight, avoiding the squares **c7**, **d6**, **f6** and **g7** that would put the Black king in check. It also avoids **c3**, because **Nc3** would be ambiguous. It goes back to **e2** after each capture. Meanwhile, the Black king's knight moves back and forth between **e7** and **g8** and ends up on **e7**.

For instance, to capture the queen: **7. Nd4 Ng8 8. Nc6 Ne7 9. Nxd8 Ng8 10. Nc6 Ne7 11. Nd4 Ng8 12. Ne2 Ne7**
3. We do the same thing with the Black king's knight.
4. We play **Ng3 Ng6** / **Nf5 Nf4**:

**Note:** All pieces are shown in the above diagram, but only the kings and the king's knights are guaranteed to still be on the board at this point.
5. White play **Ne7** if the White king's knight has to be captured, or **Ng3** otherwise. This is followed by **Ne2 Kxe2** if the Black king's knight has to be captured. Finally, Black play **... Kxe7** if the White king's knight has to be captured.

<sub>*Images generated with www.365chess.com.*</sub>

# Answer
> 4 votes
# Python 3.7+, 299 bytes

Expects a dictionary like `{'K': 1, 'Q': 1, 'R': 2, 'B': 2, 'N': 2, 'P': 6, 'k': 1, 'q': 1, 'r': 2, 'b': 2, 'n': 2, 'p': 5}` indicating how many of each piece should remain at the end of the game. Outputs a game in standard algebraic notation, complete with move numbering, like `1. d4 a6 2. g4 a5 3. c3 d5 4. Bd2 f6 5. c4 e5 6. b4 Nc6 7. e3 Nge7 8. f4 Bxg4 9. Bd3 b6 10. Qc2 Ng6 11. fxe5 Qe7 12. exf6 dxc4 13. Nc3 Rg8 14. Bxc4`.

Obeys the trickier rules of chess, including the 75-move rule, repetition, and insufficient mating material. On average, takes approximately one second per desired material content on my computer; I have checked all possible inputs.

```
from chess import*
from random import*
S=Board
def f(t):
 seed(0);b=S()
 while 1:
  for m in choices([*b.legal_moves],k=9):
   b.push(m)
   if max(d:=[str(b).count(x)-t[x]for x in t])<1:return S().variation_san(b.move_stack)
   if b.is_game_over()+b.is_check()-min(d)<1:break
   b.pop()
  else:b=S()

```

## How?

Beginning at the starting position , we randomly play moves. A move is not played if it results in too few of a desired piece on the board. (That is, we pick another random move instead, up to nine times before giving up.) A move is also not played if it results in check or any game-ending condition (checkmate, stalemate, draw by 75-move-rule, etc), except on the final move. Promotions are played occasionally, just like any other move, if the pawn is not necessary for the desired material content. There is no backtracking of individual moves beyond this "one move lookahead" mentioned already; in the event of failure, we restart from the beginning with a fresh starting board and fresh random moves.

The function is deterministic because we explicitly set the seed to 0. As a result, most of the games begin exactly the same, differing only when a capture is or is not allowed to be made, or when the entire attempt is a failure and we have to start over.

*PS*. When I started working on this challenge, I planned on a knight-based approach like Arnauld's. I didn't know whether random would work out, but I'm glad it did!

## Example games

* Kk: Reaching King versus king takes 166 moves and features 3 promotions, to two white rooks and a black bishop.
* KBkqrr: Features 6 promotions (to `RRnbNQ`) in 282 moves ending in check.
* KRNPPPk: Three promotions to black queens. White ends with three pawns on the seventh rank, but doesn't promote any because they're part of the desired material content.
* KQRRBNNPPPPPPPkrbnppppp: Mate in 42.
* KQBNNPPPPkqrbppppppp: Features capture en passant on move 21.
* KQRRBNNPPPPPPPPkrrbnppppppp: Both sides castle, consecutively but in opposite directions.
* KQRRBBNNPPPPPPPkrnnppp: Knight delivers mate.

---
Tags: code-golf, chess
---


title: Animal-Alphabetical Sequence

text:
# Question
Title: Animal-Alphabetical Sequence
The Animal-Alphabetical Sequence is an infinite string of letters built accordingly to the following procedure:

1. Start with the letter `A`;
2. Replace each letter with the name of the animal starting with such letter in the table below;
3. Go back to step 2.

For instance, the first four steps of the procedure give:

* `A`
* `ADDAX`
* `ADDAXDINGODINGOADDAXXERUS`
* `ADDAXDINGODINGOADDAXXERUSDINGOINDRINYALAGECKOOTTERDINGOINDRINYALAGECKOOTTERADDAXDINGODINGOADDAXXERUSXERUSEAGLEROBINURIALSQUID`

Note that the string obtained at each step is a prefix of the string obtained at the next step. Hence, the procedure does indeed converge to a well-defined infinite string:

`ADDAXDINGODINGOADDAXXERUSDINGOIND...`

# The Challenge

Write a function that takes as input an integer `n` in the range `[0, 2^31 - 1]` and returns as output the `n`-th letter of the Animal-Alphabetical Sequence.

# Notes

* The first letter is the `0`-th.
* Letters can be uppercase or lowercase.
* It must be possible to run the program in the Try It Online interpreter and get the result in at most 5 minutes.

# Test Cases

```
1511763812 -> M
1603218999 -> I
2049234744 -> X
2060411875 -> K
2147483647 -> D

```

# Table of Animal Names

```
ADDAX
BISON
CAMEL
DINGO
EAGLE
FOSSA
GECKO
HORSE
INDRI
JAMBU
KOALA
LEMUR
MOUSE
NYALA
OTTER
PRAWN
QUAIL
ROBIN
SQUID
TIGER
URIAL
VIXEN
WHALE
XERUS
YAPOK
ZEBRA

```

# Answer
> 4 votes
# Charcoal, 83 bytes

```
≔AηＦ↨Ｎ⁵≔§⁺η§⪪”$⌊∧Ｘ;F‖ρ=ＪD θ⊘⊙～'ΣV⦄Ｋ◨｜]≕‖◨⟧TJρ¿¿C´!⁸⁶S/Ｕ¶V×Ｗ⧴a“,=6；‴*Þ↓h!�{≦”⁴⌕αηιηη

```

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

```
≔Aη

```

Start with `A` at the `0`th index.

```
Ｆ↨Ｎ⁵

```

Input `n`, convert it to base 5 and loop over the digits.

```
≔§⁺η§⪪”...”⁴⌕αηιη

```

Get the current animal from the compressed string of all animal suffixes (excluding `EBRA`) and lookup the appropriate letter from the current digit.

```
η

```

Output the final letter.

# Answer
> 3 votes
# JavaScript (Node.js), 168 bytes

```
n=>[...n.toString(5)].reduce((c,k)=>'DIAIA-EON-OEOYTRUOQIR-HEADSMNG-CRD-AMUATAABUGI-ARPAOEGL-KSR-LUSLEWIIIEA-LUOXNLOE-OEI-AREARNLNDRL-ESK'[Buffer(c)[0]-90+k*25]||c,'A')

```

Try it online!

### How?

The lookup string (let's call it `S`) is built as 4 sub-strings of 25 characters as follows:

```
ABCDEFGHIJKLMNOPQRSTUVWXY
-------------------------
DIAIA-EON-OEOYTRUOQIR-HEA  --> 2nd letter of each word
DSMNG-CRD-AMUATAABUGI-ARP  --> 3rd letter of each word
AOEGL-KSR-LUSLEWIIIEA-LUO  --> 4th letter of each word
XNLOE-OEI-AREARNLNDRL-ESK  --> 5th letter of each word

```

Therefore:

```
S[Buffer(c)[0] - 90 + k * 25] // equivalent to S[Buffer(c)[0] - 65 + (k - 1) * 25]

```

is undefined if `k = 0`, in which case we leave `c` unchanged as expected (the first letter of the word that starts with `c` is `c`).

# Answer
> 3 votes
# Haskell, ~~170~~ 162 bytes

*Thanks to AZTECCO for helping me index the lookup shorter*

```
f 0='A'
f n|x<-f$div n 5=(x:drop(4*length['B'..x])"DDAXISONAMELINGOAGLEOSSAECKOORSENDRIAMBUOALAEMUROUSEYALATTERRAWNUAILOBINQUIDIGERRIALIXENHALEERUSAPOK")!!mod n 5

```

Try it online!

This exceeds TIO's output capacity nearly instantly, so I think this is safe on timing. My quick analysis tells me the algorithm should be \\$O(n)\\$. That is if you input a number of length \\$n\\$ bits it should take about the \\$n\\$ time to find the answer.

I'm not the best at golfing data encoding so I think that is where I am losing the most bytes.

This gets a lot easier to read if we just say we have a function `u` which gives the word for a letter. Then it is:

```
f 0='A'
f n=u(f$div n 5)!!mod n 5

```

# Answer
> 3 votes
# Python ~~3~~ 2, ~~160 159~~ 158 bytes

```
s="ABCDEGHIKLMNOPQRSTUWXYDIAIAEONOEOYTRUOQIRHEADSMNGCRDAMUATAABUGIARPAOEGLKSRLUSLEWIIIEALUOXNLOEOEIAREARNLNDRLESK"
f=lambda n:s[n and s.find(f(n/5))::22][n%5]

```

Try it online!

*-1 thanks to @ovs*

# Answer
> 2 votes
# 05AB1E, ~~78~~ 77 bytes

```
'aI5вvA…fjvмSD.•13ôºå}Æ ë¾‚pu®×ÌмĀαù·o×#·Îg4™Ā8%+ÚONp:rƒÜ∊₁Œ¿ÝøuÏādûá•4ôøJ‡yè

```

-1 byte thanks to *@Arnauld*.

Output in lowercase.

Try it online or verify all test cases.

**Explanation:**

```
'a             '# Push string "a"
  I             # Push the input-integer
   5в           # Convert it to base-5 as list
     v          # Loop `y` over each digit in this list:
      A         #  Push the lowercase alphabet
       …fjvм    #  Remove the letters 'f', 'j', and 'v'
            S   #  Convert it to a list of characters
             D  #  Duplicate this list
      .•13ôºå}Æ ë¾‚pu®×ÌмĀαù·o×#·Îg4™Ā8%+ÚONp:rƒÜ∊₁Œ¿ÝøuÏādûá•
                #  Push compressed string "ddaxisonamelingoagleeckoorsendrioalaemurouseyalatterrawnuailobinquidigerrialhaleerusapok"
        4ô      #  Split the string into parts of 4 characters
          ø     #  Create pairs with the alphabet-list (the trailing 'z' is ignored)
           J    #  Join each pair together to a single 5-char string
            ‡   #  Transliterate the current character to the animal name
                #  (again ignoring the trailing 'z')
             yè #  And index digit `y` into this string for the next iteration
                # (after the loop, the resulting character is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•13ôºå}Æ ë¾‚pu®×ÌмĀαù·o×#·Îg4™Ā8%+ÚONp:rƒÜ∊₁Œ¿ÝøuÏādûá•` is `"ddaxisonamelingoagleeckoorsendrioalaemurouseyalatterrawnuailobinquidigerrialhaleerusapok"`.

# Answer
> 2 votes
# Perl 5, 175 bytes

```
sub f{my$n=pop;$_=substr$n?f(1,$n/5):ADDAX,$n%5,1;@_?$_.[DDAXISONAMELINGOAGLE_ECKOORSENDRI_OALAEMUROUSEYALATTERRAWNUAILOBINQUIDIGERRIAL_HALEERUSAPOK=~/_|.{4}/g]->[-65+ord]:$_}

```

Try it online!

Somewhat ungolfed. Added whitespace and moved dictionary string into variable $animals:

```
sub f {
  $animals='DDAXISONAMELINGOAGLE_ECKOORSENDRI_OALAEMUROUSE'
          .'YALATTERRAWNUAILOBINQUIDIGERRIAL_HALEERUSAPOK';
  my $n=pop;                          #arg
  $_=substr                           #put letter into $_
    $n ? f(1,$n/5) : ADDAX,           #next word is word at n/5 or first word
    $n%5,1;                           #get letter at pos n%5 of word
  @_                                  #if recursed ...
  ?$_.[$animals=~/_|.{4}/g]->[-65+ord]#then return letter + its 4 letters in dict
  :$_                                 #else return just letter
}

```

About runtime: on my "vintage" laptop the five test cases spends about 0.025 sec in total. If I change `$n/5` into `int$n/5` this is reduced to 0.0016 sec (because then it doesn't need to keep dividing by 5 until the decimals disappears, thus far fewer recursions)

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), ~~254~~ ~~234~~ ~~230~~ ~~229~~ ~~228~~ ~~209~~ ~~199~~ 198 bytes

```
string f(int v,int p=-1){var h=v>-p?f(v/5,v%5):"ADDAX";return p<0?h[..1]:h[p]+"DDAXISONAMELINGOAGLEOSSAECKOORSENDRIAMBUOALAEMUROUSEYALATTERRAWNUAILOBINQUIDIGERRIALIXENHALEERUSAPOK"[(h[p]*4-260)..];}

```

Try it online!

**How?**

```
char f(int v, int p = -1)
{
    var h = v > -p ? f(v / 5, v % 5) : "ADDAX";
    return p < 0 ? h[..1] : h[p] + "DDAXISONAMELINGOAGLEOSSAECKOORSENDRIAMBUOALAEMUROUSEYALATTERRAWNUAILOBINQUIDIGERRIALIXENHALEERUSAPOK"[(h[p] * 4 - 260)..];
}

```

This version is a complete rewrite of my original solution. Inspired from other submissions, I decided to use a recursive function. The gist is still converting `v` to base 5 and use the digits to point to the correct words. When `v` and `p` are both equal to 0, the conversion is complete, so we take `ADDAX` and stop the recursion.

`Zebra` was removed from the list because it is not reachable.

Updates:

* Saved 20 bytes removing the first letter from each word in the string literal.
* Replacing `do/while` with a `for` loop reduced the size by 4 bytes
* -1 byte using a tuple to assign `b` and `g`
* -1 byte replacing 'A' with 65
* -1 byte replacing `[((h[b] - 65) * 4)..]` with `[(h[b]*4 - 260)..]`
* -10 bytes using a recursive function
* -1 byte replacing `v+p>0` with `v>-p` (thanks to @ceilingcat)

# Answer
> 1 votes
# Julia 1.0, 153 bytes

```
f(n)=*('A':'Y'...,"DIAIAOEONAOEOYTRUOQIRIHEADSMNGSCRDMAMUATAABUGIXARPAOEGLSKSRBLUSLEWIIIEAELUOXNLOEAOEIUAREARNLNDRLNESK")[n<1||f(n÷5)-'@':25:end][1+n%5]

```

Try it online!

# Answer
> 1 votes
# PowerShell, 185 182 179 177 174 173 Bytes

-1 byte thanks to mazzy!

```
for($f=[char]65;!($x=$f[$args])){$f=$f|%{,$_+"DDAXISONAMELINGOAGLEOSSAECKOORSENDRIAMBUOALAEMUROUSEYALATTERRAWNUAILOBINQUIDIGERRIALIXENHALEERUSAPOK"[($i=$_%65*4)..($i+3)]}}$x

```

Could probably be shortened, but I got stumped. If 0 can be ignored as an input, you can drop the \[char\] in \[char\]65 to save 4 bytes.

---
Tags: code-golf, string, restricted-time, substitution
---


title: Is my OS 32-bit or 64-bit?

text:
# Question
Title: Is my OS 32-bit or 64-bit?
It's not too important anymore, but occasionally somebody needs to know.

Here is a simple golf: Taking no user input, tell me if the computer on which the code is run is on a 64-bit operating system, or a 32-bit operating system!

If the code is run on a 32-bit operating system, print "32", if the code is run on a 64 bit operating system, output "64". **Important:** Print any other non-empty string of alphanumeric characters if it's neither 32 or 64 bit.

Please note that a 32 bit program running on a computer with a 64 bit operating system should output "64". You can assume that users will use 64 bit software whenever possible.

To be eligible for entry, your code must be able to run on ~~Windows 4.10 or newer~~ Microsoft supported Windows systems, and at least one flavor of Linux of your choosing (so long as that flavor is gratis). Compatibility mods can be installed, so long as the program still returns the right value.

The usual rules apply.

Note: If your answer is only meant to print out 32 or 64, but not the alt case, I'll accept it, but it is not a competing answer.

I'll try and post some results of running these codes on different OSes later!

# Answer
> 45 votes
# x86 Assembly (polyglot), 13 bytes

Bytecode:

```
31 c0 b4 80 48 70 05 04 40 83 e0 60 c3

```

Defines a function which returns 32 if interpreted as 32-bit, 64 if 64-bit, and 32767 if 16-bit.

I wanted to make a polyglot which ran on Windows and Linux, but this is a lot harder than I thought. As it is I'm not sure there's even any way to print a value on non-16-bit Windows without linking.

## Explanation

This code uses two tells to determine the architecture it is running on. The first is the instruction 0x48—on 16 and 32 bits, this is `dec %eax`, but on 64 bits, it is an instruction-size prefix. The second tell is the same instruction, however, when we execute it on the value 0x8000, the most significant bit is flipped only if the register size is 16 bits, setting the overflow flag and letting us use `jo`.

In 16 bits, this code is interpreted as the following:

```
   0:   31 c0                   xor    %ax,%ax    /* 0x0000 */
   2:   b4 80                   mov    $0x80,%ah  /* 0x8000 */
   4:   48                      dec    %ax        /* 0x7fff */
   5:   70 05                   jo c              /* taken  */
   7:   04 40                   add    $0x40,%al
   9:   83 e0 60                and    $0x60,%ax
   c:   c3                      ret               /* 0x7fff */

```

In 32 bits, this code is interpreted as the following:

```
   0:   31 c0                   xor    %eax,%eax   /* 0x00000000 */
   2:   b4 80                   mov    $0x80,%ah   /* 0x00008000 */
   4:   48                      dec    %eax        /* 0x00007fff */
   5:   70 05                   jo c               /* not taken  */
   7:   04 40                   add    $0x40,%al   /* 0x00007f3f */
   9:   83 e0 60                and    $0x60,%eax  /* 0x00000020 */
   c:   c3                      ret

```

In 64 bits, this code is interpreted as the following:

```
   0:   31 c0                   xor    %eax,%eax   /* 0x00000000 */
   2:   b4 80                   mov    $0x80,%ah   /* 0x00008000 */
   4:   48 70 05                rex.W jo c         /* not taken  */
   7:   04 40                   add    $0x40,%al   /* 0x00008040 */
   9:   83 e0 60                and    $0x60,%eax  /* 0x00000040 */
   c:   c3                      ret

```

# Answer
> 48 votes
# x86 machine code, 12 bytes

```
8c c8 83 f8 23 b0 20 75 02 00 c0 c3

```

Ungolfed:

```
getKernelBitness:
    mov eax,cs
    cmp eax,0x23 ; 32 bit process on 64 bit kernel has this selector in CS
    mov al,32
    jne kernelIs32Bit
    add al,al    ; return value in eax
kernelIs32Bit:
    ret

```

This function works in Linux when used in ELF32, following i386 SysV ABI, as well as in Windows/Wine when used in PE32, following `stdcall` calling convention.

# Answer
> 33 votes
# Mathematica, 17 bytes

```
$SystemWordLength

```

# Answer
> 22 votes
## Julia ~~14~~ 13 bytes

```
n->8sizeof(1)

```

Explain:

* Anon function, taking anything (including `nothing`) returning an integer 32, or 64
* Integer literals are of type `Int` which depending if 32 bit or 64 bit, is either an `Int32` or an `Int64` (the `1` could be any digit)
* placing a number before a function call does a juxtaposition multiplication
* This is basically a minified version of the code for `Sys.WORD_SIZE`, used in rahnema1's answer

Other fun answer is `()->"$(Int)"[4:5]`, but I can't get the count down on that one.

---

-1 thanks to @Roman Gräf

# Answer
> 21 votes
# Boot Loaders

Did you know that GRUB and IPXE both have Turing complete programming languages accessible at run-time? The Syslinux family of boot loaders don't but they can do this.

## IPXE, 36 bytes

```
#!ipxe
cpuid --ext 29 && echo 64 || echo 32

```

the first line is needed if the script is run remotely, but not if typed directly at the command line.

## GRUB, 42 bytes

```
if cpuid -l ; then
echo 64
else
echo 32
fi

```

## Syslinux, 186 bytes

This takes three files the first is syslinux.cfg (or isolinux.cfg, etc.).

```
label a
  kernel ifcpu64.c32
  append s -- t

label s
  kernel menu.c32
  append s.cfg

label t
  kernel menu.c32
  append t.cfg

default a
prompt 0
timeout 0

```

and t.cfg

```
menu title 32

```

ans s.cfg

```
menu title 64

```

For this one the hard part is that syslinux does not have any simple text display capabilities, so the menu is abused.

# Answer
> 19 votes
# julia, ~~20~~ ~~17~~ 16 bytes

```
n->Sys.WORD_SIZE

```

\*Thanks to @LyndonWhite saved 3 bytes \*Thanks to @RomanGräf saved a byte

Previous answers:

```
()->Sys.WORD_SIZE
print(Sys.WORD_SIZE)

```

Try it online!

# Answer
> 14 votes
## JavaScript (Node.js), 24 bytes

```
_=>process.arch.slice(1)

```

This is a function and returns `'32'`, `'64'`, or if neither `'rm'`.

# Answer
> 13 votes
# C, ~~33~~ ~~31~~ ~~29~~ 23 bytes

```
f(){return sizeof&f*8;}

```

Thanks to commenters @ceilingcat and @Dennis for golfing tips!

# Answer
> 10 votes
## Python 2, 52, 48, 42 41 bytes

```
from struct import*;print calcsize("P")*8

```

Thanks to totallyhuman!

# Answer
> 10 votes
## Java 8, 45 bytes

```
()->System.getProperty("sun.arch.data.model")

```

# Answer
> 10 votes
## PowerShell, 16 bytes

```
8*[IntPtr]::Size

```

Gets the pointer size in bytes, multiplies by 8 to get bits.

# Answer
> 9 votes
# Perl 6, 17 bytes

```
say $*KERNEL.bits

```

Try it

---

There is a related `$?BITS` which contains the number of bits that a native `int` has in the runtime.

```
say $?BITS

```

Try it

# Answer
> 8 votes
# Windows CMD, 56 52 bytes (thanks Bob!)

```
if EXIST "%ProgramFiles(x86)%" (echo 64)else echo 32

```

Still surprisingly lengthy - longest so far!

# Answer
> 7 votes
# Ruby, 22 bytes

```
p [?a].pack(?p).size*8

```

`["any string"].pack("p")` returns a string whose bytes correspond to the pointer that pointed towards `"any string"`, and is 8 characters if the OS is 64-bit, or 4 characters if the OS is 32-bit.

# Answer
> 7 votes
# C#, 60 50 bytes

```
_=>System.Environment.Is64BitOperatingSystem?64:32

```

Thanks @TheLethalCoder

# Answer
> 7 votes
# C, Win32 API, 103 183 bytes

```
#include <windows.h>
typedef int(WINAPI*F)(HANDLE,int*);b;main(){F f=GetProcAddress(GetModuleHandle("kernel32"),"IsWow64Process");return(f!=0&&f(GetCurrentProcess(),&b)&&!b)?32:64;}

```

Actually there are more than 2 cases here. Let's examine them

* The easiest: `IsWow64Process` does not exist: We are on a 32 bit OS

For the next two cases we need to have the knowledge that our binary will be a 32 bit executable. And this description of what will be out into the **out** parameter of `IsWow64Process`

> A pointer to a value that is set to TRUE if the process is running under WOW64. If the process is running under 32-bit Windows, the value is set to FALSE. If the process is a 64-bit application running under 64-bit Windows, the value is also set to FALSE.

That leaves us with two additional cases:

* `IsWow64Process` exists, and yields TRUE -\> We are on a 64 bit machine
* `IsWow64Process` exists, and yields FALSE -\> We are on a 32 bit machine

We don't wory about the part where a 64-bit application on a 64-bit Windows yields FALSE. As we *know* that our application is 32-bit

Oh and there is one additional case that is not covered by this challenge and should be rare anyways:

* IsWow64Process exists, but it fails: We default to 32-bit machine.

This should cover most Windows NT Operating Systems. Have only tested on Win10 64-Bit, Win 7 64-Bit, Win 8.1 32-Bit and WinXP SP1 32-Bit

---

Original answer:

```
#include<windows.h>
main(){return GetProcAddress(GetModuleHandle("Kernel32"),"IsWow64Process")?64:32;}

```

To be sure we need to distinguish only 2 cases

* `IsWow64Process` does not exist in kernel32.dll =\> We are on a 32 bit machine.
* `IsWow64Process` does exist =\> We are on a 64 bit machine.

The actual value provided by `IsWow64Process` is irrelevant for this challange, since we want the binary to be 32bit in any case.

Unlike most of the answers, this doesn't rely on the binary itself being compiled on the machine that it's executed on.

If I knew a shorter function that is present only on 64bit and not 32bit machines, I could shorten the answer.

# Answer
> 6 votes
## R, 16 bytes

```
.Machine[[18]]*8

```

Returns the pointer size.

# Answer
> 6 votes
## Perl, ~~18~~ ~~15~~ 18 bytes

```
say length pack p8

```

# Answer
> 6 votes
# PHP, 18 Bytes

```
<?=PHP_INT_SIZE*8;

```

This correctly handles all of the cases of 32, 64 and other bit CPUs provided that PHP\_INT\_SIZE is correct, it will show the precise size of the CPU no matter what CPU PHP is running on!

If PHP is running on

32-bit OS PHP\_INT\_SIZE == 4,

64-bit OS PHP\_INT\_SIZE == 8,

16-bit OS PHP\_INT\_SIZE == 2 (theoretically)

8-bit OS PHP\_INT\_SIZE == 1 (again theoretically)

128-bit OS PHP\_INT\_SIZE == 16 (Not yet achieved but possible)

# Answer
> 6 votes
# x86 machine code, 8 bytes

```
31 C0 B0 40 48 24 60 C3

```

Ungolfed:

```
31 c0    xor eax,eax
b0 40    mov al, 0x40
48       dec al — in 32-bit mode; "REX.W" in 64-bit mode (ignored)
24 60    and al, 0x60
c3       ret

```

If compiled as a 64-bit executable, it returns 64 in `eax`, and if compiled as 32-bit, then returns 32 — regardless of the OS.

This answer relies on the rules saying:

> You can assume that users will use 64 bit software whenever possible.

# Answer
> 4 votes
# Shell, 26 bytes

```
uname -m|awk \$0=/_/?64:32

```

# Answer
> 4 votes
# C, 22 bytes

```
f(){return(int**)0+8;}

```

This is a pointer-size based answer that assumes a native binary. The `0` is cast to `int**` (address `0x0`). Then we add 8 to 0, which, in C advances, the pointer by `sizeof(int*)*8`. 4 bytes * 8 bits = 32, 8 bytes * 8 bits = 64. So we get `(int**)0x20` and `0x40` which are then implicitly cast as integers by returning them from an implicitly `int`-returning function.

# C, stand-alone, 34 bytes

```
main(){printf("%d\n",(int**)0+8);}

```

# C, fun with Unicode, 30 code-points, 34 bytes(UTF-8)

```
main(){puts((int**)U" ㈳㐶"+1);}

```

# Answer
> 4 votes
**C# (29 bytes)**

```
Console.Write(IntPtr.Size*8);

```

# Answer
> 4 votes
# PowerShell, ~~17~~ 52 bytes

```
try{32+32*((gci \*`))-or(arch)[-1]-eq52)}catch{32}

```

Returns 64 if either of the following is true:

* You have a directory on your current drive with a filename ending in a close paren, the idea being to detect `Program Files (x86)`.
* `arch` returns a string ending in `4` (ASCII 52), like `x86_64`, as opposed to e.g. `i686`.

The try-catch is intended to circumvent the error you get if *gci* returns nothing and you don't have an *arch*. I haven't found a shorter way to do it so far. *gci* is used over *ls* because on Linux, *ls* will produce a visible error.

This version should detect whether the OS is 64-bit rather than just PowerShell, and is tested to work on Windows and Linux. For Mac support, replace `arch` with `uname -m`.

Previous Windows-only version: `-!(ls \*`))*32+64`

# Answer
> 4 votes
# Swift 4 REPL/Playground, 12 bytes

```
Int.bitWidth

```

`Int` is word sized, acting like either `Int32` or `Int64` depending on the system.

# Answer
> 4 votes
# Ruby, 10 bytes

```
p 0.size*8

```

While Ruby can use integers of any length, internally it stores the values that fit in a machine word as `Fixnum`. The method `Fixnum#size` always return the length in bytes of a machine word.

The `Fixnum` class was removed in Ruby 2.4.0, its functionality was included in class `Integer`. The code stands.

# Answer
> 4 votes
# Bash, 25 17 bytes

```
getconf LONG_BIT

```

Thanks to Dennis for golfing help.

# Answer
> 3 votes
# Java, 50 bytes

```
int b(){return com.sun.jna.Native.POINTER_SIZE*8;}

```

---

# Answer
> 3 votes
# PHP, 29 bytes

```
<?=@php_uname(m)[-1]-4?32:64;

```

https://3v4l.org/Y6JXv

# Answer
> 3 votes
# Python 3, 77 84 71 59 bytes

-13 bytes, thanks to @JonathanAllan!
Down to 59 by @Clearer

```
from platform import*;print({'4':64,'6':32}[machine()[-1]])

```

Try it online!

My fist time code-golfing :)
Should output the correct version even when running 32Bit-Python on 64bit-OS.
Assuming `platform.machine()` gives `i*86` or `x86` for 32Bit-OS. I don't have one available to check this. Output is `0` when OS is not in 64/32Bit
Edit: Added print statement, so it got 7 bytes longer

# Answer
> 3 votes
# C, 36 bytes

Note that the following program will need to be compiled on the system to be tested.

```
main(){printf("%u",8*sizeof(int*));}

```

Simple. Assumes that the machine's word length is the same as the pointer size, which seems to be a valid assumption.

`sizeof(int*)` (or any other pointer type, for that matter), should be `4` on a 32-bit system, and `8` on a 64-bit one (and `2` on a 16-bit system). This should also the be the most portable of all the solutions given here till now - and work back to any system with a ISO C89 compiler.

The gotcha here is that this program must be compiled for every system which it needs to be run on, otherwise it'll output the bitness of the operating system it was compiled on.

# Answer
> 3 votes
# J, 8 bytes

```
2^5+IF64

```

Alternatively, from the metal up (as opposed to using built-ins), 23 bytes:

```
2^5+1<224-~a.i.{.3!:1''

```

Based on the approach in the relevant RosettaCode task, as well as the underlying J documentation.

A version which would work on the theoretical, non-existent 16\- or 128-bit J interpreters, provided they use the same code base, 11 bytes:

```
>:2^.|{.i:_j1

```

This works in both the real-life 32\- and 64-bit J interpreters, and is a function of the implementation, not the specification.

# Answer
> 2 votes
# tcl, 40

```
puts [expr 8*$tcl_platform(pointerSize)]

```

# demo

I think I can golf it using some bit-shift magic

# Answer
> 2 votes
# Batch, ~~54 53~~ 51 bytes

Not the shortest.

```
@if defined ProgramFiles(x86) (echo 64)else echo 32

```

This checks for a 64-bit system only variable. If the variable exists, then return 64. In any other case, it returns 32.

To make this work on Linux(assuming Ubuntu):

* Install `wine` using `sudo apt-get install wine`
* Run `wine cmd` in the terminal
* Call the script: `scriptname.bat`

# Answer
> 2 votes
# PHP, 25 Bytes

```
<?=PHP_INT_SIZE==4?32:64;

```

# Answer
> 2 votes
# Javascript (ES6), ~~46~~ ~~41~~ ~~40~~ 38 Bytes

-5 Bytes thanks to @GustavoRodrigues

-2 Bytes thanks to @GustavoRodrigues!

```
_=>/64/.test(navigator.userAgent)+1<<5

```

I was only able to test it on my Windows x64 machine, so any feedback will be much appreciated :)

Edit: removed the `x` from `x64` to fix an issue pointed out by @ThomasAyoub, I don't know if this is going to cause any unexpected behaviour.

```
var c=
_=>/64/.test(navigator.userAgent)+1<<5

console.log(c());
```

# Answer
> 2 votes
# Java 7, ~~77~~ 71 bytes

A java pointer-size solution

```
void a(){System.out.print(Integer.toHexString(hashCode()).length()*8);}

```

# Answer
> 2 votes
## x86 machine code, 8 bytes

Bytecode:

`b0 40 33 c9 41 d2 e8 c3`

which decodes to:

```
mov al, 64
xor ecx, ecx
inc ecx
shr al, cl
ret
```

The "inc ecx/shr al,cl" in 32-bit becomes "shr r8b,cl" in 64-bit, and returns either 32 or 64 in the AL register.

# Answer
> 2 votes
# PowerShell, ~~51~~ ~~44~~ 43 bytes

-7 bytes thanks to Wasif Hasan

```
32+32*[Environment]::Is64BitOperatingSystem

```

Try it online!

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

Runs on Windows NT/CE, Linux, AIX, macOS and Solaris. Assumes exposure of root properties.

```
32×1+'6'∊⊃APLVersion

```

Try it online!

`APLVersion` (Target Environment, Version Number, Version Type, Program Type)

pick the first element (OSName\[-64\])

`'6'∊` is six a member thereof?

`1+` add one to that Boolean

`32×` multiply 32 by that

---

If root properties are not exposed, use `⎕WG'APLVersion'` instead of `APLVersion`.

# Answer
> 1 votes
## SAS, 28

```
%put%eval(&syssizeoflong*8);

```

Runs on any OS that supports SAS - there are many...

# Answer
> 1 votes
# JavaScript, ~~26~~ 34 bytes

```
console.log((
_=>/\d\d/.exec(navigator.oscpu)[0]
)())
```

Tested with Firefox. Not all browsers support the `navigator.oscpu` property.

**Edit:** rewrote my answer to comply with the specification. Thanks to Restioson for pointing out my error.

# Answer
> 1 votes
# VB.NET (Mono), ~~99~~ 65 Bytes

Full subroutine and module which take no input and outputs if the OS is 64 bit or not to the console.

```
Module M
Sub Main
Console.Write(8*IntPtr.Size)
End Sub
End Module

```

Try it Online. *Returns 64 as TIO is run on a 64 Bit Unix 4.11.3.202 server*

-34 Bytes thanks to @Alexander

# VBA, 41 Bytes (Non-Competing)

Anonymous VBE immediate window function that takes no input and outputs OS Version to the VBE immediate window

*This only works on Windows as VBA cannot be run on Linux*

```
?Val(Mid(Application.OperatingSystem,10))

```

# Answer
> 1 votes
## TXR Lisp, 16 bytes

```
(*(sizeof val)8)

```

Same for `long` or `cptr` instead of `val`; but those are one character longer. `val` is the FFI type denoting a raw Lisp value. That corresponds to a pointer, whose size usually determines the "bitness" of a system.

# Answer
> 1 votes
# Go, 94 bytes

```
package main;import"fmt";const wordsize=32<<(^uint(0)>>32&1);func main(){fmt.Println(wordsize)}

```

# Answer
> 1 votes
# Python 2.7, 49 bytes

```
from platform import*;print architecture()[0][:2]

```

# Answer
> 1 votes
## Perl 6, 17 bytes

```
say $*KERNEL.bits

```

# Answer
> 1 votes
# Powershell, 56 bytes

```
$null=$env:Processor_Architecture-match"\d+";$matches[0]

```

# Answer
> 0 votes
# Powershell, 47 bytes

```
(32,64)[[Environment]::Is64BitOperatingSystem]

```

Basically, it's an array that's indexed into by the truthy value returned by the environment.

This avoids the pointer methods, so will correctly identify the bitness of the OS rather than the bitness of the process.

Appears to work on Windows and Linux.

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


title: Approximate the plastic number

text:
# Question
Title: Approximate the plastic number
# The challenge

The plastic number is a number related to the golden ratio, with many interesting mathematical properties. As such, there are many approaches that can be used to calculate the number.

In order to precisely specify the number for the purposes of this challenge, we'll use the following definition (although there are plenty of equivalent definitions, and you can use any definition you wish as long as it comes to the same number):

> The plastic number is a real number *ρ* such that *ρ*³=*ρ*+1.

Your challenge is to write a program or function which takes an integer *x* as input (with *x* \> 1), and produces an approximation to *ρ* as output, such that the larger the value of *x* gets, the closer the output gets to *ρ* (with at most finitely many exceptions; staying at the same value counts as "closer" for this purpose), and for any positive number *δ*, there's some input *x* to your program that produces an output that's within *δ* of *ρ*.

# Clarifications

* If you're outputting via a method that inherently outputs strings (e.g. the standard output stream), you can format output either in decimal (e.g. `1.3247179572`), or as a ratio of two integers with a `/` character between them.
* If you're outputting as a value within your programming language (e.g. returning from a function), it must be of a fixed-point, floating-point, or rational type. (In particular, you can't use data types that store numbers symbolically, unless they're used only to hold the ratio of two integers. So if you're using Mathematica or a similar language, you'll need to include the extra code to actually generate the digits of the output.)
* Your answer must work in a hypothetical variant of your language in which integers can be arbitrarily large, and memory (including stack) is unlimited. You may *not* assume that floating-point arithmetic in your language is arbitrarily accurate, but must instead use its actual accuracy (meaning that outputting a floating-point number is only going to be possible in languages where the accuracy of floating-point numbers can be controlled at runtime).
* *x* can have any meaning you want (so long as increasing it gives more accurate outputs). I imagine that most submissions will have it control the number of digits of output to produce, or the number of iterations of the algorithm used by your program to converge on the plastic number, but other meanings are acceptable.

# Testcase

Here are the first few digits of the plastic number:

```
1.32471795724474602596090885

```

More digits are available on OEIS.

# Victory condition

As usual for , shorter is better, measured in bytes. However, feel free to post answers even if they don't win, so long as they add something (e.g. a different language, or a different algorithm) to the existing answers.

# Answer
# Python 2, 49 bytes

```
n=x=input()
while n**3/x/x<n+x:n+=1
print n,'/',x

```

Try it online!

The idea is to express the `ρ` with `ρ³=ρ+1` as a fraction `n/x` whose denominator `x` is the input accuracy parameter. We take `(n/x)³=n/x+1` and clear denominators to get `n³=x²(x+n)`.

Since the LHS increases in `n` faster than the RHS, we can approximate the equality point `n` as the smallest with `n³≥x²(x+n)`. The code counts up `n` until this is the case, starting at `x` which is smaller.

A small byte save is to divide both sides by  to write `n³/x²≥x+n` (negated in the `while` condition). This is floor division in the code, but the fractional part lost is negligible.

A same-length alternative instead puts `x` as the numerator:

**Python 2, 49 bytes**

```
n=x=input()
while x**3/n/n<n+x:n-=1
print x,'/',n

```

Try it online!
> 10 votes

# Answer
# Mathematica, 20 bytes

```
#^3-#-1&~Root~1~N~#&

```

Mathematica's builtin `Root` function gives the solutions to a polynomial equation `f[x] == 0`.

### Explanation

```
#^3-#-1&~Root~1~N~#&
                   &  (* Function *)
#^3-#-1&              (* A pure-function polynomial, x^3-x-1 *)
        ~Root~1       (* Find the first root *)
               ~N~#   (* approximate to (input) digits *)

```

### Sample I/O

```
In[1]:= f=#^3-#-1&~Root~1~N~#&;
        f[1]

Out[1]= 1.

In[2]:= f[9]

Out[2]= 1.32471796

In[3]:= f[100]

Out[3]= 1.324717957244746025960908854478097340734404056901733364534015050302827851245547594054699347981787280

```
> 10 votes

# Answer
# Mathematica, 27 bytes

```
x/.Solve[x^3==x+1>2,x]~N~#&

```

*-1 byte from Martin*
*-2 bytes from ovs*

**input**

> \[27\]

**output**

> {1.32471795724474602596090885}
> 6 votes

# Answer
# sed, ~~67~~ 60 (59+1) bytes

```
s,^,1/1/1 ,
:;s,(1*/(1*)/(1*).*)1$,\2\3/\1,
t
s,(/1*).*,\1,

```

Try it online!

+1 for the `-E` flag (ERE instead of BRE). Input and output are both unary: input 11111 for x=5 e.g. Output is a fraction of two unary numbers: the aforementioned 11111 input yields output 11111/1111 (5/4 in decimal).

Approximates the plastic number as a fraction between to consecutive elements of the Padovan sequence.
> 6 votes

# Answer
## Mathematica, 27 bytes

```
Nest[(1+#)^(1/3)&,1,#]~N~#&

```

Uses a truncated approximation of the nested cubic radical form **³√(1+³√(1+³√(1+...)))**. While the output will always have *x-1* decimal places, the result is actually less accurate than that, because the expression converges more slowly than one digit per iteration (*x* is also used as the number of nested radicals that are computed). For example *x = 100* gives

```
_________________________________________________________________________
1.324717957244746025960908854478097340734404056901733364534015050302827850993693624204577670741656151

```

where the overlined part is correct.
> 5 votes

# Answer
# MATL (27 28 bytes)

```
7BG:"t@)y@Q)+h]tG3+)yG2+)/

```

My first solution (27 bytes)

Try it online!

It's certainly not optimal, I'm still getting used to MATL.

## Explanation:

I create a Padovan sequence up to input+3 then find the ratio of the last two numbers.

```
7B     % Turn 7 into binary to give 1 1 1
G:"    % For k=1:input do...
t@)    % Existing sequence member k
y@1+)  % Existing sequence member k+1
+h     % Add them together and concatenate to the sequence array
]      % End loop
tG3+)  % Final sequence member
yG2+)  % Second last sequence member
/      % Divide to approximate ρ

```

## Proper fraction output (35 bytes) (28 bytes, @Sanchises):

However, the first solution doesn't fulfill the need for arbitrary precision being the floating point limit of default MATL settings. So rather than adding several bytes to extend this precision, it's simpler to take the proper fraction route and write a fraction of the final two integers in the (N-1)th and Nth elements of the truncated Padovan sequence.

e.g "114/86"

7BG:"t@)y@1+)+h\]tG3+)V'/'YcyG2+)VYc

```
7BG:"t@tQh)sh]tJ)V47hyJq)Vh&

```

Courtesy of user @Sanchises. :)

Try it online!

## Non-iterative evaluation:

Notably, my shortest code for the 'exact' version is (23 bytes):

```
1-1h69X^12**108+1I/^6/s

```

Try it online!

...but doesn't give arbitrary precision. I wonder if anyone can adjust this to fulfill the rules (use the input etc) and still add less than 5 bytes? :P
> 4 votes

# Answer
# , ~~15~~ 14 bytes

```
²×3’
*3Ḥ‘÷Ç
Ç¡

```

Try it online!

### Algorithm

This uses rationals and Newton's method. Specifically, for input **x**, the first **x** iterations with starting value **x** are applied.

We're trying to find a specific root of the polynomial **p(t) = t³ - t - 1**. Newton's method achieves this by taking a starting value **t0** – sufficiently close to **ρ** – and recursively defining a sequence by
**tn+1 = tn \- p(tn) / p'(tn)**.

Since **p'(t) = 3t² -1**, we get
**tn+1 = tn \- (tn³ - tn \- 1)/(3tn² - 1) = (3tn³ - tn \- tn³ + tn \+ 1) / (3tn² - 1) = (2tn³ + 1) / (3tn² - 1)**.

Note that the initial approximation **x** gets progressively worse as **x** increases. While the output for **x = 3** is slightly less precise than the output for **x = 2**, since Newton's method converges quadratically to **ρ**, this shouldn't be an issue for large values of **x**.

### How it works

```
Ç¡    Main link. Argument: x

Ç¡    Call the second helper link x times, which initial argument x.

*3Ḥ‘÷Ç  Second helper link. Argument: t

*3      Compute t³.
  Ḥ     Unhalve; yield 2t³.
   ‘    Increment; yield 2t³+1.
     Ç  Call the first helper link with argument t.
    ÷   Divide the left result by the right one.

²×3’    First helper link. Argument: t

²       Compute t².
 ×3     Compute 3t².
   ’    Decrement; yield 3t²-1.

```
> 4 votes

# Answer
# Octave, 50 bytes

```
@(n)char(digits(n)*0+vpasolve(sym('r^3-r-1'))(1));

```

Try it online!

Defines an anonymous function, with`n` the desired number of digits of output.

This answer abuses that `digits` returns the current setting for the number of digits in variable precision arithmetic. This means we can just use it in an anonymous function without errors about 'Too many output arguments'.

Other than that, it's really straightforward: `vpasolve` is short for Variable-Precision Arithmetic Solve, with the precision set by the last call of `digits`. Since `vpa` is a Symbolic data type in Octave, which is banned per the spec, we just wrap the whole function in `char(...)` to get string output. Note that in `solve` and `vpasolve`, the `f==0` is implied, so `r^3==r+1` has been replaced by `r^3-r-1 (==0)`
> 4 votes

# Answer
# Julia 0.5,  ~~44~~  40 bytes

```
|(x,r=1)=x<1?r:~-x|big(2r^3+1)//(3r^2-1)

```

Uses rationals and Newton's method.

Try it online!
> 3 votes

# Answer
# APL (Dyalog Extended), 19 bytes

```
{{(⍺+⍵*÷3)*÷3}/⍵/1}

```

Try it online!

Uses the cube root approximation method, which very, very slowly creeps towards the value of the plastic number.

## Explanation

```
{{(⍺+⍵*÷3)*÷3}/⍵/1} ⍵ → input
               ⍵/1} replicate 1 ⍵ times
 {           }/     reduce by inner fn:
          *÷3       cube root of
     ⍵*÷3           cube root of right arg
   ⍺+               plus left arg

```
> 3 votes

# Answer
# Rust, 66 bytes

```
|n|{let mut i=(1,1,1);for _ in 0..n{i=(i.1,i.2,i.0+i.1)}(i.1,i.2)}

```

Try it online!

Uses the padovan sequence to approximate the plastic number. Returns a tupled `(num,denom)`. A readable version that works with arbitrary precision integers can be found here.
> 3 votes

# Answer
# AWK, 34 bytes

```
{for(;$1^3>$1+1;)$1=($1+1)^(1/3)}1

```

Step by step:

```
{                  # $1 is the input (a positive integer)
for(;$1^3>$1+1;)   # as long as $1 cubed is bigger than the input plus one
  $1=($1+1)^(1/3)  # assigns $1 this new value: cube root of $1 plus one
}
1                  # prints $1

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 23 bytes

```
U[X3m¹/¹/¹X+›#X>U]X'/¹J

```

Try it online!

---

Direct port of https://codegolf.stackexchange.com/a/126822/59376 by xnor.
> 1 votes

# Answer
# Charcoal, 28 bytes

```
ＡＩθθＡθνＷ‹∕∕Ｘν³θθ⁺νθＡ⁺ν¹νＩ∕νθ

```

Try it online! Link to verbose mode. Also I apparently messed up `Divide` and `IntDivide` :|
Uses the same method as the Python and JavaScript answers.
> 1 votes

# Answer
# NewStack, 14 bytes

```
¹Fᵢ{E2x³⁺÷3x²⁻

```

### Break down:

```
¹                Add arbitrary number 1 to the stack.
 Fᵢ{             Define for loop with a user's input amount of itterations.
    E            Define new edit for element 0 (element 0 being the 1 added. earlier).
     2x³⁺÷3x²⁻   update x to equal (2x^3+1)/(3x^2-1). (x = element 0).

```

### How it works:

The formula (2x3+1)/(3x2-1) comes from the simplification of Newton's method for the equasion x3=x+1. You can find it here. Repeating this process an infinite amoune of times converges to the plastic number. It's rate of convergence is rather quick at around 2.6 decimals per iteration.

```
INPUT ITERATION >> VALUE
0 >> 1
1 >> 1.5
2 >> 1.3478260869565217
3 >> 1.325200398950907
4 >> 1.3247181739990537
5 >> 1.3247179572447898
6 >> 1.324717957244746    <- 16 decimal precision in 6 iterations!
...
100 >> 1.324717957244746

```

# Padovan sequence alternative, 27 25 17 bytes

```
¹Fᵢ{[ƨ2+ƨ3]ℲƤƨ/ƨ2

```

### Break down:

```
¹                  Append first element of Padovan sequence.
 Fᵢ{       Ⅎ       Define for loop of user's input amount of iterations.
    [ƨ2+ƨ3]        Append sum second and third to last elements.
            Ƥƨ/ƨ2  Print ratio of last two elements.

```

-2 bytes by choosing better print strategy

-8 bytes by choosing better way to index stack

### How it works:

As the Padovan sequence continues, the ratio of the last two elements converge to the plastic number.

```
INPUT ITERATION >> VALUE
0 >> 1
1 >> 2
...
10 >> 1.3157894736842106
...
89 >> 1.324717957244746    <- 16 decimal precision in 89 iterations
...
100> > 1.324717957244746

```
> 1 votes

# Answer
# Ruby, 35 bytes

```
->x{n=1;n+=0.1**x while n**3-n<1;n}

```

Try it online!
> 1 votes

# Answer
## Clojure, 46 bytes

```
#(nth(iterate(fn[i](Math/pow(inc i)(/ 3)))1)%)

```

Uses the iterated cube-root formula. This is a bit more interesting but longer:

```
(def f #(apply comp(repeat %(fn[i](Math/pow(inc i)(/ 3))))))

((f 10)1)
1.3247179361449652

```
> 0 votes

# Answer
## Javascript, 36 bytes

```
f=(x,n=x)=>n**3/x/x<n+x?f(x,++n):n/x

```

Works the same as the top python answer. No `console.log` was included because if you run `f(x)` in console it will be logged automatically.

```
f=(x,n=x)=>n**3/x/x<n+x?f(x,++n):n/x
console.log(f(300))
```
> 0 votes

# Answer
# \>\<\>, 38+3 = 41 bytes

```
11\n;
?!\}2,:01{::::}**-+0(?$-{+{1-:}

```

Expects the input to be present on the stack at program start, so +3 bytes for the `-v` flag.

Try it online!

Effectively performs a binary search to narrow in on the output value. Increasing `x` increases the number of iterations to perform.

*Edit: refactored calculation slightly to save 1 byte, previous version:*

```
11\n;
?!\}2,:0{::::}**$-1-0)?$-{+{1-:}

```
> 0 votes

# Answer
# k, 27 bytes

```
{"/"/$1_|x({y,z,x+y}.)/3#1}

```

Try it online! This assumes infinite integers (which, alas, is not true). It uses the Padovan sequence.
> 0 votes

# Answer
## C#, 317 bytes

```
using m=System.Math;a=x=>{if(a==0)return "1/1";var d=a(x-1).Split('/');var b=int.Parse(d[0]);var c=int.Parse(d[1]);return string.Format("{0}/{1}",(2*m.Pow(b,3)+m.Pow(c,3)).ToString(new string('#',int.MaxValue.ToString().Length)),(3*m.Pow(b,2)*c-m.Pow(c,3)).ToString(new string('#',int.MaxValue.ToString().Length)));};

```

It returns the result as a fraction.

### Explanation

It uses the Newton's method with x iterations for finding the root of the polynomial p^3-p-1=0. The formula is x\_n=1-(f(x\_(n-1)))/(f'(x\_(n-1))), and x\_0 is a starting point.

The polynomials derivative is 3p^2-1, and let's say x\_(n-1)=b/c. Then, by using the above formula we get, that x\_n=(2 b^3+c^3)/(3 b^2 c-c^3). Let's also say, that we start from 1, this will happen, when x=2, because x\>1, and is an integer. Idented, and commented code:

```
using System;
string PlasticNumber(int x)
{
    if (x == 2)
        return "1/1";

//If x=2, we return our starting value, but we need to return it as a fraction

    var d = PlasticNumber(x - 1).Split('/');
    var b = System.Convert.ToInt32(d[0]);
    var c = int.Parse(d[1]);

//We parse the previous value of the fraction, and put it into two variables

    return string.Format("{0}/{1}",
        (2 * Math.Pow(b, 3) + Math.Pow(c, 3))
        .ToString(new string('#', int.MaxValue.ToString().Length)),
        (3 * Math.Pow(b, 2) * c - Math.Pow(c, 3))
        .ToString(new string('#', int.MaxValue.ToString().Length)));

//We return the result as a fraction, but it's important not to return it in
  scientific notation, because that will cause issues in the parsing process

}

```
> 0 votes

# Answer
# TI-BASIC, 21 bytes

```
:Prompt X //Prompt for input, 3 bytes
:While X  //While X, 3 bytes
:³√(1+Y→Y //Calculate cube root of 1+Y and store to Y, 7 bytes
:DS<(X,0  //Decrement X and skip next command (which doesn't do anything), 5 bytes
:End      //End While loop, 2 bytes
:Y        //Display Y, 1 byte

```

Uses this recursive formula.

Interestingly, hard-coding the number and rounding it gives the same byte-count:

# TI-BASIC, 21 bytes

```
:Prompt X    //Prompt for input, 3 bytes
:.5√(3       //Store √(3)/2 to Ans, 5 bytes
:Ansֿ¹cosh(3ֿ¹coshֿ¹(3Ans //Store the plastic number to Ans, 9 bytes
:round(Ans,X //Round the plastic number X decimal digits, 4 bytes

```

Uses this trigonometric formula.
> 0 votes

# Answer
# PHP, 86 bytes

```
for($p=[1,1,1];$i++<$argn;)$p[]=bcadd($p[$i],$p[$i-1]);echo bcdiv($p[$i+1],$p[$i],$i);

```

PHP Sandbox Online

Creates the Padovan Spiral and print the ratio of the last two numbers.
> 0 votes

# Answer
# Axiom, 96 bytes

```
h(n:NNI):Float==(n>1.E5=>-1;n:=n+1;j:=digits(n::PI);r:=solve(x^3-x=1,10.^-n);digits(j);rhs(r.1))

```

results

```
(31) -> [h(i) for i in 0..10]
   (31)
   [1.0, 1.3, 1.33, 1.325, 1.3247, 1.32472, 1.324718, 1.324718, 1.32471796,
    1.324717957, 1.3247179572]
                                                         Type: List Float

```

how you can see h(2) should be 1.32 and not 1.33 so there is some error in last digits

Then there would be this one of 110 bytes

```
g(n:NNI):Float==(n>1.E5=>-1;n:=n+1;j:=digits(n::PI);x:=sqrt(23./108);r:=(.5+x)^(1/3)+(.5-x)^(1/3);digits(j);r)

```

It use the formula for resolve equation of III grade of type x^3-3\*p\*x-2\*q=0 in the case q^2-p^3\>=0 that is m=sqrt(q^2-p^3) and x=(q+m)^(1/3)+(q-m)^(1/3)

In our case r^3-r-1=0 this can be written as r^3-3\*(1/3)r-2\*(1/2)=0 so p=1/3 q=1/2 m=1/4-1/27=23/108 x=(0.5+m)^(1/3)+(0.5-m)^(1/3)

this one that use Newton iteration with start point r=1

```
f(n:NNI):Float==(n>1.E5=>-1;n:=n+1;j:=digits(n::PI);e:=10^-n;r:=1.;repeat(v:=(r^3-r-1)/(3*r^2-1);abs(v)<e=>break;r:=r-v);digits(j);r)

```

it change in the function, digits value for obtain one obj of n+1 digits afther the float point. At end the digits() value is assigned back to preciding value.
> 0 votes

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