title: Prime Factoral Roots

text:
# Question
Title: Prime Factoral Roots
Inspired by digital roots, the prime factoral root of a number is the number that emerges when you take the prime factors of a number, add them together, and repeat the process on the resulting number, continuing until you end up with a prime number (which has itself as its only prime factor, and is thus its own prime factoral root). The prime factoral root of 4 is 4, as 2\*2=2+2, and this is the only non-prime prime factoral root of an integer greater than 1 (which is another special case, as it has no prime factors). The OEIS sequence formed by prime factoral roots is A029908.

For example, the prime factoral root of 24 is:

```
24=2*2*2*3

2+2+2+3=9=3*3

3+3=6=2*3

2+3=5, and the only prime factor of 5 is 5.  Therefore, the prime factoral root of 24 is 5.

```

## Your Task:

Write a program or function that finds the prime factoral root of an input integer.

## Input:

An integer, input through any reasonable method, between 2 and the largest integer your language will support (inclusive). Specifically choosing a language that has an unreasonably low maximum integer size is not allowed (and also violates this standard loophole)

## Output:

An integer, the prime factoral root of the input.

## Test Cases:

```
4   -> 4
24  -> 5
11  -> 11
250 -> 17

```

## Scoring:

This is , lowest score in bytes wins!

# Answer
> 19 votes
# Haskell, 61 bytes

```
import Data.Numbers.Primes
until=<<((==)=<<)$sum.primeFactors

```

Try it online!

### Explanation

`until=<<((==)=<<)` takes a function `f` and applies it to input `x` until a fix point is reached, that is `f x` equals `x`. `primeFactors` returns the list of prime factors of a number, `sum` yields the sum of a list of numbers.

*But wait, why does* `until=<<((==)=<<)` *the job and looks so weird?*

If we assume `f=sum.primeFactors`, a more natural definition would be `until(\x->f x==x)f`, because `until` takes a predicate (a function which returns a boolean), a function which has the same input and return type (e.g. `Int -> Int`) and value of this type, and then applies the function to the value until the predicate is fulfilled.

`until(\x->f x==x)f` is the same as `until(\x->(==)(f x)x)f`, and as it holds that `g (h x) x` is the same as `(g=<<h)x`, we get `until(\x->((==)=<<f)x)f`. After Eta conversion, this becomes `until((==)=<<f)f`. But if we now treat `(==)=<<` as a function which is applied to `f`, we can see that `until(((==)=<<)f)f` is again of the form `g (h x) x`, with `g=until`, `h=((==)=<<)` and `x=f`, so it can be rewritten to `(until=<<((==)=<<))f`. Using the `$` operator to get rid of the outer parentheses and substituting `f` with `sum.primeFactors` yields the solution from above.

# Answer
> 16 votes
# 05AB1E, 3 bytes

```
FÒO

```

Try it online!

**Explanations:**

```
FÒO
F    Loops <input> times + 1
 Ò   List of prime factors w/ duplicates
  O  Total sum of the list
     -- implicit output

```

# Answer
> 5 votes
# Husk, 4 bytes

```
ω(Σp

```

Try it online!

Explanation:

```
ω(   -- apply the following function until the result no longer changes (fixpoint)
  Σ  -- sum
   p -- the list of primefactors

```

# Answer
> 5 votes
# Pyth, 3 bytes

```
usP

```

Try it here.

Explanation:

```
usPGQ The trailing GQ is implicit
  PG  Get prime factors
 s    Sum
u   Q Repeat until returned value no longer unique starting with the input

```

# Answer
> 4 votes
# Java 8, ~~175~~ ~~144~~ ~~142~~ ~~141~~ ~~139~~ 101 bytes

```
n->{for(int i=n;i-->0;)n=f(n,2);return n;};int f(int n,int d){return n>1?n%d<1?f(n/d,2)+d:f(n,d+1):0;}

```

-38 bytes porting *@ovs*' Python answer, so make sure to upvote him as well!

Try it online.

```
n->{                 // Method with integer as both parameter and return-type
  for(int i=n;i-->0;)//  Loop the input `n` amount of times:
    n=f(n,2);        //   Change `n` that many times by calling the recursive method
                     //   with n,2 as parameters
  return n;}         //  Then return the potentially modified `n` as result

int f(int n,int d){  // Separated method with 2 integer parameters & integer return
                     // (`d` is 2 when we initially call this recursive-method)
  return n>1?        //  If input `n` is larger than 1:
          n%d<1?     //   If `n` is divisible by `d`:
           f(n/d     //    Divide `n` by `d`
             ,2)     //    Do a recursive call with n/d,2 as parameters
                +d   //    And add `d` to its result
          :          //   Else:
           f(n,d+1)  //    Do a recursive-call with the next `d` by using n,d+1 as
                     //    parameters
         :           //  Else:
          0;}        //   Simply return 0

```

**Original ~~175~~ ~~144~~ ~~142~~ ~~141~~ 139 bytes answer:**

```
n->{for(int i,t=n,x;;n=t){for(i=2;i<t;)t=t%i++<1?0:t;if(t>1|n<5)return n;for(t=0,i=1;i++<n;)for(;n%i<1;t+=x)for(n/=x=i;x>9;x/=10)t+=x%10;}}

```

-1 byte thanks to *@Nevay*
-2 bytes thanks to *@ceilingcat*

**Explanation:**

Try it online.

```
n->{                 // Method with integer as both parameter and return-type
  for(int i,         //  Index-integer `i`
          t=n,       //  Temp integer `t`, starting at the input `n`
          x;         //  Temp integer `x`
      ;              //  Loop indefinitely:
      n=t){          //    After every iteration, replace `n` with the value `t`
    for(i=2;i<t;)    //   Inner loop `i` in the range [2,t):
      t=t%i++<1?     //    If `t` is divisible by `i`:
         0           //     Set `t` to 0
        :            //    Else:
         t;          //     Leave `t` the same
    if(t>1           //   If `t` is not 0 or 1 (it means it's a prime),
       |n<5)         //   or if `n` is below 5 (for edge-cases n=1 and n=4)
      return n;      //    Return `n` as result
    for(t=0,         //   Reset `t` to 0
        i=1;         //   Reset `i` to 1
        i++<n;)      //   Inner loop `i` in the range (2,n]:
      for(;n%i<1;    //    Inner loop as long as `n` is divisible by `i`:
          t+=x)      //      After every iteration: Increase `t` by `x`
        for(n/=x=i;  //     Reset `x` to `i`
                     //     And divide `n` by `i`
            x>9;     //     Inner loop as long as `x` contains more than 1 digit:
            x/=10)   //       After every iteration, remove the trailing digit of `x`
          t+=x%10;}} //      Increase `t` with the trailing digit of `x`

```

# Answer
> 4 votes
# Python 2, 84 bytes

```
f=lambda n,d=2:n>1and(n%d and f(n,d+1)or d+f(n/d))
i=input()
exec'i=f(i);'*i
print i

```

Try it online!

# Answer
> 3 votes
## Retina, 30 bytes

```
{+`(\1|\b11+?\B)+$
$1;$#1$*
;

```

Input and output in unary.

Try it online! (Performs decimal/unary conversion for convenience.)

### Explanation

```
{+`(\1|\b11+?\B)+$
$1;$#1$*

```

The `{` instructs Retina to run the entire program in a loop until a full pass fails to modify the string, i.e. until a fixed point is reached. Consequently, the program itself computes one step of summing the prime factors of the current value.

This stage itself computes the prime factorisation of the input. The `+` is similar to `{` but loops only this stage until it stops changing the string. The regex tries to match the final run of `1`s by repeatedly matching the same substring (i.e. the factor). The way this is done is a bit convoluted due to the forward reference `\1`. On the first iteration, group `1` hasn't captured anything yet, so `\1` fails unconditionally. Instead, we have to match `\b11+?\B` which is the smallest possible substring that starts at the beginning of the run, contains at least two `1`s and doesn't cover the entire run. Subsequent iterations will not be able to use this alternative again, due to the `\b`. So on all further iterations, we're matching `\1`, i.e. the same substring over and over again. This process has to hit the end of the string exactly (`$`) to make sure we've captured and actual divisor. The benefit of using this somewhat tricky approach is that group `1` will have been used exactly **n/d** times, i.e. what remains after dividing out the divisor **d**.

We replace this match with **d** (`$1`), a separating `;` and **n/d** (`$#1$*`, which inserts `$#1` copies of `1`, where `$#1` is the number of captures made by group `1`).

This process stops once the final run in the string is itself a prime, because then the regex no longer matches.

```
;

```

All we need to do to sum the primes is to remove all the separators.

# Answer
> 3 votes
# Jelly, 5 bytes

```
ÆfS$¡

```

Explanations:

```
Æf    list of prime factors
  S   sum
   $¡ repeat n times

```

Try it online!

# Answer
> 3 votes
# Ohm v2, 4 bytes

```
·ΘoΣ

```

Try it online!

**Explanation:**

```
·Θ    evaluate the block until the result returned has already been seen
   Σ  sum
  o   the full prime factorization

```

# Answer
> 2 votes
# Actually, 7 bytes

```
⌠w♂πΣ⌡Y

```

Try it online!

Explanation:

```
⌠w♂πΣ⌡Y
⌠    ⌡Y  do this until output stops changing (fixed-point combinator)
 w         factor into [prime, exponent] pairs
  ♂π       product of each pair
    Σ      sum of products

```

# Answer
> 2 votes
# \+ pracma, 53 bytes

```
function(n){for(i in 1:n)n=sum(pracma::factors(n))
n}

```

Try it online! (r-fiddle)

R doesn't have a prime factors builtin, but numerous packages (`pracma`, `numbers`, etc.) do, so I picked a conveniently short one.

# Answer
> 1 votes
# MATL, 6 bytes

*Uses scottinet's idea of looping more times than needed. Thanks also to Shaggy for a pointing out a mistake, now corrected.*

```
t:"Yfs

```

**Try it online!**

### Explanation

```
t       % Take input (implicit). Duplicate
:"      % Do the following that many times
  Yf    %   Array of prime factors
  s     %   Sum of array
        % End (implicit). Display (implicit)

```

# Answer
> 1 votes
# Jelly, 6 bytes

This answer uses one of Jelly's many prime factorization builtins, and the quick for `repeat until the results are no longer unique`.

```
ÆfSµÐL

```

**Try it online!**

# Answer
> 1 votes
# PowerShell, 124 bytes

```
function f($a){for($i=2;$a-gt1){if(!($a%$i)){$i;$a/=$i}else{$i++}}}
for($x=$args[0];$l-ne$x){$l=$x;$x=(f($x))-join'+'|iex}$x

```

Try it online!

PowerShell doesn't have any prime factorization built-ins, so this uses code from my answer on Prime Factors Buddies (the top line) to perform the factorization calculations.

The second line is the meat of this program. We take input from `$args` into `$x`, then `for` loop until `$l` is `-n`ot`e`qual to `$x`. (The first iteration, `$l` is `$null` and `$x` is an integer, so we'll loop at least once).

Inside the loop, we set our `$l = $x` to determine if we've hit the end of the loop or not. Then we get the factors of `$x` with `f($x)`, `-join` those together with `+` and `|iex` them (short for `Invoke-Expression` and similar to `eval`). That's stored back into `$x`. Thus, we've hit the "end" where the prime factorization summed together is back to itself. Then, we simply place `$x` on the pipeline and output is implicit.

# Answer
> 0 votes
# Mathematica, 35 bytes

```
#//.x_:>Tr[1##&@@@FactorInteger@x]&

```

Try it online!

(Mathics does not support `Tr`. I have to implement it manually)

# Answer
> 0 votes
# Ruby, 63 bytes

```
->n{n.times{n=n.prime_division.map{|x|x.reduce:*}.sum};n}

```

Try it online!

Uses the `-rprime` flag for +6 bytes to make use of Prime#prime\_division.

`prime_division` returns pairs of `[prime, exponent]` (for example, for 24 we have the factors `[2, 2, 2, 3]` so it gives `[[2, 3], [3, 1]]`) so in each step we just multiply the members of those pairs together and sum the results.

# Answer
> 0 votes
# Javascript (ES6), 63 bytes

```
f=n=>(q=(p=(m,x)=>m<x?0:m%x?p(m,x+1):x+p(m/x,x))(n,2))^n?f(q):q
```

```
<input id=i type=number min=0 value=0 oninput="o.innerText=f(i.value)">
<p id=o></p>
```

## Ungolfed:

```
f=n=>(                  // Recursive function `f`
    p=(m,x=2)=>(        //   Recursive function `p`, used to sum prime factors
        m<x?            //     If m (the number to be factored) is less than x (the current
            0           //     iteration), return 0
        :m%x?           //     Else if m doesn't divide x
            p(m,x+1)    //     run the next iteration
        :               //     Else (if m divides x)
            x+p(m/x,x)  //     Divide m by x and repeat the current iteration
    ),
    q=p(n),             //   Set q to the sum of the prime factors of n
    q^n?                //   If q != n then
        f(q)            //     repeat f with q
    :                   //   else
        q               //     return q
)

```

# Answer
> 0 votes
# Factor, 33 bytes

```
[ [ factors Σ ] to-fixed-point ]

```

Try it online!

* `to-fixed-point` Apply a quotation to an object until it stops changing.
* `factors Σ` Sum of prime factors.

---
Tags: code-golf, number, sequence, primes
---


# Question
Title: Calculate the n-th iterate of a polynomial for a specific value; fⁿ(x)
Given a polynomial function *f* (e.g. as a list *p* of real coefficients in ascending or descending order), a non-negative integer *n*, and a real value *x*, return:

# *f*n(*x*)

i.e. the value of *f* (*f* (*f* (…*f* (*x*)…))) for *n* applications of *f* on *x*.

Use reasonable precision and rounding.

Solutions that take *f* as a list of coefficients will probably be the most interesting, but if you are able to take *f* as an actual function (thereby reducing this challenge to the trivial "apply a function *n* times"), feel free to include it after your non-trivial solution.

### Example cases

*p* =`[1,0,0]` or *f* =`x^2`, *n* =`0`, *x* =`3`: *f*0(3) =`3`

*p* =`[1,0,0]` or *f* =`x^2`, *n* =`1`, *x* =`3`: *f*1(3) =`9`

*p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`0`, *x* =`2.3`: *f*0(2.3) =`2.3`

*p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`1`, *x* =`2.3`: *f*1(2.3) =`-8.761`

*p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`2`, *x* =`2.3`: *f*2(2.3) =`23.8258`

*p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`3`, *x* =`2.3`: *f*3(2.3) =`-2.03244`

*p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`4`, *x* =`2.3`: *f*4(2.3) =`1.08768`

*p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`5`, *x* =`2.3`: *f*5(2.3) =`-6.38336`

*p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`6`, *x* =`2.3`: *f*6(2.3) =`14.7565`

*p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`7`, *x* =`2.3`: *f*7(2.3) =`-16.1645`

*p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`8`, *x* =`2.3`: *f*8(2.3) =`59.3077`

*p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`9`, *x* =`2.3`: *f*9(2.3) =`211.333`

*p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`10`, *x* =`2.3`: *f*10(2.3) =`3976.08`

*p* =`[0.1,-2.3,-4]` or *f* =`0.1x^2-2.3x-4`, *n* =`11`, *x* =`2.3`: *f*11(2.3) =`1571775`

*p* =`[-0.1,2.3,4]` or *f* =`−0.1x^2+2.3x+4`, *n* =`0`, *x* =`-1.1`: *f*0(-1.1) =`-1.1`

*p* =`[-0.1,2.3,4]` or *f* =`−0.1x^2+2.3x+4`, *n* =`1`, *x* =`-1.1`: *f*1(-1.1) =`1.349`

*p* =`[-0.1,2.3,4]` or *f* =`−0.1x^2+2.3x+4`, *n* =`2`, *x* =`-1.1`: *f*2(-1.1) =`6.92072`

*p* =`[-0.1,2.3,4]` or *f* =`−0.1x^2+2.3x+4`, *n* =`14`, *x* =`-1.1`: *f*14(-1.1) =`15.6131`

*p* =`[0.02,0,0,0,-0.05]` or *f* =`0.02x^4-0.05`, *n* =`25`, *x* =`0.1`: *f*25(0.1) =`-0.0499999`

*p* =`[0.02,0,-0.01,0,-0.05]` or *f* =`0.02x^4-0.01x^2-0.05`, *n* =`100`, *x* =`0.1`: *f*100(0.1) =`-0.0500249`

# Answer
> 7 votes
# Octave, 49 bytes

```
@(p,x,n)(f=@(r,m){@()p(r(r,m-1)),x}{~m+1}())(f,n)

```

Try it online!

Or, taking coefficients:

## Octave, ~~75~~ 57 bytes

```
@(p,x,n)(f=@(f,n){@()polyval(p,f(f,n-1)),x}{~n+1}())(f,n)

```

Try it online!

A special thanks for Suever over at StackOverflow, for this answer some time ago on a question of mine, proving that a recursive anonymous function is possible.

This defines an anonymous function, which is a wrapper for a **recursive anonymous function**; something which is not a native Octave concept, and requires some fancy cell array indexing.

As a bonus, the second version is a nice lesson in variable scoping in Octave. All instances of `r` can legally be replaced by `f`, which then simply overwrites the existing `f` in the most local scope (similar for `n`)

### Explanation

```
@(p,x,n)(f=@(r,m){@()p(r(r,m-1)),x}{~m+1}())(f,n)
@(p,x,n)         .                ..    .  ..   .   % Defines main anonymous function
        (f=@(r,m).                ..    .  ).   .   % Defines recursive anonymous function
                 .                ..    .   .   .   %  r: Handle ('pointer') to recursive function
                 .                ..    .   .   .   %  m: Current recursion depth (counting from n to 0)
                 .                ..    .   (f,n)   % And call it, with
                 .                ..    .           %  r=f (handle to itself)
                 .                ..    .           %  m=n (initial recursion)
                 {                }{    }           % Create and index into cell array
                                    ~m+1            %  Index: for m>0: 1; for m==0: 2.
                                ,x                  %  Index 2: final recursion, just return x.
                  @()                               %  Index 1: define anonymous function, taking no inputs.
                     p(        )                    %   which evaluates the polynomial
                       r(     )                     %    of the recursive function call
                         r,m-1                      %     which is called with r
                                                    %     and recursion depth m-1
                                                    %     (until m=0, see above)
                                         ()         % Evaluate the result of the cell array indexing operation.
                                                    %  which is either the anonymous function
                                                    %  or the constant `x`.

```

The key to this is that anonymous functions are **not** evaluated when they are defined. So, the `@()`, which seems a bit superfluous since it defines an anonymous function which is called with `()` directly after, is actually strictly necessary. It is not called **unless** it is selected by the indexing statement.

### Octave, 39 bytes (boring way)

```
function x=f(p,x,n)for i=1:n;o=p(o);end

```

Just for completeness, the Octave solution with the shortest bytecount. Yawn..

# Answer
> 4 votes
# Mathematica, ~~56~~ ~~47~~ 28 bytes

```
Nest[x\[Function]x#+#2&~Fold~#,##2]&

```

`\[Function]` takes 3 bytes in UTF-8.

Take parameters in order `p,x,n`.

`p` (parameter 1) is in increasing order of degree.

Obviously if `f` can be taken as a function this can be reduced just to `Nest`.

# Answer
> 4 votes
# Pari/GP, 31 bytes

```
(p,n,x)->for(i=1,n,x=eval(p));x

```

Try it online!

# Answer
> 4 votes
# Husk, 5 bytes

```
←↓¡`B

```

Try it online!

The key idea here is that evaluating a polinomial at a point *x* is equivalent to performing base conversion from base *x*.

`B` when given a base and a list of digits performs base conversion. Here we use its flipped version, in order to take the list of digits first and partially apply this function to it. We obtain then a function which computes the value of the given polynomial at a point, the second part of this solution deals with iterating this function the correct amount of times:

# Husk, 3 bytes

```
←↓¡

```

`¡` is the "iterate" function, it takes a function and a starting point and returns the infinite list of values obtained iterating the function.

takes a number (the third argument of this challenge) and drops that many elements from the start of the list.

returns the first element of the resulting list.

# Answer
> 3 votes
## JavaScript (ES6),  ~~52 49 44~~  42 bytes

*Saved 5 bytes thanks to G B and 2 more bytes thanks to Neil*

Takes input in currying syntax as `(p)(n)(x)`, where ***p*** is the list of coefficients in descending order.

```
p=>n=>g=x=>n--?g(p.reduce((s,v)=>s*x+v)):x

```

### Test cases

```
let f =

p=>n=>g=x=>n--?g(p.reduce((s,v)=>s*x+v)):x

console.log(f([1,0,0])(0)(3))
console.log(f([1,0,0])(1)(3))
console.log(f([0.1,-2.3,-4])(0)(2.3))
console.log(f([0.1,-2.3,-4])(1)(2.3))
console.log(f([0.1,-2.3,-4])(2)(2.3))
console.log(f([0.1,-2.3,-4])(3)(2.3))
console.log(f([0.1,-2.3,-4])(4)(2.3))
console.log(f([0.1,-2.3,-4])(5)(2.3))
console.log(f([0.1,-2.3,-4])(6)(2.3))
console.log(f([0.1,-2.3,-4])(7)(2.3))
console.log(f([0.1,-2.3,-4])(8)(2.3))
console.log(f([0.1,-2.3,-4])(9)(2.3))
console.log(f([0.1,-2.3,-4])(10)(2.3))
console.log(f([0.1,-2.3,-4])(11)(2.3))
console.log(f([-0.1,2.3,4])(0)(-1.1))
console.log(f([-0.1,2.3,4])(1)(-1.1))
console.log(f([-0.1,2.3,4])(2)(-1.1))
console.log(f([-0.1,2.3,4])(14)(-1.1))
console.log(f([0.02,0,0,0,-0.05])(25)(0.1))
console.log(f([0.02,0,-0.01,0,-0.05])(100)(0.1))
```

# Answer
> 3 votes
# Ruby, 42 bytes

```
->c,n,x{n.times{x=c.reduce{|s,r|s*x+r}};x}

```

C is the list of coefficients in descending order

Trivial version, where f is a lambda function (**26 bytes**):

```
->f,n,x{n.times{x=f[x]};x}

# For example:
# g=->f,n,x{n.times{x=f[x]};x}
# p g[->x{0.02*x**4-0.01*x**2-0.05},100,0.1]

```

Try it online!

# Answer
> 2 votes
# , ~~96~~ ~~58~~ ~~55~~ 52 bytes

```
f=function(n,p,x)`if`(n,f(n-1,p,x^(seq(p)-1)%*%p),x)

```

Try it online!

### Explanation:

`seq(p)` generates the list `1, 2, ..., length(p)` when `p` is a vector, so `seq(p)-1` is the exponents of the polynomial, hence `x^(seq(p)-1)` is equivalent to `x^0` (always equal to 1)`, x^1, x^2, ...` and computing a dot product `%*%` with `p` evaluates the polynomial at `x`.

Additionally, if `P` is taken as a function, then this would be **38 bytes:**

```
function(n,P,x)`if`(n,f(n-1,P,P(x)),x)

```

And we can of course always generate `P` by `P=function(a)function(x)sum(x^(seq(a)-1)*a)`

# Answer
> 2 votes
# Jelly, 10 bytes

```
*⁹LḶ¤×⁹Sµ¡

```

Try it online!

Takes x, coefficients in ascending order, n in this order.

# 4 bytes

```
⁹v$¡

```

Try it online!

Takes x, Jelly link (may need to be quoted/escaped), n in this order.

# Answer
> 2 votes
# APL (Dyalog), ~~20~~ 9 bytes

```
{⊥∘⍵⍣⎕⊢⍺}

```

Try it online!

This takes `x` as the left argument, the coefficients of the function as the right argument, and `n` from STDIN.

Looking back at this after many a long time, I realised I could simplify the calculation by using base conversion .

---

# APL (Dyalog), 5 bytes

If we can take the function as a Dyalog APL function, then this can be 5 bytes.

```
⎕⍣⎕⊢⎕

```

Takes `x`, `n` and then the function as input from STDIN.

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

-1 byte thanks to Erik the Outgolfer

```
sF³gÝ¨m*O

```

Try it online!

Takes x as first argument, n as second and p in ascending order as third.

### Explanation

```
sF³gÝ¨m*O
s         # Forces the top two input arguments to get pushed and swaped on the stack
 F        # Do n times...
  ³        # Push the third input (the coefficients)
   g       # Get the length of that array...
    Ý¨     # and create the range [0 ... length]
      m    # Take the result of the last iteration to these powers (it's just x for the first iteration)
       *   # Multiply the resuling array with the corresponding coefficients
         O # Sum the contents of the array
          # Implicit print

```

# Answer
> 2 votes
# , 15 bytes

```
0{(p.{.)^:(]{:)

```

Try it online!

Takes the polynomial as a list of coefficients of ascending powers.

## Explanation

```
0{(p.{.)^:(]{:)  Input: polynomial P (LHS), [x, n] (RHS)
            {:   Tail of [x, n], gets n
           ]     Right identity, passes n
  (    )^:       Repeat n times starting with g = [x, n]
     {.            Head of g
   p.              Evaluate P at that value
                   Return g = [P(head(g))]
0{               Return the value at index 0

```

# Answer
> 2 votes
# Haskell, 15 bytes

```
((!!).).iterate

```

Try it online!

Thanks to totallyhuman for 11 bytes off of both solutions

This defines a tacit function that takes a function as its first argument and `n` as its second argument, and composes that function with itself `n` times. This can then be called with an argument `x` to get the final value. Thanks to the magic of currying, this is equivalent to one function taking three arguments.

---

Taking a list of coefficients instead of a function argument:

# Haskell, 53 bytes

```
((!!).).iterate.(\p x->sum$zipWith(*)p[x^i|i<-[0..]])

```

Try it online!

This is the same as the above code, but composed with a lambda function that converts a list of coefficients into a polynomial function. The coefficients are taken in reverse order from the examples - as ascending powers of `x`.

# Answer
> 2 votes
# Jelly, 4 bytes

```
⁴ḅ$¡

```

Try it online!

Full program that takes `x p n` as command line arguments

## How it works

```
⁴ḅ$¡ - Main link. Takes x and p on the left
  $  - Previous 2 links as a monad f(x):
⁴    -   Yield p
 ḅ   -   Convert p from base x
   ¡ - Apply f(x) to x n times

```

# Answer
> 1 votes
# Python 3, ~~70~~ 69 bytes

```
f=lambda p,n,x:n and f(p,n-1,sum(c*x**i for i,c in enumerate(p)))or x

```

Takes `p` in ascending order, i.e. if `p` is `[0, 1, 2]` then the corresponding polynomial is `p(x) = 0 + 1*x + 2*x^2`. Simple recursion solution.

Try it online!

# Answer
> 1 votes
# C# (.NET Core), 82 bytes

```
using System.Linq;f=(p,n,x)=>n<1?x:p.Select((c,i)=>c*Math.Pow(f(p,n-1,x),i)).Sum()

```

Try it online!

Takes a list of coefficients in the opposite order from the test cases (increasing order?) so that their index in the array is equal to the power x should be raised to.

And the trivial version in 30 bytes:

```
f=(p,n,x)=>n<1?x:f(p,n-1,p(x))

```

Try it online!

Takes a delegate and applies it recursively n times.

# Answer
> 1 votes
# MATL, 11 bytes

```
ii:"ZQ6Mw]&

```

Try it online!

Slightly less interesting than my Octave answer, although I think there's some clever juggling of inputs to make sure `n=0` works as expected.

# Answer
> 1 votes
## Julia 0.6.0 (78 bytes)

`using Polynomials;g(a,n,x)=(p=Poly(a);(n>0&&(return g(a,n-1,p(x)))||return x))`

Explainations:

The package Polynomials is pretty self explanatory: it creates polynomials. After that it's a pretty basic recursion.

In order to have a polynomial: -4.0 - 2.3\*x + 0.1\*x^2 the input `a` must be like `a = [-4, -2.3, 0.1]`

# Answer
> 1 votes
# Axiom, 91 bytes

```
f(n,g,x)==(for i in 1..n repeat(v:=1;r:=0;for j in 1..#g repeat(r:=r+v*g.j;v:=v*x);x:=r);x)

```

indented

```
fn(n,g,x)==
     for i in 1..n repeat
          v:=1; r:=0
          for j in 1..#g repeat(r:=r+v*g.j;v:=v*x)
          x:=r
     x

```

the input for polynomy g it is one list of numbers in the reverse of the example of exercise. for example

```
[1,2,3,4,5]

```

it would represent the polinomy

```
1+2*x+3*x^2+4*x^3+5*x^4

```

test:

```
(3) -> f(0,[0,0,1],3)
   (3)  3
                                                    Type: PositiveInteger
(4) -> f(1,[0,0,1],3)
   (4)  9
                                                    Type: PositiveInteger
(5) -> f(0,[-4,-2.30,0.1],2.3)
   (5)  2.3
                                                              Type: Float
(6) -> f(1,[-4,-2.30,0.1],2.3)
   (6)  - 8.7610000000 000000001
                                                              Type: Float
(7) -> f(2,[-4,-2.30,0.1],2.3)
   (7)  23.8258121
                                                              Type: Float
(8) -> f(9,[-4,-2.30,0.1],2.3)
   (8)  211.3326335688 2052491
                                                              Type: Float
(9) -> f(9,[-4,-2.30,0.1,0,0,0,0,1],2.3)
   (9)  0.4224800431 1790652974 E 14531759
                                                              Type: Float
                                   Time: 0.03 (EV) + 0.12 (OT) = 0.15 sec
(10) -> f(2,[-4,-2.30,0.1,0,0,0,0,1],2.3)
   (10)  44199336 8495528344.36
                                                              Type: Float

```

# Answer
> 1 votes
# Röda, 41 bytes

```
f p,n,x{([0]*n)|x=_+p()|reduce _*x+_;[x]}

```

Try it online!

A trivial version:

```
f F,n{([_]..[0]*n)|reduce F(_)+_}

```

Try it online!

It takes the the value for `x` from the stream.

# Answer
> 1 votes
# C++14, 71 bytes

As generic unnamed lambda, returning via the `x` Parameter:

```
[](auto C,int n,auto&x){for(auto t=x;t=0,n--;x=t)for(auto a:C)t=a+x*t;}

```

Ungolfed and testcase:

```
#include<iostream>
#include<vector>

using namespace std;

auto f=
[](auto C,int n,auto&x){
 for(
  auto t=x; //init temporary to same type as x
  t=0, n--; //=0 at loop start, also check n
  x=t       //apply the result
  )
  for(auto a:C)
   t=a+x*t; //Horner-Scheme
}
;

int main() {
 vector<double> C = {0.1,-2.3,-4};//{1,0,0};
 for (int i = 0; i < 10; ++i) {
  double x=2.3;
  f(C, i, x);
  cout << i << ": " << x << endl;
 }
}

```

# Answer
> 0 votes
# QBIC, 19 bytes

```
[:|:=:*c^2+:*c+:}?c

```

Takes inputs as

* Number of iterations
* starting value of x
* Then the 3 parts of the polynomial

Sample output:

```
Command line: 8 2.3 0.1 -2.3 -4
 59.30772

```

# Answer
> 0 votes
## Clojure, 66 bytes

```
#(nth(iterate(fn[v](apply +(map *(iterate(partial * v)1)%3)))%2)%)

```

Full example:

```
(def f #(nth(iterate(fn[v](apply +(map *(iterate(partial * v)1)%3)))%2)%))
(f 10 2.3 [-4 -2.3 0.1])
; 3976.0831439050253

```

Composing a function is 26 bytes:

```
#(apply comp(repeat % %2))

(def f #(apply comp(repeat % %2)))
((f 10 #(apply + (map * [-4 -2.3 0.1] (iterate (partial * %) 1)))) 2.3)
; 3976.0831439050253

```

# Answer
> 0 votes
# Japt, 18 bytes

Pretty straightforward, does what the challenge says on the tin.

```
o r_VË*ZpVÊ-EÉÃx}W
o                  // Take `n` and turn it into a range [0,n).
  r_            }W // Reduce over the range with initial value of `x`.
    VË             // On each iteration, map over `p`, yielding the item
      *Z           // times the current reduced value
        pVÊ-EÉ     // to the correct power,
              Ãx   // returning the sum of the results.

```

Takes inputs in order `n`, `p`, `x`.

Try it online!

# Answer
> 0 votes
# Haskell, 39 bytes

```
p!x=(iterate(\y->foldl1((+).(y*))p)x!!)

```

Try it online!

`(!)` takes as input a polynomial `p`, represented as a list of coefficients, a real number `x` and an integer `n`, and returns \\$p^n(x)\\$.

# Answer
> 0 votes
# Factor \+ `math.polynomials`, 35 bytes

```
[ [ [ polyval ] keep ] times drop ]

```

Try it online!

Takes a value, a list of coefficients (high powers on the right), and the number of times to iterate, in that order. `polyval` is a builtin word that evaluates a polynomial given a value and a list of coefficients.

---
Tags: code-golf, math, sequence, polynomials
---


# Question
Title: Acronyms can really obviously narrow your message sensors
Because of this, you need a better way of working out if a phrase is an acronym of a word. You also think it would be worthwhile to see if the phrase and word in question are recursive acronyms.

## Your task:

Given a word and then a phrase separated by a line, output if the phrase is an acronym and then if it is a recursive acronym. (The phrase contains what it stands for)

* The input will compose of alphabetical characters as well as spaces.
* Your program shouldn't be case sensitive.

## Example Input/Output:

Case 1:

Input:

```
Acronyms
Acronyms can really obviously narrow your message sensors

```

Output:

```
True
True

```

Case 2:

Input:

```
FAQ
frequently asked questions

```

Output:

```
True
False

```

Case 3:

Input:

```
foo
bar baz

```

Output:

```
False
False

```

Case 4:

Input:

```
GNU
GNU is not Unix

```

Output:

```
False
False

```

Case 5:

Input:

```
Aha
A huge Aha

```

Output:

```
True
True

```

# Answer
> 10 votes
# Pyth, ~~19~~ 18

```
&pqJrz0hCKcrw0)}JK

```

This prints the result in a rather odd format, like: `TrueFalse`.

You can try it online or run the Test Suite.

### Explanation:

```
&pqJrz0hCKcrw0)}JK      :
    rz0    rw0          : read two lines of input, and convert each to lower case
          c   )         : chop the second input on whitespace
   J     K              : store the first line in J and the chopped second line in K
  q    hC               : zip K and take the first element, check if it is the same as J
 p                      : print and return this value
&              }JK      : and the value with whether J is in K, implicit print

```

# Answer
> 14 votes
# Python 3, 89

Saved a bunch of bytes thanks to SOPython.

```
a=input().lower()
d=input().lower().split()
h=tuple(a)==next(zip(*d))
print(h,h&(a in d))

```

The most complicated part of this solution is `h=tuple(a)==next(zip(*d))`.
This unpacks the list `d` into zip and then calls `next` to return a tuple of the first element of each iterable passed into `zip` which is then compared against a tuple of each letter in a (`tuple(a)`).

# Answer
> 7 votes
# CJam, ~~21~~ 20 bytes

```
qeuN/)S/_:c2$s=_p*&,

```

Try this fiddle in the CJam interpreter or verify all test cases at once.

### How it works

```
qeu                  e# Read from STDIN and convert to uppercase.
   N/                e# Split at linenfeeds.
     )S/             e# Pop the second line form the array.
      S/             e# Split it at spaces.
        _:c          e# Push a copy and keep on the initial of each word.
           2$s       e# Push a copy of the line array and flatten it.
                     e# This pushes the first line.
              =      e# Check for equality.
               _p    e# Print a copy of the resulting Boolean.
                 *   e# Repeat the word array 1 or 0 times.
                  &  e# Intersect the result with the line array.
                   , e# Push the length of the result (1 or 0).

```

# Answer
> 4 votes
# Scala, 135 110 108 bytes

```
val Array(x,y)=args.map(_.toLowerCase)
val z=y.split(" ").map(_(0)).mkString
print(z==x,z==x&&y.contains(z))

```

Saved a few bytes by using command line arguments (thanks to J Atkin for the hint), putting the booleans out as a tupel, using `mkString` instead of `new String` and print instead of println.

EDIT: Misinterpreted the question, and had to reimplement the solution

# Answer
> 4 votes
# Haskell, ~~81~~ 80 bytes

```
import Data.Char
f[a,b]|c<-words b=(a==map(!!0)c,elem a c)
p=f.lines.map toLower

```

The output format is not strictly defined, so I return a pair of booleans, e.g. `p "Aha\na huge arm"` -\> `(True,False)`.

# Answer
> 3 votes
# Python 3, 106 bytes

Well, at least it beat Scala ;)

```
x=input().lower()
y=input().lower().split()
g=all(x[i]==y[i][0]for i in range(len(y)))
print(g,g&(x in y))

```

# Answer
> 3 votes
# AppleScript, ~~302~~ ~~301~~ ~~297~~ 293 Bytes

Aw, hell yeah. Not even bothered that I lose, this is competitive for AppleScript.

```
set x to(display dialog""default answer"")'s text returned
set y to(display dialog""default answer"")'s text returned's words
set n to y's items's number
repeat n
try
if not y's item n's character 1=(x as text)'s character n then return{false,false}
end
set n to n-1
end
return{true,x is in y}
```

Outputs as:

```
{true, false}
```

Or whatever the answer happens to be.

# Answer
> 2 votes
# Ruby, ~~77~~ 74 bytes

```
b=gets.chop.upcase
a=gets.upcase
p c=a.scan(/\b\w/)*''==b,c&&a.include?(b)

```

# Answer
> 2 votes
# PHP, 120 bytes

Not being case sensitive is a lot of weight (26 bytes). Passed all test cases:

```
foreach($c=explode(' ',strtolower($argv[2]))as$l)$m.=$l[0];var_dump($x=$m==$a=strtolower($argv[1]),$x&&in_array($a,$c));

```

Outputs two bool values in this form:

```
bool(true)
bool(false)

```

Reads two arguments from the command line, like:

```
a.php Acronyms "Acronym can really obviously narrow your message sensors"

```

**Ungolfed**

```
$acronym = strtolower($argv[1]);
$words = strtolower($argv[2]);
$words = explode(' ', $words);

foreach($words as $word) {
    $letters .= $word[0];
}

$isAcronym = $letters == $acronym;

var_dump(
    $isAcronym,
    $isAcronym && in_array($acronym, $words)
);

```

# Answer
> 1 votes
# Ruby, 52 bytes

```
p !!gets[/^#{x=gets.scan(/\b\w/)*""}$/i],!! ~/#{x}/i

```

Example:

```
$ echo "Aha
A huge AHA" | ruby acronym.rb
true
true

```

# Answer
> 1 votes
## Matlab, 90 bytes

```
function z=f(r,s)
z=[sum(regexpi(s(regexpi(s,'(?<=(\s|^))\S')),r))>0 nnz(regexpi(s,r))>0];

```

Example (note that Matlab displays `true`/ `false` as `1`/ `0`):

```
>> f('Aha', 'A huge Aha')
ans =
     1     1

```

# Answer
> 1 votes
# JavaScript ES6, ~~95~~ 92 bytes

```
(a,b)=>[(r=eval(`/^${a}$/i`)).test((s=b.split` `).map(c=>c[0]).join``),s.some(c=>r.test(c))]

```

Input both strings as parameters. Outputs an array with two values: one for each boolean.

# Answer
> 0 votes
# GNU sed, 118 bytes

Requires `-r` flag, included in score as +1. Note that I'm using `\b` for a word-boundary match, even though I can't find this documented in GNU sed. It *Works For Me*...

```
N
h
s/^(.*)\n.*\b\1\b.*/True/i
/\n/s/.*/False/
x
:
s/(.)(.*\n)\1[^ ]* ?/\2/i
t
/../s/.*/False/
/F/h
/F/!s/.*/True/
G

```

### Expanded:

```
#!/bin/sed -rf

N
h

# Is it recursive?
s/^(.*)\n.*\b\1\b.*/True/i
# If no replacement, there's still a newline => false
/\n/s/.*/False/

x

# Is it an acronym?
# Repeatedly consume one letter and corresponding word
:
s/(.)(.*\n)\1[^ ]* ?/\2/i
t
# If more than just \n remain, then false
/../s/.*/False/
# And falsify recursive, too
/F/h
# !False => true
/F/!s/.*/True/

G

```

# Answer
> 0 votes
# Groovy, 91 bytes

```
a=args*.toLowerCase()
println([a[1].split()*.charAt(0).join("")==a[0],a[1].contains(a[0])])

```

Output format is `[bool, bool]`.This takes it's input from the command line args.

# Answer
> 0 votes
# Lua 5.3, 182 bytes

```
a=""b=io.read c=a.lower d=a.reverse e=d(c(b()))f=~e:len()h=a.sub g=d(c(b()))for m in g:gmatch"[^ ]+"do f=-~f if h(e,f,f)~=h(m,~0)then break end k=k or m==e end f=f>~1print(f,f and k)

```

# Answer
> 0 votes
# R, 93 bytes

```
a=tolower(readLines(,2));cat(a[1]==gsub("([^ ])\\w* ?","\\1",a[2]),a[1]%in%scan(t=a[2],w=""))

```

Usage:

```
> a=tolower(readLines(,2));cat(a[1]==gsub("([^ ])\\w* ?","\\1",a[2]),a[1]%in%scan(t=a[2],w=""))
Aha
A huge Aha
Read 3 items
TRUE TRUE
> a=tolower(readLines(,2));cat(a[1]==gsub("([^ ])\\w* ?","\\1",a[2]),a[1]%in%scan(t=a[2],w=""))
Acronyms
Acronyms can really obviously narrow your message sensors
Read 8 items
TRUE TRUE
> a=tolower(readLines(,2));cat(a[1]==gsub("([^ ])\\w* ?","\\1",a[2]),a[1]%in%scan(t=a[2],w=""))
FAQ
frequently asked questions
Read 3 items
TRUE FALSE
> a=tolower(readLines(,2));cat(a[1]==gsub("([^ ])\\w* ?","\\1",a[2]),a[1]%in%scan(t=a[2],w=""))
foo
bar baz
Read 2 items
FALSE FALSE

```

# Answer
> 0 votes
# `awk` 137 bytes

```
awk 'BEGIN{T="True";F="False"}NR*NF<2{a=tolower($1)}END{for(i=1;i<=NF;i++)b=b substr(tolower($i),1,1);print(a==b?T:F)"\n"(a==tolower($1)?T:F)}'

```
* Initialize `T="True";F="False"` to simplify output.
* `NR*NF<2{a=tolower($1)}`: set `a` only if the first line only has one field.
* `END{...}`: assuming only two lines...
    + `for(i=1;i<=NF;i++)b=b substr(tolower($i),1,1)`: construct recursive acronym.
    + `print(a==b?T:F)"\n"(a==tolower($1)?T:F)`: print the output of both comparisons, `a==b` and `a==tolower($1)`.

If anyone knows how to optimize the recursive acronym construction, feel free to suggest.

# Answer
> 0 votes
# SpecBAS - 144 bytes

```
1 INPUT a$,b$: LET a$=UP$(a$),b$=UP$(b$),d$="": DIM c$(SPLIT b$,NOT " ")
2 FOR EACH w$ IN c$(): LET d$=d$+w$(1): NEXT w$
3 TEXT d$=a$'POS(a$,b$)>0

```

Converting the 2 x inputs to uppercase saves characters vs. lowercase conversion. Can now have multiple assignments done in one `LET` statement, which also helps. And `TEXT` saves one character over `PRINT`.

Uses 1/0 to show true/false (the apostrophe just moves output to the next line).

# Answer
> 0 votes
# Perl5, 90 bytes

```
($a,$b)=map{chomp;lc}<>;print((join"",map{substr($_,0,1)}split/ /,$b)ne $a?0:($b=~$a?2:1))

```

cheating a bit: 0 = all false, 1 = one true, 2 = both true. I'm not a golfer, but am upset perl is missing while browsing!

```
($a,$b)=map{chomp;lc}<>;              # get the two lines as lowercase
print((                               #
join"",map{substr($_,0,1)}split/ /,$b # collapse first letters of secondline
     ) ne $a  ? 0 : ( $b=~$a ? 2 : 1))# 0 nothing, 1 not recursive, or 2

```

# Answer
> 0 votes
# JavaScript (ES6), ~~89~~ ~~96~~ 95 bytes

```
(a,b)=>[p=(a=a[l='toLowerCase']())==(c=b[l]().split` `).map(x=>x[0]).join``,p&&c.some(x=>x==a)]

```

Shucks...I thought I had it all sorted out, but apparently I was wrong.

This defines an anonymous function which takes input as two strings, and returns and array of two boolean items. The first item is calculated by comparing the the first string in all lowercase with the first char of each word in the second string. The second item is calculated simply by checking if the second string contains the first.

Here's another solution for the second item; 2 bytes shorter, but very few browsers support it:

```
p&&c.includes(a)

```

# Answer
> 0 votes
# JavaScript (ES6) 93

```
(w,s)=>s[L='toLowerCase'](w=w[L](z=y='')).replace(/\w+/g,v=>y+=v[z=z||v==w,0])&&[y=y==w,y&&z]

```

Test running the snippet below in any EcmaScript 6 compliant browser

```
f=(w,s)=>s[L='toLowerCase'](w=w[L](z=y='')).replace(/\w+/g,v=>y+=v[z=z||v==w,0])&&[y=y==w,y&&z]

// TEST

out=x=>O.innerHTML+=x+'\n';

;[
 ['Acronyms', 'Acronyms can really obviously narrow your message sensors', true, true]
,['FAQ', 'frequently asked questions', true, false]
,['foo', 'bar baz', false, false]
,['GNU', 'GNU is not Unix', false, false]
,['Aha', 'A huge Aha', true, true]
,['Lolcat', 'Laughing over lolcat captions and tearing.', true, true]
,['ABCDE', 'Another basic clearly defined example.', true, false]
,['GNU', 'Gnus nettle unicorns', true, false]
,['PHP', 'PHP Hypertext Preprocessor', true, true]
].forEach(([a,b,c,d]) => (
  [r,s]=f(a,b),
  out(((r==c && s==d)?'OK ':'KO ') + a + ',' + b + ' -> ' + f(a,b))
))
```

```
<pre id=O></pre>
```

# Answer
> 0 votes
## Pyke (was untitled when posted), (noncompetitive), 20 bytes

```
l1c"jFh)J"iQl1qDji{&

```

You can find the source code here, language is completely unstable (first test challenge for it) so don't expect it to work in the future (commit 8)

### Or 18 bytes (stableish)

```
l1idcmhsRl1jqDji{&

```

Try it here!

# Answer
> 0 votes
# Jelly, 13 bytes

```
ŒlḲḢ€⁼ɗ,wɗ/«\

```

Try it online!

Takes input as a pair `[phrase, word]`. +2 bytes to input as a newline separated pair with the word first

If the inputs were always in a single case, then this much more elegant program would work for 9 bytes.

This outputs the pair `[a, b]`, where `a` and `b` are truthy values (`1`) or falsey values (`0`). The Footer in the TIO link runs the code over each test case.

## How it works

```
ŒlḲḢ€⁼ɗ,wɗ/«\ - Main link. Takes [phrase, word] on the left
Œl            - Convert both to lowercase
         ɗ    - Group the previous 3 links into a dyad, f(phrase, word):
      ɗ       -   Group the previous 3 links into a dyad, g(phrase, word):
  Ḳ           -     Split the phrase on spaces
   Ḣ€         -     Take the first characters of each word
     ⁼        -     Does this equal the word?
        w     -   Index of word as a sublist of phrase, or 0 if not found
       ,      -   Pair; Yield [g(phrase, word), index]
          /   - Reduce [phrase, word] by f, yielding f(phrase, word)
           «\ - Scan by minimum

```

It is possible for `word` to be a sublist of `phrase`, but not an acronym (for example, `[GNU is not Unix, GNU]`. In this case, `f` returns `[0, 1]` which isn't a valid output. Additionally, `w` returns a non-zero integer, rather than `1/0`, any we want to turn this into `1`.

Therefore, we scan `f`'s return by `«` (minimum), which transforms it:

```
[g(phrase, word), index] «\ = [g(phrase, word), min(g(phrase, word), index)]

```

This zeros out any trailing `1`s, and converts `[1, x]` (where `x > 0`) into `[1, 1]`

# Answer
> 0 votes
# AWK, 107 bytes

```
$0=tolower($0){a="True"}b{for(c="False";$++d;e+=b==$d)f=f substr($d,1,1);$0=(b==f?a:c)"\n"(e?a:c)}!b{b=$1}f

```

Try it online!

Here's a different take using GAWK... The code defines four conditions with associated code blocks. The order they are evaluated when each line is read in matters in this case, to save a couple of characters.

The first condition,

```
$0=tolower($0)

```

is always true given the possible inputs. The check is really unimportant here, the side effect of translating the input line to lowercase it what we care about. The code run just sets variable `a` to the string `True` to shorten the code.

```
{a="True"}

```

The second condition,

```
b

```

is true only for the second input line, since `b` isn't set until the first line is processes. So it's essentially a shortcut for `NR>1`.

```
{for(c="False";$++d;e+=b==$d)f=f substr($d,1,1);e=e?a:c;$0=(b==f?a:c)"\n"e}

```

The code block is two statement, first a `for` loop that processes each word in the input stream. The top of loop statement,

```
c="False"

```

is just setting up `c` as a shortcut for `False` to save characters. Putting here saves a character, since the `;` is already there.

The "should I iterate" test,

```
$++d

```

sets `d` to the current word and stops when we run off the end of the line. And the bottom of the loop statement,

```
e+=b==$d

```

increments `e` everytime the current word matches the acronym from the first line (which is in `b`).

Finally, the body of the loop appends the first character of the current word to `f`, which will end up being the acronym associated with the line.

```
f=f substr($d,1,1)

```

Once the loop is done, the output `$0` is set by concatenating two ternary.

```
$0=(b==f?a:c)"\n"(e?a:c)

```

The `(b==f?a:c)` part is `True` or `False` depending on whether or not the provided and constructed acronyms match. And the second part,

```
(e?a:c)

```

is `True` or `False` based on how many words in the second line matched the acronym from the first line.

The third condition applied to each line just sets `b` to the value of the first line, setting `b` only if is hasn't been set already.

```
!b{b=$1}

```

And the last condition is true only after the second line has been processed.

```
f

```

It uses the default action for unspecified code block. So it's a shortcut for `NR>1{print$0}`.

One caveat: I'm not 100% clear on the rules of the contest. If the second condition depends on the first, meaning only valid acronyms can be recursive acronyms, this slightly longer version is necessary.

```
$0=tolower($0){a="True"}b{for(c="False";$++d;e+=b==$d)f=f substr($d,1,1);$0=(g?a:c)"\n"(e&&(g=b==f)?a:c)}!b{b=$1}f

```

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


title: Generate all solvable 2xN mazes

text:
# Question
Title: Generate all solvable 2xN mazes
Your job is to write a program that takes a number N as input and outputs all 2-by-N mazes that are solvable.

Output format can be in the form of any two distinct values representing wall and empty - I use `x` and `.` here but you can use anything. You can have a matrix, array, string, ascii art, whatever is convenient, and it can be horizontal, as shown in my examples, or vertical.

A maze is solvable if it has a path of empty cells (represented here as `.`) from the left end to the right end. For example,

```
xxxx.....
.....x..x

```

is solvable, because you can trace a path (marked with O):

```
xxxxOOOOO
OOOOOx..x

```

But this is not.

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

```

You cannot pass through diagonal gaps, so this is also not:

```
xxx...
...xxx

```

# Testcases

```
1:

.
.

.
x

x
.

2:

..
..

..
.x

.x
..

..
x.

..
xx

x.
..

xx
..

```

# Answer
> 11 votes
# Excel, ~~163~~ 143 bytes

```
=LET(a,BASE(SEQUENCE(3^A1)-1,3,A1),b,FILTER(a,ISERROR(FIND(12,a))*ISERROR(FIND(21,a))),SUBSTITUTE(b,2,0)&"
"&SUBSTITUTE(SUBSTITUTE(b,1,0),2,1))

```

Use `1` for walls and `0` for empty cells.

## Original

```
=LET(a,BASE(SEQUENCE(3^A1)-1,3,A1),b,FILTER(a,ISERROR(FIND(12,a))*ISERROR(FIND(21,a))),SUBSTITUTE(SUBSTITUTE(b,1,"X"),2,0)&"
"&SUBSTITUTE(SUBSTITUTE(b,2,"X"),1,0))

```

Uses `0` for empty cells and `X` for walls.

Link to Spreadsheet

# Answer
> 8 votes
# C (gcc), ~~192~~ ~~190~~ 188 bytes

* Saved two bytes thanks to ceilingcat using `++u<=`\\$\iff\\$`u++<` and `puts("")`'s return value of `1` (i.e. the number of printed bytes).
* Saved two bytes thanks to ceilingcat; transforming `(a=L>>_+o&1)|(b=L>>o++&1)||(l=v=0),l|=a,v|=b;` into `v=(a=L>>_+o&1)|(b=L>>o++&1)?l|=a,v|b:(l=0);` which when naming the major equivalent segment `@` becomes `@||(l=v=0),l|=a,v|=b;` and `v=@?l|=a,v|b:(l=0);`.

```
s,o,l,v,a,b,L;e(_){for(L=0;L++<1<<2*_;s||puts("")){for(l=v=o=s=0;o<_;s|=l&v)v=(a=L>>_+o&1)|(b=L>>o++&1)?l|=a,v|b:(l=0);for(l=0;l/2<!s;l+=puts(""))for(o=0;o<_;)putchar(46+(L>>l*_+o++)%2);}}

```

Try it online!

---

Uses `.` as a path character and `/` as a wall character. Requires `n < 16` assuming an `int` is 32 bits wide and can thus hold `2*n +1` bits. Due to this problem's combinatorial nature, this restriction should be of little hindrance. Else one may need to consider 128 bit systems.

If one was to allow barely printable characters like tab (ASCII `9`) and newline (ASCII `10 = 9+1`), one could save a byte by substituting `s!46+!9+!`. Even more extremely, outputting literal zeroes and ones, `s!46+!!` would save three bytes.

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

Returns a list of mazes where each maze is a list of `2×1` slices. `0`'s are walls.

```
T2ãIãʒ∊ü&PĀ

```

Try it online! Footer prints mazes horizontally.

Same idea as my APL answer, for each `2×2` submaze check if it is solvable (contains `11` in the top or bottom row).

**Commented:**

```
T            # push integer / string 10
 2ã          # all pairs of 1/0
   Iã        # all n-tuples of pairs of 1/0
             # each n-tuple represents a 2×n maze
     ʒ       # filter the mazes on:
      ∊      #   extend the maze by mirroring (for n=1)
       ü&    #   bitwise and of adjacent maze slices
         PĀ  #   is the product not equal to 0?

```

# Answer
> 5 votes
# Vyxal, ~~109~~ 84 bytes

```
\0⅛\1⅛\2⅛?(¾3n›e(¼_)ƛ0+⅛_nt0=[n›⅛n2+⅛|nt1=[n›⅛|n2+⅛]])ƛ\0`00
`øṙ\1`01
`øṙ\2`10
`øṙ;⁋

```

My first Vyxal answer, which is probably why it's so bad.

-25 bytes thanks to lyxal.

Try it Online!

# Answer
> 4 votes
# Python 3, ~~91~~ 83 bytes

Returns a list of lists of strings with characters `.` and `x`.

```
f=lambda n,*d:[[]][n:]or[w+[x]for x in{'.x','x.'}^{*d,'..'}for w in f(n-1,x[::-1])]

```

Try it online! The output is vertical.

# Answer
> 4 votes
# JavaScript (Node.js), 78 bytes

```
f=n=>n?f(n-1).flatMap(a=>(g=eval(a+=`
`))%22?[a+22,a+g]:[a+12,a+21,a+22]):['']

```

Try it online!

2 as path, 1 as wall

# JavaScript (Node.js), 88 bytes

```
f=n=>n?f(n-1).flatMap(a=>(g=a.slice(0,2),g%11?[11,g]:['01',10,11]).map(_=>_+`
`+a)):['']

```

Try it online!

1 as path, 0 as wall

# Answer
> 4 votes
# Haskell, 66 bytes

```
(d%)
r%0=[[]]
r%n=[h:t|h<-max[d,"x.",".x"][r,d],t<-h%(n-1)]
d=".."

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog Unicode), ~~47~~ ~~40~~ 43 bytes

Assumes `⎕IO←0`, `0`'s are walls.

-7 bytes inspired by this answer.
-4 bytes thanks to Razetime! (Commute  to save on parenthesis, replicate first  instead of replicate along the first axis `/[0]`)

```
{(⌊/⌈/[1]2⌊/x,⌽x)⌿x←(2*2×⍵)2⍵⍴↑⍳2⍴⍨2×⍵}

```

Try it online!

`⌊/⌈/[1]2⌊/x,⌽x` is checking if a maze is solvable, everything else is just generating and filtering all mazes.

# Answer
> 3 votes
# Charcoal, 39 bytes

```
ＮθＥΦＥＸ³θＥ◧⍘ι³θΣλ⬤ι⁻³∧μ⁺λ§ι⊖μＥ²⭆ι§.x⁼⊕λν

```

Try it online! Link is to verbose version of code. Explanation: Represents mazes internally as a list of digits, `0` = no walls, `1` = upper wall, `2` = lower wall. (`3` would be an impossible maze, of course.)

```
Ｎθ                                      Input `N` as a number.
    ＥＸ³θ                                Map over potential mazes
        Ｅ◧⍘ι³θΣλ                         Split into lists of walls
   Φ                                     Filter over mazes where
                ⬤ι                      All columns satisfy
                  ⁻³∧μ⁺λ§ι⊖μ            Consecutive sums do not total 3
  Ｅ                                     Map over filtered mazes
                            Ｅ²          Map over each row
                              ⭆ι        Map over the maze and join
                                §.x⁼⊕λν Select wall or space
                                        Implicitly print

```

# Answer
> 3 votes
# , 43 bytes

```
[:(#~(0=&#.*&(2#.\0,]))/"2)-]\"#.2#:@i.@^+:

```

Try it online!

# Answer
> 3 votes
# Jelly, 11 bytes

```
4ṗ’Ḋ&ƝP$Ƈd2

```

A monadic Link accepting a positive integer that yields a list of lists of pairs where `0` represents a wall and `1` represents space.

**Try it online!**

### How?

```
4ṗ’Ḋ&ƝP$Ƈd2 - Link: integer, n
4           - four
 ṗ          - ([1,2,3,4]) Cartesian power (n) -> all n-tuples made from alphabet [1,2,3,4]
  ’         - decrement -> all n-tuples made from alphabet [0,1,2,3] (first is all zeros)
   Ḋ        - dequeue (remove the first, to make the rest work when n=1)
        Ƈ   - filter keep those for which this is truthy (non zero):
       $    -   last two links as a monad - f(potential):
     Ɲ      -     for neighbours:
    &       -       bitwise AND
      P     -     product
         d2 - div-mod two (vectorises)

```

# Answer
> 2 votes
# Haskell, 80 bytes

```
f n=[m|m<-mapM(["..","x.",".x"]<$f)[1..n],all(<"xx").z(z max)m$tail m]
z=zipWith

```

Try it online!

Takes `n` as input, returns the list of all the \\$2\times n\\$ solvable mazes; each maze is represented as a list of list of characters, where `.` is an empty cell and `x` is a wall.

# Haskell, 81 bytes

```
f 1=pure<$>g e
f n=[x:h:t|h:t<-f$n-1,x<-g h]
g".."=[e,"x.",".x"]
g s=[e,s]
e=".."

```

Try it online!

Recursive version.

# Answer
> 2 votes
# JavaScript (V8), 101 bytes

Prints all solutions, with `0` = empty and `1` = wall.

```
n=>{for(i=q=1<<n;i--;)for(j=q;j--;)i&(j|j*2|j/2)||print((g=n=>n--?[i>>n&1]+[j>>n&1]+`
`+g(n):'')(n))}

```

Try it online!

# Answer
> 1 votes
# Haskell, 75 bytes

A port of my Python answer.

```
(!"")
0!_=[[]]
n!d=[x:w|x<-"..":[w|w<-[".x","x."],w/=d],w<-(n-1)!reverse x]

```

Try it online!

# Answer
> 1 votes
# Pip `-P`, 39 bytes

```
Y3**a[01t00]@^_MtNI_.RV_FI@>(_TB3)My+,y

```

Outputs each maze as a list of 2x1 slices, where `0` is a space and `1` is a wall. Try it online!

Here's a version with nicer output: Try it online!

### Explanation

Observing that a slice with both walls (`11`) is no good, we try all combinations of slices `00`, `01`, and `10`, with the further rule that `01` and `10` cannot be adjacent.

I tried using Cartesian product at first, but found that abusing base conversion was shorter.

```
Y3**a[01t00]@^_MtNI_.RV_FI@>(_TB3)My+,y
                                         a is command-line arg; t is 10 (implicit)
Y3**a                                    Yank 3 to the power of a into y variable
                                   y+,y  Range from y to 2*y
                                  M      For each number in that range:
                             _TB3         Convert to base 3
                          @>(    )        Remove the leading 1
                                         We now have a list of all strings of 0,1,2
                                         whose length equals the input number
                                         0 represents a slice with a wall in the
                                         lower half, 1 with a wall in the upper half,
                                         and 2 a slice with no walls.
                        FI               Filter that list on this function:
                t                         10
                 NI                       is not a substring of
                   _.RV_                  the string concatenated to its reverse
               M                         For each string in the remaining list:
             ^_                           Split it into digits
     [01t00]@                             and use each digit to index into the list
                                          [01;10;00]

```

# Answer
> 0 votes
# Zsh `-F`, 57 bytes

```
eval for\ {1..$1}\ (01 10 00) 'grep -Ev "1 1|10 01"<<<$@'

```

Try it online!

Outputs as a space-separated list of pairs of characters, with `1` representing walls and `0` representing gaps.

* `for\ {1..$1}\ (01 10 00)`: construct the string `for 1 (01 10 00) for 2 (01 10 00) for 3 (01 10 00) ... for n (01 10 00)`
* `eval`uate that string, which is n nested for-loops using the loop variables `1` to `n`, creating all the combinations of `01 10 00` (so all possible mazes)
* `<<<$@` \- print all the variables numbered `1` to `n` separated by spaces
* `grep -Ev "1 1|10 01"` \- filter out combinations which match either `1 1` or `10 01` (i.e., diagonal walls)

---
Tags: code-golf
---


title: Which big number is bigger?

text:
# Question
Title: Which big number is bigger?
**Input**

Integers a1, a2, a3, b1, b2, b3 each in the range 1 to 20.

**Output**

```
True if a1^(a2^a3) > b1^(b2^b3) and False otherwise.

```

^ is exponentiation in this question.

**Rules**

This is code-golf. Your code must terminate correctly within 10 seconds for any valid input on a standard desktop PC.

You can output anything Truthy for True and anything Falsey for False.

You can assume any input order you like as long as its specified in the answer and always the same.

For this question your code should always be correct. That is it should not fail because of floating point inaccuracies. Due to the limited range of the input this should not be too hard to achieve.

**Test cases**

```
3^(4^5) > 5^(4^3)
1^(2^3) < 3^(2^1)
3^(6^5) < 5^(20^3)
20^(20^20) > 20^(20^19)
20^(20^20) == 20^(20^20)
2^2^20 > 2^20^2
2^3^12 == 8^3^11
1^20^20 == 1^1^1
1^1^1 == 1^20^20

```

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

*-2 bytes thanks to Grimy*

```
*.log10* * ***>*.log10* * ***

```

Try it online!

Believe it or not, this is *not* an esolang, even if it is composed of mostly asterisks. This uses Arnauld's formula, with log10 instead of ln.
> 16 votes

# Answer
# , 39 bytes

```
function(x,y,z)rank(log2(x)*(y^z))[1]<2

```

Try it online!

Returns FALSE when `a > b` and TRUE if `b < a`
> 8 votes

# Answer
# 05AB1E, ~~11~~ ~~9~~ ~~11~~ 7 bytes

```
.²Šm*`›

```

Port of *@Arnauld*'s JavaScript and *@digEmAll*'s R approaches (I saw them post around the same time)
-2 bytes thanks to *@Emigna*
+2 bytes as bug-fix after *@Arnauld*'s and *@digEmAll*'s answers contained an error
-4 bytes now that a different input order is allowed after *@LuisMendo*'s comments

Input as `[a1,b1]`, `[a3,b3]`, `[a2,b2]` as three separated inputs.

Try it online or verify all test cases.

**Explanation:**

```
.²       # Take the logarithm with base 2 of the implicit [a1,b1]-input
  Š      # Triple-swap a,b,c to c,a,b with the implicit inputs
         #  The stack order is now: [log2(a1),log2(b1)], [a2,b2], [a3,b3]
   m     # Take the power, resulting in [a2**a3,b2**b3]
    *    # Multiply it with the log2-list, resulting in [log2(a1)*a2**a3,log2(b1)*b2**b3]
     `   # Push both values separated to the stack
      ›  # And check if log2(a1)*a2**a3 is larger than log2(b1)*b2**b3
         # (after which the result is output implicitly)

```
> 6 votes

# Answer
# Java (JDK), 56 bytes

```
(a,b,c,d,e,f)->a>Math.pow(d,Math.pow(e,f)/Math.pow(b,c))

```

Try it online!

## Credits
> 5 votes

# Answer
# Wolfram Language (Mathematica), 23 bytes

```
#2^#3Log@#>#5^#6Log@#4&

```

Try it online!
> 4 votes

# Answer
# , <sup>~~11~~</sup> 9 bytes

```
>&(^.@^/)

```

Try it online!

Arguments given as lists.

* `>` is the left one bigger?
* `&(...)` but first, transform each argument thusly:
* `^.@^/` reduce it from the right to the left with exponention. But because ordinary exponentiation will limit error even for extended numbers, we take the logs of both sides
> 3 votes

# Answer
# Python 3, 68 bytes

```
lambda a,b,c,d,e,f:log(a,2)*(b**c)>log(d,2)*(e**f)
from math import*

```

Try it online!

Port of @Arnualds answer, but with the base for log changed.
> 3 votes

# Answer
# Clean, 44 bytes

```
import StdEnv
$a b c d e f=b^c/e^f>ln d/ln a

```

Try it online!

Uses an adaptation of Arnauld's formula.
> 3 votes

# Answer
# Vyxal, 11 bytes

```
2(?9•??e*)>

```

I'm beginning to understand Vyxal.

Try it Online!
> 3 votes

# Answer
# 05AB1E, 13 bytes

Uses the method from Arnauld's JS answer

```
2F.²IIm*ˆ}¯`›

```

Try it online!
> 2 votes

# Answer
## Excel, 28 bytes

```
=B1^C1*LOG(A1)>E1^F1*LOG(D1)

```

Excel implementation of the same formula already used.
> 2 votes

# Answer
# JavaScript, 51 bytes

```
f=(a,b,c,h,i,j)=>(l=Math.log)(a)*b**c-l(h)*i**j>1e-8

```

~~Surprisingly, the test cases doesn't show any floating-point error. I don't know if it ever does at this size.~~

This just compares the logarithm of the numbers.

Equality tolerance is equal to `1e-8`.
> 2 votes

# Answer
# TI-BASIC, ~~27~~ 31 bytes

```
ln(Ans(1))Ans(2)^Ans(3)>Ans(5)^Ans(6)(ln(Ans(4

```

Input is a list of length \\$6\\$ in `Ans`.
Outputs true if the first big number is greater than the second big number. Outputs false otherwise.

**Examples:**

```
{3,4,5,5,4,3
   {3 4 5 5 4 3}
prgmCDGF16
               1
{20,20,20,20,20,19       ;these two lines go off-screen
{20 20 20 20 20 19}
prgmCDGF16
               1
{3,6,5,5,20,3
  {3 6 5 5 20 3}
prgmCDGF16
               0

```

**Explanation:**

```
ln(Ans(1))Ans(2)^Ans(3)>Ans(5)^Ans(6)(ln(Ans(4   ;full program
                                                 ;elements of input denoted as:
                                                 ; {#1 #2 #3 #4 #5 #6}

ln(Ans(1))Ans(2)^Ans(3)                          ;calculate ln(#1)*(#2^#3)
                        Ans(5)^Ans(6)(ln(Ans(4   ;calculate (#5^#6)*ln(#4)
                       >                         ;is the first result greater than the
                                                 ; second result?
                                                 ; leave answer in "Ans"
                                                 ;implicit print of "Ans"

```

---

**Note:** TI-BASIC is a tokenized language. Character count does ***not*** equal byte count.
> 1 votes

# Answer
# Jelly, 8 bytes

```
l⁵×*/}>/

```

Try it online!

Based on Arnauld’s JS answer. Expects as input `[a1, b1]` as left argument and `[[a2, b2], [a3, b3]]` as right argument.

Now changed to use log to the base 10 which as far as correctly handles all the possible inputs in the range specified. Thanks to Ørjan Johansen for finding the original problem!
> 1 votes

# Answer
# bc -l, 47 bytes

```
l(read())*read()^read()>l(read())*read()^read()

```

with the input read from `STDIN`, one integer per line.

`bc` is pretty fast; it handles a=b=c=d=e=f=1,000,000 in a little over a second on my laptop.
> 1 votes

# Answer
# C++ (gcc), 86 bytes

Thanks to @ØrjanJohansen for pointing out a flaw in this and @Ourous for giving a fix.

```
#import<cmath>
int a(int i[]){return pow(i[1],i[2])/pow(i[4],i[5])>log(i[3])/log(*i);}

```

Try it online!

Takes input as a 6-integer array. Returns 1 if \\$a^{b^c} \> d^{e^f}\\$, 0 otherwise.
> 1 votes

# Answer
# APL(NARS), chars 36, bytes 72

```
{>/{(a b c)←⍵⋄a=1:¯1⋄(⍟⍟a)+c×⍟b}¨⍺⍵}

```

Here below the function z in (a b c )z(x y t) would return 1 if a^(b^c)\>x^(y^t) else would return 0; test

```
  z←{>/{(a b c)←⍵⋄a=1:¯1⋄(⍟⍟a)+c×⍟b}¨⍺⍵}
  3 4 5 z 5 4 3
1
  1 2 3 z 3 2 1
0
  3 6 5 z 5 20 3
0
  20 20 20 z 20 20 19
1
  20 20 20 z 20 20 20
0
  2 2 20 z 2 20 2
1
  2 3 12 z 8 3 11
0
  1 20 20 z 1 1 1
0
  1 1 1 z 1 20 20
0
  1 4 5 z 2 1 1
0

```

{(a b c)←⍵⋄a=1:¯1⋄(⍟⍟a)+c×⍟b} is the function p(a,b,c)=log(log(a))+c\*log(b)=log(log(a^b^c)) and if aa=a^(b^c) with a,b,c \>0 and a\>1 bb=x^(y^t) with x,y,t \>0 and x\>1 than

```
aa>bb <=> log(log(a^b^c))>log(log(x^y^t))  <=>  p(a,b,c)>p(x,y,t)

```

There is a problem with the function p: When a is 1, log log 1 not exist so I choose to represent that with the number -1; when a=2 so log log a is a negative number but \> -1 .

PS. Seen the function in its bigger set in which is defined

```
p(a,b,c)=log(log(a))+c*log(b)

```

appear range for a,b,c in 1..20 is too few... If one see when it overflow with log base 10, the range for a,b,c could be 1..10000000 or bigger for a 64 bit float type.
> 1 votes

---
Tags: code-golf
---


title: The "skip-pure" numbers

text:
# Question
Title: The "skip-pure" numbers
The skip-pure numbers are defined with this rule:

```
A(0) = 1
A(1) = 1
A(n) = the smallest positive number not in the sequence such that A(x) + A(x-2) for any x never appears

```

For example, the term A(2) is 2, because 1 has already appeared. The term A(3) is 4, as A(2) + A(0) = 3 and 3 is disallowed by the third line of the rule.

Given a number n, your program should output the nth skip-pure number, using zero-based indexing (such that A(0) is defined).

Output can be in any format (strings, ints, lists, arrays, etc.), but the number itself must be outputted in base 10.

Trailing output (newlines, etc.) is allowed but only if your language has to output it. If you can work around trailing output, solve it with the workaround.

Here are test cases, shown in the format `input = output`:

```
0 = 1
1 = 1
2 = 2
3 = 4
4 = 6
5 = 7
6 = 9
7 = 10
8 = 12
9 = 13

```

I created this sequence myself and am probably the first person to talk about it, so there is no OEIS link.

This is a code-golf, so the shortest program that does all of the above (measured in bytes) wins. Have fun.

# Answer
> 4 votes
# 05AB1E, ~~20~~ ~~17~~ ~~16~~ 13 bytes

```
‚Qλè∞λÐ¦¦+«Kн

```

-3 bytes by porting *@Arnauld*'s JavaScript answer, so make sure to upvote him!
-6 bytes on my original 20 bytes solution thanks to *@Grimmy*, making it shorter than the port

Outputs the 0-based \\$n^{th}\\$ value, as specified in the challenge description.

Try it online.

Outputting the infinite sequence would be **12 bytes**:

```
1‚λ∞λÐ¦¦+«Kн

```

Try it online.

And outputting the first \\$n\\$ values of the sequence would be **13 bytes** again:

```
‚Qλ£∞λÐ¦¦+«Kн

```

Try it online.

**Explanation:**

```
‚              # Pair the (implicit) input with itself
 Q             # Check for each whether it's equal to the (implicit) input
               # which results in a pair of 1s: [1,1]
  λ            # Create a recursive environment
   è           # to output the 0-based n'th value, where n is the (implicit) input
               # (which will be output implicitly at the end)
               # Starting with a(0)=a(1)=1 due to the earlier [1,1]-pair
               # And for any other a(n) we'll:
    ∞          #  Push an infinite positive list: [1,2,3,...]
     λ         #  Push a list of all previous values: [a(0),a(1),...,a(n-1)]
      Ð        #  Triplicate that list
       ¦¦      #  Remove the first two values from the top copy
         +     #  Add the values in the top two lists together at the same positions,
               #  which also shortens the longer list by two:
               #  [a(0)+a(2),a(1)+a(3),...,a(n-3)+a(n-1)]
          «    #  Merge it to the remaining copy of the triplicate
           K   #  Remove all those values from the infinite positive list
            н  #  Pop and leave the first remaining positive integer

1‚             # Pair 1 with itself (only works if there is no input,
               # in which case it uses the 1 again implicitly)
  λ            # Create a recursive environment
               # to output the infinite list
   ∞λÐ¦¦+«Kн   #  The rest is the same as above

```

# Answer
> 19 votes
# JavaScript (ES7),  ~~59~~  31 bytes

Returns the \\$n\\$-th term, 0-indexed. This is a closed-form formula.

```
n=>n*1.5^Math.log2(n)&n%4==2^!n

```

Try it online!

### Formula

The only edge case is \\$a(0)=1\\$. For \\$n\ge1\\$:

$$a(n)=\cases{\left\lfloor\dfrac{3n}{2}\right\rfloor-1,&\text{if $\lfloor log\_2(n)\rfloor$ is odd and $n\equiv 2\pmod 4$} \\ \left\lfloor\dfrac{3n}{2}\right\rfloor,&\text{otherwise} } $$

# Answer
> 4 votes
# Haskell, 68 bytes

```
a n|n<2=1|q<-n-1=[x|x<-[a q+1..],notElem x[a c+a(c-2)|c<-[2..q]]]!!0

```

Try it online!

Pretty simple answer, doesn't use the formula since that is no fun.

```
a n                   -- a n is ...
  |n<2=1              -- 1 if n less than 2
  |q<-n-1=            -- where q is n-1
    [...]!!0          -- the first element of ...
      x|x<-[a q+1..], -- the integers larger than a(n-1) such that ...
        notElem x[a c+a(c-2)|c<-[2..q]]
          -- it satisfies the condition in the challenge.

```

# Answer
> 2 votes
# Husk, 16 bytes

```
!¡ȯ←`-NS+Sz+↓2ḋ3

```

Try it online!

Outputting the infinite list gives -1. Kinda sad I'm unable to get it below 16.

# Answer
> 1 votes
# Python 2, 76 bytes

```
a=b=1
w=s={1}
exec"w|=s;c=b;b=a\nwhile w&s:a+=1;s={a,a+c}\n"*input()
print b

```

Try it online!

# Answer
> 1 votes
# Python 2, ~~75~~ \\$\cdots\\$ ~~44~~ 42 bytes

Using Arnauld's formula from his JavaScript answer.

Saved ~~2~~ ~~5~~ 8 bytes thanks to Kevin Cruijssen!!!
Saved a whopping ~~8~~ ~~22~~ ~~23~~ 25 bytes thanks to the man himself Arnauld!!!

```
lambda n:0**n^3*n/2^(len(bin(n))%2|n%4==2)

```

Try it online!

**Using the OP's formula**

# Python 3, ~~87~~ 86 bytes

```
f=lambda n,r=[1,1],i=1:i*(len(r)/2>=n)or(i in r)and f(n,r,i+1)or f(n,[i]+r+[i+r[1]],i)

```

Try it online!

# Answer
> 1 votes
# Japt, 17 bytes

Direct port of Arnauld's formula so be sure to `+1` him.

```
*1½^MmU &U%4¥2^!U

```

Try it

# Answer
> 1 votes
# C (gcc), ~~58~~ 42 bytes

Using Arnauld's formula from his JavaScript answer.

Saved a whopping 16 bytes thanks to the man himself Arnauld!!!

```
f(n){n=3*n/2^~__builtin_clz(n)&n%4==2^!n;}

```

Try it online!

# Answer
> 1 votes
# Io, 75 bytes

Port of Arnauld's formula from their JS answer.

```
method(n,(3*n/2)floor-if((n log2 floor%2==0)and(n%2==4),-1,0)+if(n==0,1,0))

```

Try it online!

# Answer
> 1 votes
# , ~~43~~ ~~42~~ 40 bytes

Using the same formula as earlier answers (and Robin's suggestions)

```
n+(n/2)%/%1-(!n%%4-2&log2(n+.1)%%2>1)+!n

```

Try it online!

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


title: The (Easy) Road to Code

text:
# Question
Title: The (Easy) Road to Code
## Input:

* An integer \\$n\\$, which is guaranteed to be \\$\ge3\\$.
* An integer \\$d\\$, which is one of \\$\[-1,0,1\]\\$.

## Output:

A road of size \\$n\\$, which will be in a north-west direction if \\$d=-1\\$; a north direction if \\$d=0\\$; or a north-east direction if \\$d=1\\$. The road will always be three spaces wide (or five in general if we'd include the outer borders). In addition, there will be a road separator line on the bottom section, and after that alternating while going upwards.

**Some examples:**

Input: \\$n=7, d=1\\$
Output:

```
      / / /
     /   /
    / / /
   /   /
  / / /
 /   /
/ / /

```

Input: \\$n=4, d=-1\\$ Output:

```
\   \
 \ \ \
  \   \
   \ \ \

```

## Challenge rules:

* Any amount of leading/trailing spaces and/or newlines are acceptable, as long as it prints the required road somewhere on the screen.
* Instead of the options \\$\[-1,0,1\]\\$ you are also allowed to use the options \\$\[0,1,2\]\\$ or \\$\[1,2,3\]\\$ instead. Also, you can choose which of the three options map to which of the three directions. (Make sure to mention which options you've used if it differs from the \\$\[-1,0,1\]\\$ for `[north-west, north, north-east]` respectively that is used in this challenge description!)
* Any reasonable output format is acceptable. The most common is of course to print it to STDOUT, but returning it as a string or 2D character list is fine as well.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

The two examples above, and:

Input: \\$n=10, d=0\\$
Output:

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

```

# Answer
> 3 votes
# Canvas, ~~23~~ 22 bytes

```
B}⁴H‟ｍ↶⁷？／|∙/╋］＼|∙\╋］｝

```

Try it here!

Uses the direction inputs 0, 1 and 2.

Explanation:

```
...‟    push "--¶¶- ¶¶--"
    m   mold the horizontal length to the 1st input - a horizontal road
     ↶  rotate counter-clockwise - so the separator is on the bottom
        also replaces the dashes with bars

⁷?     ]     ]}  switch over the 2nd input:
                 default case (input 2):
  /                pad with spaces to a "/" diagonal
   |∙/╋            replace "|" with "/"
                 case 0:
        \          pad with spaces to a "\" diagonal
         |∙\╋      replace "|" with ""

case 1 is empty, but because of a bug, the trailing "}" is still required

```

# Answer
> 16 votes
# Python 2, ~~79~~ ~~78~~ ~~73~~ 72 bytes

```
n,d=input()
c='|\/'[d]
i=n
while i:print' '*(n-i*d)+c,i%2*c or' ',c;i-=1

```

Try it online!

Takes `[1,0,-1]` for `[north-west, north, north-east]`

-1 byte, thanks to Neil

# Answer
> 7 votes
# Python 2, 66 bytes

```
n,d=input()
s=' '+'|\/'[d]
for c in(s*n)[n:]:print' '*n+s,c+s;n+=d

```

Try it online!

Uses `d=-1` for NE, `d=0` for N, and `d=1` for NW. Takes advantage of leading spaces being allowed. The rule that the *bottom* segment of the road have a separator made it tricky to get the parity right; it's achieved by the slicing `(s*n)[n:]` taking the second half of the `2n` alternations between space and a the road character.

# Answer
> 6 votes
# 1. Python 3.5, 122 120 bytes

Script takes two params: n, d.

d: 0, 1, 2 -\> \ | /

tio.run

```
import sys;(n,d)=[*map(int,sys.argv[1:3])];c="\\|/"[d]
for i in range(n):j=n+~i;print(" "*(i,0,j)[d],c,c*(j%2<1)or" ",c)

```

output:

```
$ ./script.py 6 2
      /   /
     / / /
    /   /
   / / /
  /   /
 / / /
$ ./script.py 6 1
 |   |
 | | |
 |   |
 | | |
 |   |
 | | |
$ ./script.py 6 0
 \   \
  \ \ \
   \   \
    \ \ \
     \   \
      \ \ \

```

## Explanation

```
# parse input params
(n,d)=[*map(int,sys.argv[1:3])]

# select char for "road"
c="\\|/"[d]

# loop n-times
for i in range(n):

    # complement (how many lines to end)
    j=n+~i

    # print
    #   space i or 0 or j times
    #   road, center of road if j is even else space, road
    print(" "*(i,0,j)[d], c, c*(j%2<1) or " ", c)

```

edit: -2 bytes thanks to Kevin Cruijssen

# Answer
> 5 votes
# PowerShell, ~~88~~ ~~82~~ ~~80~~ ~~74~~ 71 bytes

-8 bytes thanks to Mazzy
-6 bytes thanks to AdmBorkBork and Mazzy
-3 bytes thanks to AdmBorkBork

```
param($n,$d)$n..1|%{' '*($_,($n-$_))[$d]+($y='/\|'[$d])," $y"[$_%2],$y}

```

Try it online!

Uses \[0,1,2\] for NW, NE, N. Uses `d` as a list index twice to first get the spacing method (Drops off the list when using 2 which returns 0) and then which character to use when drawing the lines. Appends a list to the string of spaces (which innately has spaces between the members when appended as such) which builds the road. Also swaps between an open lane or a dash based on modulo math.

# Answer
> 5 votes
# Charcoal, ~~33~~ ~~29~~ 23 bytes

```
↷ＮＮη⊘⊕ηＵＥ¹¦¹Ｆ⟦²±²⟧«Ｊι⁰η

```

Try it online! Link is to verbose version of code. Now that all of the underlying Charcoal bugs seem to be fixed I can advertise the optimal code. Explanation:

```
↶Ｎ

```

Rotate the cursor direction anticlockwise according to the first input, so that 1 becomes north east, 2 north and 3 north west.

```
Ｎη

```

Input the length of the road.

```
⊘⊕ηＵＥ¹¦¹

```

Print half the length of the road and then stretch it giving the road separator.

```
Ｆ⟦²±²⟧«Ｊι⁰η

```

Print the sides of the road.

@KevinCruijssen subsequently submitted a harder version of this question which was since deleted but users with enough rep can see it here: The (Hard) Road to Code The stretching trick I used in this answer isn't applicable to that question, so instead I wrote the following ~~47~~ 45-byte program:

```
Ｆ³«Ｊ×ι⊘⊕θ⁰≔…⟦¹ ⟧⊕﹪ι²ιＦη«↶§κ⁰Ｆ⊖§κ¹§ιⅉＰ§ιⅉ↑↷§κ⁰

```

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

```
Ｆ³«

```

Loop over the sides and separator.

```
Ｊ×ι⊘⊕θ⁰

```

Jump to the start of the side.

```
≔…⟦¹ ⟧⊕﹪ι²ι

```

Make an array containing a `1` and a space, but remove the space again if we're drawing the sides rather than the separator.

```
Ｆη«

```

Loop over each road section.

```
↶§κ⁰

```

Rotate the cursor direction accordingly.

```
Ｆ⊖§κ¹

```

Loop over one less than the length of the road section...

```
§ιⅉ

```

... and print alternating elements of the array. The alternation is achieved by cyclically indexing into the array with the Y-coordinate of the cursor.

```
Ｐ§ιⅉ

```

Print the last row of this road section, but without moving the cursor...

... so that the cursor can be moved up ready for the next section instead.

```
↷§κ⁰

```

Rotate the cursor direction back ready for the next section.

# Answer
> 5 votes
# C (gcc), ~~100~~ 90 bytes

```
f(a,b,c,d){for(c=a,d="\\|/"[b+1];c--;)printf("%*c %c %c\n",b>0?c+1:b?a-c:0,d,c%2?32:d,d);}

```

Try it online!

---

Well written version

# Answer
> 4 votes
# Kotlin, ~~96~~ 92 bytes

```
{n,d->val c="\\|/"[d];(0..n-1).map{println(" ".repeat(n-it*(d-1))+ "$c ${" $c"[it%2]} $c")}}

```

Accepts \[0, 1, 2\] instead of \[-1, 0, 1\]

It works similarly to solutions in other languages, but unfortunately Kotlin doesn’t really shine in this one.

`val c=“\\|/“;` retrieves the char to use in road building by taking advantage of the fact that Kotlin treats Strings like an Array of chars (as it should, looking at you Java)

Try it online!

# Answer
> 4 votes
# TSQL code, ~~171~~ 117 bytes

I realized this could be written much shorter as code.

```
DECLARE @n INT=7,@d INT=0

,@ INT=0a:PRINT
space(@n-@*@d)+stuff(replicate(substring('\|/',@d+2,1)+' ',3),3,@%2,space(@%2))SET
@+=1IF @n>@ GOTO a

```

# TSQL query, 137 bytes

```
USE master
DECLARE @n INT=6,@ INT=-1

SELECT space(@n-y*@)+z+iif(y%2=1,z,'  ')+z
FROM(SELECT top(@n)row_number()over(order
by @)y,' '+substring('\|/',@+2,1)z FROM spt_values)x

```

*USE master* is not necessary, if your database is master already. Some users however have a different default database.

Script when *trying it out* is slightly different. I had to replace space ascii-32 with ascii-160, the spaces were not shown.

**Try it out**

Made some tweaks and realized that I could replace

> order by 1/0

with

> order by @

# Answer
> 3 votes
# JavaScript (ES8),  ~~90 87~~  85 bytes

Takes input as `(direction)(length)`. Expects \\$0\\$ for North-West, \\$1\\$ for North or \\$2\\$ for North-East.

```
d=>g=(n,w=n)=>n?(c='/|\\'[d]).padStart([n--,,w-n][d])+` ${n&1?' ':c} ${c}
`+g(n,w):''

```

Try it online!

---

# JavaScript (ES6), 90 bytes

This one draws the output character by character with a little more maths instead of the `.padStart()` method.

Takes input as `(direction)(length)`. Expects \\$1\\$ for North-West, \\$2\\$ for North or \\$3\\$ for North-East.

```
d=>n=>(g=x=>y?` /|\\
`[x+5?17+y%2*4>>--x+5-[,n+1-y,n,y][d]&1&&d:(x=n,y--,4)]+g(x):'')(y=n)

```

Try it online!

# Answer
> 3 votes
# Jelly,  ~~31~~  30 bytes

```
⁶ẋẋƤḂ};€ị“\/|”ẋ3KƊ}Ṛ⁹¡⁶-2¦€ÐeṚ

```

A dyadic Link accepting the length on the left and the negated-direction\* on the right which yields a 2d array of characters.
* `[north-west, north, north-east]=[1, 0, -1]`

**Try it online!** (footer calls the Link, joins with newline characters and prints the result)

### How?

```
⁶ẋẋƤḂ};€ị“\/|”ẋ3KƊ}Ṛ⁹¡⁶-2¦€ÐeṚ - Link: integer, L; integer, D
⁶                              - space character
 ẋ                             - repeat L times
     }                         - using the right argument (D):
    Ḃ                          -   mod 2 (0 if D = 0, 1 otherwise ...A would work too)
   Ƥ                           - for each prefix (of the list of spaces):
  ẋ                            -   repeat (D mod 2 times)
                  }            - using the right argument (D):
                 Ɗ             -   last three links as a monad:
        ị“\/|”                 -     index into "\/|" (1-indexed & modular)
              ẋ3               -     repeat three times - e.g. "\\\"
                K              -     join with spaces          "\ \ \"
      ;€                       - concatenate €ach (altered prefix with that list)
                     ¡         - repeat action...
                    ⁹          - ...number of times: right argument (-1 repeats 0 times)
                   Ṛ           - ...action: reverse (i.e. reverse if north-west)
                           Ðe  - for even indexes:
                         ¦€    -   sparse application for €ach...
                       -2      -   ...to indices: [-2] (the middle of the road)
                      ⁶        -   ...action: a space character
                             Ṛ - reverse

```

# Answer
> 2 votes
# Python 2, 127 bytes

```
n,d=input()
c='|/\\'[d]
for i in range(n):t=0if d==0else(i if d<0else n-i);print(' '*t+'{} {} {}'.format(c,' 'if i%2==0else c,c))

```

Try it online!

First two lines taken from @TFeld.

# Answer
> 2 votes
# , 64 bytes

```
' \|/'{~(_2&|*[:i.[*1 _1{~3=])|."_1((5+[){."1(5,~[)|.@$]*#:@689)

```

Try it online!

* 1 North-West
* 2 North
* 3 North-East

Will try to golf it later

# Answer
> 2 votes
# Python 2, 93 bytes

```
n,d=input();p=''
while n:g='|/\\'[d];n-=1;print['',' '*n,p][d]+g+' %s '%(g,' ')[n%2]+g;p+=' '

```

Try it online!

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), ~~129~~ ~~107~~ ~~103~~ 93 bytes

```
a=>b=>{for(char i=a,W="/|\\"[b+1];i>0;)Write("{0,"+(a-i*b+5)+"} {1} {0}\n",W,--i%2<1?W:' ');}

```

-1 for north-east, 1 for north-west, 0 for north

Try it online!

# Answer
> 2 votes
# Vyxal, 91 bytes

```
£:0=[¥(n₂[`| | |`|`|   |`],)|1=[¥(ðn*n₂[`\ \ \\`|`\   \\`]+,)|¥(ð¥‹n-*n₂[`/ / /`|`/   /`]+,

```

Try it Online!

A little better.

# Answer
> 1 votes
# Red, 157 bytes

```
func[s d][p: pick"\|/"d set[a b]reduce pick[[4 1]0[5 + s -1]]d
repeat n s[print pad/left form reduce pick[[p" "p][p p p]]odd?(n + pick[1 0]odd? s)a: a + b]]

```

Try it online!

* 1 North-West
* 2 North
* 3 North-East

# Answer
> 1 votes
# Japt, 53 bytes

```
W="|/\\"gV;Æ"{W} {YÉ %2?W:' } {W}"ùVÄ?V?Y+5:5:U-Y+4Ãw

```

Try it Online!

# Answer
> 1 votes
# Stax, 23 bytes

```
ù╒←∩♂2Ωⁿ¡├∩22♀Ç○=÷â╧δÖ↑

```

Run and debug it

Input is two integers separated by a space.
The first is `d`. -1 specifies north-east. 0 for north. 1 for north-west. The second parameter is `n`. These two values will get implicitly parsed from input and placed on the input stack with `n` on top. Additionally `d` will be accessible from the stax's `x` register since it's the first implicitly parsed value.

For example, input "1 7"

```
            Main stack      Explanation
            ----------      -----------
;           [7]             peek from input stack
m                           map over integers [1..n] using the rest of the program
                            output each produced value implicitly
  ;         [1 7]           peek from input stack
  +         [8]             add
  .*"       [8 [42 34]]     2 character string literal with codepoints 42 and 34
  @         [42]            get the element at the specified modular index (8)
  0         [42 0]          literal zero
  "|\/"x@   [42 0 92]       get codepoint from string literal at input d (from x register)
  \         [42 [0 92]]     make pair
  :B        ['\ \ \ ']      encode in custom base; it's binary with custom codepoints
  _x*       ['\ \ \ ' 1]    (loop variable) * (input d)
  ;^        ['\ \ \ ' 1 8]  peek from input stack and increment
  %         ['\ \ \ ' 1]    modulus
  6+        ['\ \ \ ' 7]    add 6
  )         [' \ \ \ ']     left-pad to length

```

Run this one

# Answer
> 1 votes
# Swift 4.2, ~~112~~ 108 bytes

-4 bytes thanks to Sriotchilism O'Zaic

```
let c=["\\","|","/"][d];(0..<n).map{print((0..<n-$0*(d-1)).map{_ in" "}.joined()+c+" \($0%2==0 ?c:" ") "+c)}

```

\[0,1,2\] instead of \[-1,0,1\].

Try it online!

## Explanation

```
let c=["\\","|","/"][d]

```

Determines the street sign to use. (I bet this can be shortened somehow)

```
(0..<n).map{

```

Iterates over the length of the street.

```
(0..<n-$0*(d-1)).map{_ in" "}.joined()

```

Adds the spaces in front of the street.

```
\($0%2==0 ?c:" ")"

```

Adds the middle sign to every other line.

My very first one ☝, I'm happy about any optimization advices. Learned mostly from that thread: Tips for golfing in Swift.

# Answer
> 1 votes
# Perl 6, 66 bytes

```
->\n,\d{{(' 'x--$ *d%-+^n~(' ',<\ | />[d+1])[1,(n+$++)%2,1])xx n}}

```

Try it online!

Returns a list of lines.

### Explanation

```
->\n,\d{                                                         }  # Block taking n, d
        {                                                       }   # Reset $ variables
         (                                                 )xx n    # Repeat n times
          ' 'x  # Space times
              --$ *d  # (-1,-2,-3,...) if d=1
                      # (0,0,0,...) if d=0
                      # (1,2,3,...) if d=-1
                    %-+^n  # modulo -~n = n+1
                         ~  # Concat
                          (' ',<\ | />[d+1])  # Space or line
                                            [1,(n+$++)%2,1]  # Alternate middle char

```

# Answer
> 1 votes
# Ruby, 90 bytes

```
n,a=*$*.map{|i|-i.to_i}
c='|\/'[a]
n.upto(-1){|i|puts' '*(i*a-n)+c+' '+[' ',c][i%2]+' '+c}

```

Try it online!

UPDATE: Thank you, Kevin, for pointing out that my original submission was missing spaces between the road edges and markers (i.e., 3-width roads instead of 5-width.) That said, there might be a shorter fix for that than `c+' '+...+' '+c`.

Directional information: `-1, 0, 1` maps to `{ north-west, north, north-east }`

Arguments: this reads command-line arguments such as `4 -1` (a four row road, slanted to the north-west).

Additional note: This was tested locally with Ruby v2.6.1, and it appears that *Try It Online* uses Ruby v2.5.3. I have no reason to think it would not work with all other Ruby versions.

# Answer
> 1 votes
# Java (JDK), 116 bytes

```
d->n->{for(int c="\\|/".charAt(d),i=n;i-->0;)System.out.printf("%"+(d<1?n-i:d>1?i+1:1)+"c%2c %c%n",c,i%2<1?c:32,c);}

```

Try it online!

Takes `d` as one of `0`, `1` or `2`.

# Answer
> 1 votes
# Japt `-R`, 40 bytes

```
Æ=Vg"|\\/";²i1S+iX%2?S:U)iSp[TZÊ-YY]gVÃw

```

Try it online!

### Explanation:

```
Æ=Vg"|\\/";²i1S+iX%2?S:U)iSp[TZÊ-YY]gVÃw
                                            // U = road size
                                            // V = direction
Æ                                     Ã     // Loop X through [0...U]
 =        ;                                 //   Set U to:
    "|\\/"                                  //       "|\/"
  Vg                                        //            [V]
           ²                                //  Double U
            i1          )                   //  Insert at index 1:
              S+                            //    " " +
                 X%2?S:U                    //         X%2?" ":U
                i                           //                  + " "
                         i                  //  Insert at index 0:
                          Sp                //    " " repeated this many times:
                            [TZÊ-YY]        //      [0,U.length - X,X]
                                    gV      //                        [V]
                                        w   // Reverse output

```

# Answer
> 0 votes
# perl -M5.010 -Mfeature=signatures, 97 bytes

```
sub f($n,$d){$x=qw[| / \\][$d];say" "x($d<1?$_*-$d:$n-$_),$x,$",($n-$_)%2?$":$x,$",$x for 1..$n;}

```

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