title: Beware of the matrix tornado!

text:
# Question
Title: Beware of the matrix tornado!
The matrix tornado is just like any other tornado: it consists of things rotating around a center. In this case, elements of the matrix instead of air.

Here is an example of a matrix tornado:

First we start by sectioning the matrix into square rings, each section consists of elements that are farther away from the border by the same distance. These sections will be rotated clockwise around the center. In real tornadoes, the severity increases towards the center, and so does the rotation step in a matrix tornado: the outermost section (the red one) is rotated by 1 step, the next (the yellow) one is rotated by 2, and so on. A rotation step is a 90° rotation around the center.

### Task:

Your task, should you accept it, is to write a function or program that takes as input a square matrix, apply the tornado effect to it and then output the resulting matrix.

### Input:

The input should be a square matrix of order `n` where `n >= 1`. No assumption is to be made about the elements of the matrix, they could be anything.

### Output:

A square matrix of the same order which would be the result of applying the tronado effect to the input matrix.

### Examples:

A matrix of order `n = 1`:

```
[['Hello']]               ===>    [['Hello']]

```

A matrix of order `n = 2`:

```
[[1 , 2],                 ===>    [[5 , 1],
 [5 , 0]]                          [0 , 2]]

```

A matrix of order `n = 5`:

```
[[A , B , C , D , E],             [[+ , 6 , 1 , F , A],
 [F , G , H , I , J],              [- , 9 , 8 , 7 , B],
 [1 , 2 , 3 , 4 , 5],     ===>     [/ , 4 , 3 , 2 , C],
 [6 , 7 , 8 , 9 , 0],              [* , I , H , G , D],
 [+ , - , / , * , %]]              [% , 0 , 5 , J , E]]

```

# Answer
# Python 3, ~~100~~ ~~97~~ 96 bytes

-3 bytes thanks to Graipher by changing `rot90(a,axes=(1,0))` to `rot90(a,1,(1,0))`
-1 byte thanks to Kevin Cruijssen by removing a space

```
import numpy
def f(a):
 if len(a):a=numpy.rot90(a,1,(1,0));a[1:-1,1:-1]=f(a[1:-1,1:-1]);return a

```

Try it online!
> 6 votes

# Answer
# Charcoal, 44 bytes

```
≔ＥθＳθＷθ«≔Ｅθ⮌⭆θ§§θνλθθＭ¹⁻¹Ｌθ≔Ｅ✂θ¹±¹¦¹✂κ¹±¹¦¹θ

```

Try it online! Link is to verbose version of code. Only works on character squares because Charcoal's default I/O doesn't do normal arrays justice. Explanation:

```
≔ＥθＳθ

```

Read the character square.

```
Ｗθ«

```

Loop until it's empty.

```
≔Ｅθ⮌⭆θ§§θνλθ

```

Rotate it.

```
θＭ¹⁻¹Ｌθ

```

Print it, but then move the cursor to one square diagonally in from the original corner.

```
≔Ｅ✂θ¹±¹¦¹✂κ¹±¹¦¹θ

```

Trim the outside from the array.
> 5 votes

# Answer
# Jelly, 27 bytes

```
J«þ`UṚ«Ɗ‘ịZU$LÐ¡ŒĖḢŒHEƊƇṁµG

```

Try it online!

I think this could be far shorter.

```
           Input: n×n matrix A.
J          Get [1..n].
 «þ`       Table of min(x, y).
    UṚ«Ɗ   min with its 180° rotation.

Now we have a matrix like: 1 1 1 1 1
                           1 2 2 2 1
                           1 2 3 2 1
                           1 2 2 2 1
                           1 1 1 1 1

‘ị          Increment all, and use as indices into...
     LÐ¡    List of [A, f(A), f(f(A)), …, f^n(A)]
  ZU$       where f = rotate 90°

Now we have a 4D array (a 2D array of 2D arrays).
We wish to extract the [i,j]th element from the [i,j]th array.

ŒĖ     Multidimensional enumerate

This gives us: [[[1,1,1,1],X],
                [[1,1,1,2],Y],
                ...,
                [[n,n,n,n],Z]]

ḢŒHEƊƇ     Keep elements whose Ḣead (the index) split into equal halves (ŒH)
           has the halves Equal to one another. i.e. indices of form [i,j,i,j]
           (Also, the head is POPPED from each pair, so now only [X] [Y] etc remain.)

ṁµG        Shape this like the input and format it in a grid.

```
> 5 votes

# Answer
# Perl 6, ~~78 73~~ 72 bytes

*Thanks to nwellnhof for -5 bytes!*

```
$!={my@a;{(@a=[RZ] rotor @_: sqrt @_)[1..*-2;1..@a-2].=$!}if @_;@a[*;*]}

```

Try it online!

Recursive code block that takes a flattened 2D array and returns a similarly flattened array.

### Explanation:

```
$!={      # Assign code block to pre-declared variable $!
    my@a; # Create local array variable a
   {
     (@a=[RZ]  # Transpose:
             rotor @_: sqrt @_;  # The input array converted to a square matrix
     )[1..*-2;1..@a-2].=$!  # And recursively call the function on the inside of the array
   }if @_;    # But only do all this if the input matrix is not empty
   @a[*;*]  # Return the flattened array
}

```
> 5 votes

# Answer
# Octave,  ~~86~~ 81 bytes

```
f(f=@(g)@(M,v=length(M))rot90({@(){M(z,z)=g(g)(M(z=2:v-1,z)),M}{2},M}{1+~v}(),3))

```

Try it online!

I'm aware that recursive anonymous functions are not the shortest method to do things in Octave, but they're the most *fun* method by far. This is the shortest anonymous function I could come up with, but I'd love to be outgolfed.

### Explanation

The recursive function is defined according to this answer by ceilingcat. `q=f(f=@(g)@(M) ... g(g)(M) ...` is the basic structure of such an anonymous function, with `g(g)(M)` the recursive call. Since this would recurse indefinitely, we wrap the recursive call in a conditional cell array: `{@()g(g)(M),M}{condition}()`. The anonymous function with empty argument list delays evaluation to after the condition has been selected (although later, we see that we can use that argument list to define `z`). So far it has just been basic bookkeeping.

Now for the actual work. We want the function to return `rot90(P,-1)` with P a matrix on which `g(g)` has been recursively called on the central part of M. We start by setting `z=2:end-1` which we can hide in the indexing of M. This way, `M(z,z)` selects the central part of the matrix that needs to be tornadoed further by a recursive call. The `,3` part ensures that the rotations are clockwise. If you live on the southern hemisphere, you may remove this bit for -2 bytes.

We then do `M(z,z)=g(g)M(z,z)`. However, the result value of this operation is only the modified central part rather than the entire `P` matrix. Hence, we do `{M(z,z)=g(g)M(z,z),M}{2}` which is basically stolen from this answer by Stewie Griffin.

Finally, the `condition` is just that the recursion stops when the input is empty.
> 5 votes

# Answer
# Python 2, 98 bytes

```
def f(a):
 if a:a=zip(*a[::-1]);b=zip(*a[1:-1]);b[-2:0:-1]=f(b[-2:0:-1]);a[1:-1]=zip(*b)
 return a

```

Try it online!
> 4 votes

# Answer
# , 87 bytes

```
function(m,n=nrow(m)){for(i in seq(l=n%/%2))m[j,j]=t(apply(m[j<-i:(n-i+1),j],2,rev));m}

```

Try it online!
> 4 votes

# Answer
# MATL,  ~~25 24 23~~ 22

```
t"tX@Jyq-ht3$)3X!7Mt&(

```

Try it online!

Indexing in MATL is never easy, but with some golfing it actually beats the current best Jelly answer...

```
t                       % Take input implicitly, duplicate.
 "                      % Loop over the columns of the input*
   X@                   % Push iteration index, starting with 0. Indicates the start of the indexing range.
     Jyq-               % Push 1i-k+1 with k the iteration index. Indicates the end of the indexing range
         t              % Duplicate for 2-dimensional indexing.
  t       3$)           % Index into a copy of the matrix. In each loop, the indexing range gets smaller
             3X!        % Rotate by 270 degrees anti-clockwise
                7Mt&(   % Paste the result back into the original matrix.

```

\*For an `n x n` matrix, this program does `n` iterations, while you really only need `n/2` rotations. However, the indexing in MATL(AB) is sufficiently flexible that indexing impossible ranges is just a no-op. This way, there's no need to waste bytes on getting the number of iterations just right.
> 4 votes

# Answer
# JavaScript (ES6), 99 bytes

```
f=(a,k=m=~-a.length/2)=>~k?f(a.map((r,y)=>r.map(v=>y-m>k|m-y>k|--x*x>k*k?v:a[m+x][y],x=m+1)),k-1):a

```

Try it online!

### How?

Given a square matrix of width \\$W\\$, we define:

$$m=\frac{W-1}{2}\\ t\_{x,y}=\max(|y-m|,|x-m|)$$

Example output of \\$t\_{x,y}\\$ for a 5x5 matrix (\\$W=5\\$, \\$m=2\\$):

$$\begin{pmatrix} 2 & 2 & 2 & 2 & 2 \\ 2 & 1 & 1 & 1 & 2 \\ 2 & 1 & 0 & 1 & 2 \\ 2 & 1 & 1 & 1 & 2 \\ 2 & 2 & 2 & 2 & 2 \end{pmatrix}$$

We start with \\$k=m\\$ and perform a 90° clockwise rotation of all cells \\$(x,y)\\$ satisfying:

$$t\_{x,y}\le k$$

while the other ones are left unchanged.

This is equivalent to say that a cell is ***not*** rotated if we have:

$$(y-m\>k) \text{ OR } (m-y\>k) \text{ OR } (X^2\>k^2)\text{ with }X=m-x$$

which is the test used in the code:

```
a.map((r, y) =>
  r.map(v =>
    y - m > k | m - y > k | --x * x > k * k ?
      v
    :
      a[m + x][y],
    x = m + 1
  )
)

```

Then we decrement \\$k\\$ and start again, until \\$k=-1\\$ or \\$k=-3/2\\$ (depending on the parity of \\$W\\$). Either way, it triggers our halting condition:

```
~k === 0

```
> 3 votes

# Answer
# K (ngn/k), ~~41~~ ~~39~~ 38 bytes

```
{s#(+,/'4(+|:)\x)@'4!1+i&|i:&/!s:2##x}

```

Try it online!

`{` `}` function with argument `x`

`#x` length of `x` \- the height of the matrix

`2##x` two copies - height and width (assumed to be the same)

`s:` assign to `s` for "shape"

`!s` all indices of a matrix with shape `s`, e.g. `!5 5` is

```
(0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4
 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4)

```

This is a 2-row matrix (list of lists) and its columns correspond to the indices in a 5x5 matrix.

`&/` minimum over the two rows:

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

```

`i&|i:` assign to `i`, reverse (`|`), and take minima (`&`) with `i`

```
0 0 0 0 0 0 1 1 1 0 0 1 2 1 0 0 1 1 1 0 0 0 0 0 0

```

These are the flattened ring numbers of a 5x5 matrix:

`4!1+` add 1 and take remainders modulo 4

`(+|:)` is a function that rotates by reversing (`|` \- we need the `:` to force it to be monadic) and then transposing (`+` \- since it's not the rightmost verb in the "train", we don't need a `:`)

`4(+|:)\x` apply it 4 times on `x`, preserving intermediate results

`,/'` flatten each

`+` transpose

`(` `)@'` index each value on the left with each value on the right

`s#` reshape to `s`
> 3 votes

# Answer
# Jelly, 24 bytes

```
ṙ⁹ṙ€
ḊṖ$⁺€ßḷ""ç1$ç-ZUµḊ¡

```

Try it online!

> I think this could be far shorter.

*Lynn*
> 3 votes

# Answer
# Haskell, 108 bytes

```
e=[]:e
r=foldl(flip$zipWith(:))e
g!(h:t)=h:g(init t)++[last t]
f[x,y]=r[x,y]
f[x]=[x]
f x=r$(r.r.r.(f!).r)!x

```

Try it online!

I used Laikoni's transpose and modified it a little, to rotate an array 90°:

```
  e=[]:e;foldr(zipWith(:))e.reverse
≡ e=[]:e;foldl(flip$zipWith(:))e

```

# Explanation

`r` rotates an array by 90°.

`(!)` is a higher-level function: “apply to center”. `g![1,2,3,4,5]` is `[1] ++ g[2,3,4] ++ [5]`.

`f` is the tornado function: the base cases are size 1 and 2 (somehow 0 doesn't work).

The last line is where the magic happens: we apply `r.r.r.(f!).r` on the middle rows of `x` and then rotate the result. Let's call those middle rows **M**. We want to recurse on the middle *columns* of **M**, and to get at those, we can rotate **M** and then use `(f!)`. Then we use `r.r.r` to rotate **M** back into its original orientation.
> 3 votes

# Answer
# , 37 bytes

```
<./~@g`(|:@|.^:(1<@+>./@g=.#\.<.#\))}

```

Try it online!

Independently solved, but this approach is very similar to Lynn's.

It is also one of the most perfect problems for J's little used "composite item" `}` (in gerund form) that I have come across.
> 3 votes

# Answer
# Java 10, ~~198~~ ~~192~~ ~~181~~ ~~174~~ 173 bytes

```
m->{int d=m.length,b=-1,i,j;var r=new Object[d][d];for(;b<d/2;){for(i=b++;++i<d-b;)for(j=b;j<d-b;)r[j][d+~i]=m[i][j++];for(i=d;i-->0;)m[i]=r[i].clone();}return r;}

```

-25 bytes thanks to *@ceilingcat*

Try it online.

**Explanation:**

```
m->{                      // Method with Object-matrix as both parameter & return-type
  int d=m.length,         //  Dimensions of the matrix
      b=-1,               //  Boundaries-integer, starting at -1
      i,j;                //  Index-integers
  var r=new Object[d][d]; //  Result-matrix of size `d` by `d`
  for(;b<d/2;){           //  Loop `b` in the range (-1,`d/2`]:
    for(i=b++;++i<d-b;)   //   Inner loop `i` in the range [`b`,`d-b`):
      for(j=b;j<d-b;)     //    Inner loop `j` in the range [`b`,`d-b`):
        r[j][d+~i]=       //     Set the `j,d-i-1`'th result-cell to:
          m[i][j++];      //      The `i,j`'th cell-value of the input-matrix
    for(i=d;i-->0;)       //   Inner loop `i` in the range (`d`,0]:
      m[i]                //    Change the `i`'th row of the input-matrix
        =r[i].clone();}   //     to a copy of the `i`'th row of the result-matrix
  return r;}              //  Return the result-matrix

```

`b` is basically used to indicate which ring we're at. And it will then rotate this ring (including everything inside it) once clockwise during every iteration.

The replacement of the input-matrix is done because Java is pass-by-reference, so simply setting `r=m` would mean both matrices are modified when copying from cells, causing incorrect results. We therefore instead have to copy the values in every cell one row at a time, without copying their reference (by using `.clone()`).
> 2 votes

# Answer
# Haskell, 274 bytes

`w` is the main function, which has the type `[[a]] -> [[a]]` that you would expect.

I'm sure a more experienced Haskell golfer could improve on this.

```
w m|t m==1=m|0<1=let m'=p m in(\a b->[h a]++x(\(o,i)->[h o]++i++[f o])(zip(tail a)b)++[f a])m'(w(g m'))
p m|t m==1=m|0<1=z(:)(f m)(z(\l->(l++).(:[]))(r(x h(i m)):(p(g m))++[r(x f(i m))])(h m))
t[]=1
t[[_]]=1
t _=0
h=head
f=last
x=map
i=tail.init
g=x i.i
z=zipWith
r=reverse

```
> 1 votes

# Answer
# MATLAB, 93 bytes

```
function m=t(m),for i=0:nnz(m),m(1+i:end-i,1+i:end-i)=(rot90(m(1+i:end-i,1+i:end-i),3));end;end

```

I'm sure this can be golfed some more somehow.

**Explanation**

```
function m=t(m),                                                                          end % Function definition
                for i=0:nnz(m),                                                       end;    % Loop from 0 to n^2 (too large a number but matlab indexing doesn't care)
                                                            m(1+i:end-i,1+i:end-i)            % Take the whole matrix to start, and then smaller matrices on each iteration
                                                      rot90(                      ,3)         % Rotate 90deg clockwise (anti-clockwise 3 times)
                               m(1+i:end-i,1+i:end-i)=                                        % Replace the old section of the matrix with the rotated one

```
> 1 votes

# Answer
# C (gcc), 128 118 115 bytes

-15 bytes from @ceilingcat

```
j,i;f(a,b,w,s)int*a,*b;{for(j=s;j<w-s;j++)for(i=s;i<w-s;)b[~i++-~j*w]=a[i*w+j];wmemcpy(a,b,w*w);++s<w&&f(a,b,w,s);}

```

Try it online!
> 1 votes

# Answer
# Haskell, 144 bytes

```
import Data.List
k=transpose
v=init.tail
t[[o]]=[[o]]
t m=k.reverse.(head m:).(++[last m]).
 k.((v.head$k m):).(++[v.last$k m]).
 k.t.map(v).v$m

```

Try it online!

`v` cuts out center (rows). `map v` cuts out center columns. `t` recurses into the tornado. `k` exposes columns as rows. `(++[v.last$k m])` appends center of last column. `((v.head$k m):)` prepends center of first column. `k` flips rows out again. `(++[last m])` appends last row unprocessed. `(head m:)` prepends last row unprocessed. `k.reverse` rotates matrix.
> 1 votes

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

```
f=(a,k=0,L=a.length+~k)=>L?f(a.map((b,x)=>b.map((c,y)=>x<k|y<k|x>L|y>L?c:a[k+L-y][x])),k+1):a

```

Try it online!

```
f=(
  a,             // Input
  k=0,           // Range Left
  L=a.length+~k  // Range Right
)=>L?            // More than enough
  f(
    a.map((b,x)=>b.map((c,y)=>x<k|y<k|x>L|y>L?c:
      a[k+L-y][x]// k+L=a.length-1
  )),k+1)
:a

```
> 1 votes

# Answer
# Uiua SBCS, 25 bytes

```
∧(⍜(↘⊙↻|≡⇌⍉)×¯2.⊟.)⇡⌈÷2⧻.

```

Try it!

Fun problem.

```
∧(⍜(↘⊙↻|≡⇌⍉)×¯2.⊟.)⇡⌈÷2⧻.
                   ⇡⌈÷2⧻.  # create range for each ring
∧(                )        # fold over range and matrix, using matrix as accumulator
                ⊟.         # create pair indicating how much to rotate matrix on each axis
            ×¯2.           # and another pair indicating how much to drop from each axis
  ⍜(   |   )               # call the left part, then the right, then the inverse of left
        ≡⇌⍉                # rotate matrix clockwise
    ↘⊙↻                    # but only the interior

```
> 0 votes

---
Tags: code-golf, matrix
---


title: Alternating Sign Sequence

text:
# Question
Title: Alternating Sign Sequence
### Introduction

The sign of a number is either a `+`, or a `-` for every non-zero integer. Zero itself is signless (`+0` is the same as `-0`). In the following sequence, we are going to alternate between the **positive sign**, the **zero** and the **negative sign**. The sequence starts with `1`, so we write `1` with a positive sign, with zero (this one is weird, but we just multiply the number by 0) and the negative sign:

```
1, 0, -1

```

The next number is `2`, and we do the same thing again:

```
2, 0, -2

```

The sequence eventually is:

```
1, 0, -1, 2, 0, -2, 3, 0, -3, 4, 0, -4, 5, 0, -5, 6, 0, -6, 7, 0, -7, ...

```

Or a more readable form:

```
a(0) = 1
a(1) = 0
a(2) = -1
a(3) = 2
a(4) = 0
a(5) = -2
a(6) = 3
a(7) = 0
a(8) = -3
a(9) = 4
...

```

### The Task

Given a non-negative integer *n*, output the *n*th term of the above sequence. You can choose if you use the **zero-indexed** or **one-indexed** version.

### Test cases:

Zero-indexed:

```
a(0) = 1
a(11) = -4
a(76) = 0
a(134) = -45
a(296) = -99

```

Or if you prefer one-indexed:

```
a(1) = 1
a(12) = -4
a(77) = 0
a(135) = -45
a(297) = -99

```

This is , so the submission with the smallest number of bytes wins!

# Answer
> 6 votes
# Jelly, 7 bytes

```
+6d3’PN

```

Zero-indexed. Test cases here.

Explanation:

```
+6      Add 6:     x+6
d3      Divmod:    [(x+6)/3, (x+6)%3]
’       Decrement: [(x+6)/3-1, (x+6)%3-1]
P       Product    ((x+6)/3-1) * ((x+6)%3-1)

```

# Answer
> 6 votes
# JavaScript ES6, 18 bytes

```
n=>-~(n/3)*(1-n%3)

```

Turned out very similar to @LeakyNun's answer but I didn't see his until after I posted mine.

## Explanation and Ungolfed

`-~` is shorthand for `Math.ceil`, or rounding up:

```
n =>               // input in var `n`
    Math.ceil(n/3) // Get every 3rd number 1,1,1,2,2,2, etc.
    *
    (1-n%3)        // 1, 0, -1, 1, 0, -1, ...

```

```
function f(n){n=i.value;o.value=-~(n/3)*(1-n%3);}
```

```
Input: <input id=i oninput="f()"/><br /><br />
Output: <input id=o readable/>
```

# Answer
> 6 votes
# MarioLANG, ~~93~~ 81 bytes

*one-indexed*

**Try It Online**

```
;(-))+(-
"============<
>:(![<:![<:)![
 !=#="!#="!=#=
!  < !-< !- <
#==" #=" #=="

```

**Explanation :**

we begin by taking the imput

```
;

```

wich give us

```
          v
... 0 0 input 0 0 ...

```

we then decrement the left byte and increment the right byte with

```
;(-))+(
=======

```

we end up with

```
           v
... 0 -1 input +1 0 ...

```

we then set up the loop

```
;(-))+(-
"============<
>  ![< ![<  ![
   #=" #="  #=
!  < !-< !- <
#==" #=" #=="

```

the loop will go until the memory look like

```
         v
... 0 -X 0 +X 0 ...

```

we then only need to output the result

```
;(-))+(-
"============<
>:(![<:![<:)![
 !=#="!#="!=#=
!  < !-< !- <
#==" #=" #=="

```

# Answer
> 4 votes
# Python 2, 24 bytes

```
lambda n:(n/3+1)*(1-n%3)

```

## Full program:

```
a=lambda n:(n/3+1)*(1-n%3)

print(a(0))   #   1
print(a(11))  #  -4
print(a(76))  #   0
print(a(134)) # -45
print(a(296)) # -99

```

# Answer
> 4 votes
# MATL,  ~~15~~  12 bytes

```
3/XkG3X\2-*_

```

This uses one based indexing.

Try it online! or verify test cases

Explanation:

```
    G          #Input
     3X\       #Modulus, except multiples of 3 give 3 instead of 0
        2-     #Subtract 2, giving -1, 0 or 1
3/Xk           #Ceiling of input divided by 3.
          *    #Multiply
           _   #Negate

```

# Answer
> 4 votes
# Haskell, 27 bytes

```
f x=div(x+3)3*(1-mod(x+3)3)

```

Slightly more interesting 28 byte solution:

```
(((\i->[i,0,-i])=<<[1..])!!)

```

(Both are `0`-indexed)

# Answer
> 3 votes
# Bash, 28 25 Bytes

```
echo $[(1+$1/3)*(1-$1%3)]

```

# Answer
> 3 votes
# MATL, 8 bytes

```
:t~y_vG)

```

The result is 1-based.

**Try it online!**

### Explanation

This builds the 2D array

```
 1  2  3  4  5 ...
 0  0  0  0  0 ...
-1 -2 -3 -4 -5 ...

```

and then uses linear indexing to extract the desired term. Linear indexing means index down, then across (so in the above array the first entries in linear order are `1`, `0`, `-1`, `2`, `0`, ...)

```
:     % Vector [1 2 ... N], where N is implicit input
t~    % Duplicate and logical negate: vector of zeros
y_    % Duplicate array below the top and negate: vector [-1 -2 ... -N]
v     % Concatenate all stack contents vertically
G)    % Index with input. Implicit display

```

# Answer
> 3 votes
# Perl 5, 22 bytes

21 plus one for `-p`:

```
$_=(-$_,$_+2)[$_%3]/3

```

Uses 1-based indexing.

Explanation:

`-p` sets the variable `$_` equal to the input. The code then sets it equal to the `$_%3`th element, divided by 3, of the 0-based list `(-$_,$_+2)` (where `%` is modulo). Note that if `$_%3` is two, then there is no such element, and the subsequent division by 3 numifies the undefined to 0. `-p` then prints `$_`.

# Answer
> 3 votes
## 05AB1E, 7 bytes

**Code:**

```
(3‰`<*(

```

**Explained:**

```
(           # negate input: 12 -> -12
 3‰         # divmod by 3: [-4, 0]
   `        # flatten array: 0, -4
    <       # decrease the mod-result by 1: -1, -4
     *      # multiply: 4
      (     # negate -4

```

# Answer
> 2 votes
## Pyke, ~~8~~ 7 bytes (old version)

```
3.DeRt*

```

Try it here! \- Note that link probably won't last for long

```
3.D      - a,b = divmod(input, 3)
   e     - a = ~a -(a+1)
     t   - b -= 1
      *  - a = a*b
         - implicit output a

```

Newest version

```
3.DhRt*_

```

Try it here!

```
3.D      - a,b = divmod(input, 3)
   h     - a+=1
     t   - b-=1
      *  - a = a*b
       _ - a = -a
         - implicit output a

```

# Answer
> 2 votes
# Perl 6,  ~~26~~  23 bytes

```
~~{({|(++$,0,--$)}...*)[$_]}~~
{($_ div 3+1)*(1-$_%3)}
```

( The shorter one was translated from other answers )

## Explanation (of the first one):

```
{ # bare block with implicit parameter ｢$_｣
  (

    # start of sequence generator

    { # bare block
      |(  # slip ( so that it flattens into the outer sequence )
        ++$, # incrementing anon state var =>  1, 2, 3, 4, 5, 6
        0,   # 0                           =>  0, 0, 0, 0, 0, 0
        --$  # decrementing anon state var => -1,-2,-3,-4,-5,-6
      )
    }
    ...  # repeat
    *    # indefinitely

    # end of sequence generator

  )[ $_ ] # get the nth one (zero based)
}

```

### Test:

```
#! /usr/bin/env perl6
use v6.c;
use Test;

# store it lexically
my &alt-seq-sign = {({|(++$,0,--$)}...*)[$_]}
my &short-one = {($_ div 3+1)*(1-$_%3)}

my @tests = (
    0 =>   1,
   11 =>  -4,
   76 =>   0,
  134 => -45,
  296 => -99,
  15..^30  => (6,0,-6,7,0,-7,8,0,-8,9,0,-9,10,0,-10)
);

plan @tests * 2 - 1;

for @tests {
  is alt-seq-sign( .key ), .value, 'alt-seq-sign  ' ~ .gist;

  next if .key ~~ Range; # doesn't support Range as an input
  is short-one(    .key ), .value, 'short-one     ' ~ .gist;
}

```

```
1..11
ok 1 - alt-seq-sign  0 => 1
ok 2 - short-one     0 => 1
ok 3 - alt-seq-sign  11 => -4
ok 4 - short-one     11 => -4
ok 5 - alt-seq-sign  76 => 0
ok 6 - short-one     76 => 0
ok 7 - alt-seq-sign  134 => -45
ok 8 - short-one     134 => -45
ok 9 - alt-seq-sign  296 => -99
ok 10 - short-one     296 => -99
ok 11 - alt-seq-sign  15..^30 => (6 0 -6 7 0 -7 8 0 -8 9 0 -9 10 0 -10)

```

# Answer
> 2 votes
# J, ~~19~~ 15 bytes

```
>.@(%&3)*1-3|<:

```

Probably need to golf this further...

1-indexed.

### Ungolfed:

```
>> choose_sign      =: 1-3|<:      NB. 1-((n-1)%3)
>> choose_magnitude =: >.@(%&3)    NB. ceil(n/3)
>> f                =: choose_sign * choose_magnitude
>> f 1 12 77
<< 1 _4 0

```

Where `>>` means input (STDIN) and `<<` means output (STDOUT).

# Answer
> 2 votes
# J, 27 bytes

Whilst not the golfiest, I like it better, as it uses an agenda.

```
>.@(>:%3:)*1:`0:`_1:@.(3|])

```

Here is the tree decomposition of it:

```
         ┌─ >.
  ┌─ @ ──┤    ┌─ >:
  │      └────┼─ %
  │           └─ 3:
  ├─ *
──┤           ┌─ 1:
  │      ┌────┼─ 0:
  │      │    └─ _1:
  └─ @. ─┤
         │    ┌─ 3
         └────┼─ |
              └─ ]

```

This is very similar to Kenny's J answer, in that it chooses the magnitude and sign, but it's different in that I use an agenda to choose the sign.

# Answer
> 2 votes
# MATL, 8 bytes

```
_3&\wq*_

```

This solution uses 1-based indexing into the sequence.

**Try it Online**

Modified version showing all test cases

**Explanation**

```
        % Implicitly grab the input
_       % Negate the input
3&\     % Compute the modulus with 3. The second output is floor(N/3). Because we negated
        % the input, this is the equivalent of ceil(input/3)
w       % Flip the order of the outputs
q       % Subtract 1 from the result of mod to turn [0 1 2] into [-1 0 1]
*       % Take the product with ceil(input/3)
_       % Negate the result so that the sequence goes [N 0 -N] instead of [-N 0 N]
        % Implicitly display the result

```

# Answer
> 2 votes
# Pyth, 10 bytes

```
*h/Q3-1%Q3

```

Try it online!

Explanation:

```
*     : Multiply following two arguments
h/Q3  : 1 + Input/3
-1%Q3 : 1 - Input%3

```

Note: I've assumed the zero-indexed sequence.

# Answer
> 2 votes
## Actually, 10 bytes

```
3@│\u)%1-*

```

Try it online!

Explanation:

```
3@│\u)%1-*
3@│         push 3, swap, duplicate entire stack ([n 3 n 3])
   \u)      floor division, increment, move to bottom ([n 3 n//3+1])
      %1-   mod, subtract from 1 ([1-n%3 n//3+1])
         *  multiply ([(1-n%3)*(n//3+1)])

```

# Answer
> 2 votes
# Batch (Windows), 86 bytes

## Alternate.bat

```
SET /A r=%1%%3
SET /A d=(%1-r)/3+1
IF %r%==0 ECHO %d%
IF %r%==1 ECHO 0
IF %r%==2 ECHO -%d%

```

This program is run as `Alternate.bat n` where `n` is the number you wish to call the function on.

# Answer
> 2 votes
# GeoGebra, 44 bytes

```
Element[Flatten[Sequence[{t,0,-t},t,1,n]],n]

```

where `n` is one-indexed.

Explanation:

```
Element[                      , n] # Return the nth element of the list                  .
 Flatten[                    ]     # Strip all the unnecessary braces from the list     /|\
  Sequence[{t,0,-t}, t, 1, n]      # Generate a list of lists of the form {t, 0, -t}     |
                             # This list will start with {1,0,-1} and end with {n,0,-n}  |

```

It is not necessary to generate all triplets through `{n, 0, -n}`, but it's shorter than writing `ceil(n/3)` or something to that effect. Note that `n` must be defined to create this object (if it isn't defined at the time this is run, GeoGebra will prompt you to create a slider for `n`).

# Answer
> 2 votes
## Labyrinth, ~~17~~ ~~15~~ 14 bytes

*Saved 3 bytes using Sok's idea of using `1-(n%3)` instead of `~(n%3-2)`.*

```
1?:#/)}_3%-{*!

```

The program terminates with an error (division by zero), but the error message goes to STDERR.

Try it online!

### Explanation

The program is completely linear, although some code is executed in reverse at the end.

```
1     Turn top of stack into 1.
?:    Read input as integer and duplicate.
#     Push stack depth (3).
/)    Divide and increment.
}     Move over to auxiliary stack.
_3%   Take other copy modulo 3.
-     Subtract from 1. This turns 0, 1, 2 into 1, 0, -1, respectively.
{*    Move other value back onto main stack and multiply.
!     Output as integer.

```

The instruction pointer now hits a dead end and turns around, so it starts to execute the code from the end:

```
*     Multiply two (implicit) zeros.
{     Pull an (implicit) zero from the auxiliary to the main stack.
-     Subtract two (implicit) zeros from one another.
      Note that these were all effectively no-ops due to the stacks which are
      implicitly filled with zeros.
%     Attempt modulo, which terminates the program due to a division-by-zero error.

```

# Answer
> 2 votes
## Erlang, 40 bytes

```
F=fun(N)->trunc((N/3+1)*(1-N rem 3))end.

```

Sadly Erlang has no '%' modulo operator and 'rem' requires the spaces, even before the 3.

# Answer
> 2 votes
# Hexagony, 25 bytes

```
?'+}@/)${':/3$~{3'.%(/'*!

```

Or, in non-minified format:

```
    ? ' + }
   @ / ) $ {
  ' : / 3 $ ~
 { 3 ' . % ( /
  ' * ! . . .
   . . . . .
    . . . .

```

Try it online!

My first foray into Hexagony, so I'm certain I've not done this anywhere near as efficiently as it could be done...

Calculates `-(n%3 - 1)` on one memory edge, `n/3 + 1` on an adjacent one, then multiplies them together.

# Answer
> 2 votes
# R, 28 bytes

```
-((n=scan())%%3-1)*(n%/%3+1)

```

Looks like this is a variation of most of the answers here. Zero based.

```
   n=scan()                  # get input from STDIN
  (        )%%3-1            # mod by 3 and shift down (0,1,2) -> (-1,0,1)
-(               )           # negate result (1,0,-1), this handles the alternating signs
                  *(n%/%3+1) # integer division of n by 3, add 1, multiply by previous

```

The nice thing about it is that it handles multiple inputs

```
> -((n=scan())%%3-1)*(n%/%3+1)
1: 0 3 6 9 1 4 7 10 2 5 8 11
13:
Read 12 items
 [1]  1  2  3  4  0  0  0  0 -1 -2 -3 -4
>

```

Originally I wanted to do the following, but couldn't trim off the extra bytes.

```
rbind(I<-1:(n=scan()),0,-I)[n]

```

Uses `rbind` to add 0's and negatives to a range of 1 to `n` then return the `n`'th term (one based).

```
# for n = 5
rbind(                    )    # bind rows
            n=scan()           # get input from STDIN and assign to n
      I<-1:(        )          # build range 1 to n and assign to I
                     ,0        # add a row of zeros (expanded automatically)
                       ,-I     # add a row of negatives
                           [n] # return the n'th term

```

# Answer
> 2 votes
## APL, 12 chars

```
-×/1-0 3⊤6+⎕

```

`0 3⊤` is APL's `divmod 3`.

# Answer
> 2 votes
# Java 7, 38 37 36 bytes

My first golf, be gentle

```
int a(int i){return(1+i/3)*(1-i%3);}

```

Try it here! (test cases included)

Edit: I miscounted, and also golfed off one more character by replacing `(-i%3+1)` with `(1-i%3)`.

# Answer
> 1 votes
# Retina, 45 bytes

```
.+
11$&$*
(111)+(1)*
$#2$#1
T`d`+0-`^.
^0.+
0

```

Try it online!

Test suite.

Takes input/output in base-ten. 1-indexed.

### Unary input, base-ten output, 1-indexed: 40 bytes

```
$
11
(111)+(1)*
$#2$#1
T`d`+0-`^.
^0.+
0

```

Try it online!

Test suite.

# Answer
> 1 votes
## Batch, ~~30~~ 29 bytes

```
@cmd/cset/a(1+%1/3)*(1-%1%%3)

```

The `cmd/c` makes `set/a` echo the result of the calculation. Edit: Saved 1 byte by removing the unnecessary space.

# Answer
> 1 votes
# GNU Coreutils, 27 Bytes

```
echo "(1+$1/3)*(1-$1%3)"|bc

```

# Answer
> 1 votes
# MATLAB / Octave, 27 bytes

```
@(n)ceil(n/3)*(mod(-n,3)-1)

```

This creates an anonymous function that can be called using `ans(n)`. This solution uses 1-based indexing.

All test cases

# Answer
> 1 votes
# Mathematica 26 bytes

With 4 bytes saved thanks to Martin Ender.

```
⎡#/3⎤(-#~Mod~3-1)&

```

Uses the same approach as Suever.

# Answer
> 1 votes
# Octave, 23 bytes

With no mod cons...

```
@(n)(-[-1:1]'*[1:n])(n)

```

Uses 1-based indexing magic.

---

**Explanation**

Creates an anonymous function that will:

```
(-[-1:1]'*[1:n])(n)
  [-1:1]              % make a row vector [-1 0 1]
 -      '             % negate and take its transpose making a column vector
          [1:n]       % make a row vector [1..n], where n is the input
         *            % multiply with singleton expansion
               (n)    % use linear indexing to get the nth value

```

After the multiplication step we'll have a 3xn matrix like so (for n=12):

```
 1    2    3    4    5    6    7    8    9   10   11   12
 0    0    0    0    0    0    0    0    0    0    0    0
-1   -2   -3   -4   -5   -6   -7   -8   -9  -10  -11  -12

```

Making `n` columns is overkill, but it's a convenient number that is guaranteed to be large enough. Linear indexing counts down each column from left to right, so the element at linear index `4` would be `2`.

All test cases on ideone.

# Answer
> 1 votes
# JavaScript, 22 bytes

```
r=n%3
o=(1-r)/3*(n-r+3)

```

`n` is the number you wish to call the function on. `o` is the output number.

# Answer
> 1 votes
# dc, 10

```
?2+3~1r-*p

```

Uses 1-based indexing.

```
?              # Push input to stack
 2+            # Add 2
   3~          # divmod by 3
     1r-       # subtract remainder from 1
        *      # multiply by quotient
         p     # print

```

# Answer
> 1 votes
# APL, 14 bytes

```
{⍵⌷∊{⍵0,-⍵}¨⍳⍵}

```

This is 1-indexed, i.e.:

```
     {⍵⌷∊{⍵0,-⍵}¨⍳⍵}¨1 2 3 4 5 6 7 8
1 0 ¯1 2 0 ¯2 3 0

```

Explanation:

```
{⍵⌷                   select the ⍵th element
   ∊                  from all elements in
    {⍵0,-⍵}           the values ⍵, 0, and -⍵
           ¨⍳⍵}       for each number in 1..⍵

```

# Answer
> 1 votes
## CJam, 11 bytes

```
ri3+3md(W**

```

0-based input.

Test it here.

### Explanation

```
ri   e# Read input and convert to integer N.
3+   e# Add 3.
3md  e# Divmod 3, putting N/3+1 and N%3 on the stack.
(W*  e# Decrement, multiply by -1, turning 0, 1, 2 into 1, 0, -1, respectively.
*    e# Multiply.

```

# Answer
> 1 votes
# \>\<\>, 16+3 = 19 bytes

```
:3%:1$-}-3,1+*n;

```

Needs the input to be present on the stack, so +3 bytes for the `-v` flag. Try it online!

The program outputs the **zero-indexed** sequence, using the formula:

`f(n) = ((n-(n%3))/3) * (1-(n%3))`

# Answer
> 1 votes
# Java 7, 36 bytes

```
int c(int n){return(n/3+1)*(1-n%3);}

```

**Ungolfed & test code:**

Try it here.

```
class Main{

    static int c(int n){
        return (n / 3 + 1) * (1 - n % 3);
    }

    public static void main(String[] a){
        System.out.println(c(0));
        System.out.println(c(11));
        System.out.println(c(76));
        System.out.println(c(134));
        System.out.println(c(296));
    }
}

```

**Zero-indexed output:**

```
1
-4
0
-45
-99

```

# Answer
> 1 votes
# Desmos, ~~125~~ 86 bytes

```
b=\operatorname{ceil}\left(\frac{a}{3}\right)
b\operatorname{mod}\left(-a,3\right)-b
a=1

```

Simple fix for `\operatorname{ceil}\left(\frac{a}{3}\right)`

125 bytes:

```
\operatorname{ceil}\left(\frac{a}{3}\right)\operatorname{mod}\left(-a,3\right)-\operatorname{ceil}\left(\frac{a}{3}\right)
a=1

```

This is as close as I could get to divmod. Might be able to get rid of subtracting `-\operatorname{ceil}\left(\frac{a}{3}\right)` to shave some bytes off.

# Answer
> 1 votes
# Cubix, 30 bytes

```
1..-.w>?^I3%?;,)O@...o-'.<u;;;

```

Try it here. You will need to replace the current code with the above and enter an input number.
This wraps onto a cube with an edge length of 3. I'm hoping to reduce this a bit more, but at the moment it's not to bad. It would be nice to have some of the planned features for the stack, but oh well.

```
      1 . .
      - . w
      > ? ^
I 3 % ? ; , ) O @ . . .
o - ' . < u ; ; ; . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

```

Explanation:

* `I 3 % ?` Take a number from input, push a literal 3, mod on TOS and do a check. The `?` redirects right for negative and left for positive. Pass through for zero
* For zero value `; , ) O @` Pop, integer divide TOS, increment TOS, output number and terminate
* For positive value `1 - > ?` Push literal 1, subtract TOS, change direction and check
+ For zero value `^ w O @` Redirect up, sidestep left (ends up on another face), output number (zero in this case) and terminate
    + For positive value `; < ' - o ; ; ; u , ) O @` pop, redirect, push character -, output character, pop, pop, pop, u-turn to left, integer divide TOS, increment TOS, output number and terminate

# Answer
> 1 votes
# C#, 34 bytes

```
n=>n%3==1?0:(n/3+1)*(n%3==0?1:-1);

```

To assign the lambda to a variable, write:

```
Func<int,int>f=n=>n%3==1?0:(n/3+1)*(n%3==0?1:-1);

```

With C# 6, you can also assign the lambda to a method:

```
int F(int n)=>n%3==1?0:(n/3+1)*(n%3==0?1:-1);

```

# Answer
> 1 votes
# Python 3, ~~30~~ 25 bytes

I tried to replicate the results of Leaky Nun's Python post for 10 minutes before realising it was for Python 2, not 3.

Zero-indexed:

```
lambda n:(n//3+1)*(1-n%3)

```

## Full program:

```
a = lambda n:(n//3+1)*(1-n%3)
print(a(0))   #   1
print(a(11))  #  -4
print(a(76))  #   0
print(a(134)) # -45
print(a(296)) # -99

```

# Answer
> 1 votes
# Java, 19 bytes

Using lambda expressions.

```
i->(1+i/3)*(1-i%3);

```

Try it here!

# Answer
> 1 votes
# Oasis, 12 bytes (non-competing)

```
n3÷>n3÷y>n-*

```

Try it online!

Oasis is a language designed by Adnan which is specialized in sequences.

Currently, this language can do recursion and closed form.

This answer can only demonstrate closed form. For recursion, see for example this answer.

We use this formula: `a(n) = (n/3+1)*((n/3*3)+1-n)` which is modified from the formula used in my Python answer, since there is no modulo at the moment.

```
n3÷>n3÷y>n-*

n             push n (input)
 3÷           integer-division by 3
   >          +1
    n         push n (input)
     3÷       integer-division by 3
       y      *3
        >     +1
         n    push n (input)
          -   subtract the top of stack from the second top of stack
           *  multiply the top of stack to the second top of stack

```

# Answer
> 1 votes
# Python 2, 64 bytes

Although Leaky Nun has already posted a much shorter, brilliant Python answer, I decided to see whether this could be done recursively, calculating each new term from the last two. The result was interesting:

```
f=lambda n,a=1,b=0:(n<1)*`a`or f(n-1,b,[[0,-a][b==0],1-b][a==0])

```

**Try it online!**

# Answer
> 1 votes
# Lua, 50 bytes

```
function a(n)print((math.floor(n/3)+1)*(1-n%3))end

```

Try it online!

# Answer
> 0 votes
**VBA Excel , 46 bytes**

using immediate window and `Range A1` as input

```
a=[A1]:b=a Mod 3:?IIf(b=0,-a/3,IIf(b=1,a/3,0))

```

# Answer
> 0 votes
# Common Lisp, ~~73~~ 43 bytes

```
(lambda(n)(*(1+(floor n 3))(- 1(mod n 3))))

```

Try it online!

# Answer
> 0 votes
# Vyxal, 52 bitsv2, 6.5 bytes

```
Þn2ẇ0Zfi

```

Try it Online!

Bitstring:

```
0010101100100111101111111101010011100010011001000000

```

Silly vyxal (1 indexed)

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


title: Yarr! A map to the hidden treasure!

text:
# Question
Title: Yarr! A map to the hidden treasure!
### Introduction

"Yarr!! We had a laddie who called himself a "programmer" make a map t' our hidden treasure! But 'tis written wit' weird numbers 'n letters! "E5, N2, E3"... what does it even mean? Madness! Can't even scribe a proper treasure map, t' useless cretin. Fix it fer us! We'll gift ye a share o' t' treasure!"

### Challenge Description

A group of pirates are having trouble reading a treasure map. Can you write a program to convert it into a more... piratey form?

As input, you'll receive the original treasure map. It's a list of comma separated strings, each string which consists of a *letter portion* (which tells the pirates which direction they need to walk in), and a *number portion* (which tells the pirates how many steps to take in that direction). For instance, the following treasure map:

```
E2,N4,E5,S2,W1,S3

```

would mean, "walk two steps to the east, walk four steps to the north, walk five steps to the east, walk two steps to the south, walk one step to the west, then walk three steps to the south."

As output, you'll output the map in a graphical form, using the characters `>`, `^`, `v`, and `<` as pointers. Here's the output for the above input:

```
  >>>>>v
  ^    v
  ^   v<
  ^   v
>>^   X

```

Notice that we've replaced the last step to the south with an `X` instead. This is because the last step is where the treasure is, and as we all know, pirates must have an X on their treasure maps, otherwise they won't know how to read it.

By the way, the map won't ever cross itself, so you don't need to worry about dealing with overlaps. Also, you are allowed to have a trailing new line at the end of the output.

### Sample Inputs and Outputs

```
S5,W2

```

```
 v
 v
 v
 v
 v
X<

```

```
N1,E1,S1,E1,N1,E1,S2

```

```
>v>v
^>^X

```

```
N1

```

```
X

```

```
N6,E6,S6,W5,N5,E4,S4,W3,N3,E2,S2,W1,N2

```

```
>>>>>>v
^>>>>vv
^^>>vvv
^^^Xvvv
^^^^<vv
^^^<<<v
^^<<<<<

```

```
E21,S2

```

```
>>>>>>>>>>>>>>>>>>>>>v
                     X

```

```
N12,E11,S12,W2,N4

```

```
>>>>>>>>>>>v
^          v
^          v
^          v
^          v
^          v
^          v
^          v
^          v
^        X v
^        ^ v
^        ^ v
^        ^<<

```

# Answer
> 8 votes
# Ruby, ~~213 209 198 186~~ 178

```
M={};x=0,m=q=0
gets.scan(/.(\d+)/){?1.upto($1){m,y=x
x[d=$&.ord%10%7-2]+=1|($u=M[y]||={})[m]=d
m<q&&q=m}}
$u[m]=2
puts M.sort.map{|_,b|(q..b.max[0]).map{|k|">vX <^"[b[k]||3]}*""}

```

Pass input via stdin.

This uses a `y -> x -> char` dictionary to construct the map, where both `x` and `y` can be negative. Once the input has been parsed, the global minimum of the x coordinate is extracted. For each row, it then iterates over a range going from the global minimum to the maximum index for the current line, and prints the correct character for that index.

To stay with the theme, the expressions to turn `NESW` into the proper indices were shamelessly pirated from Sp3000's answer.

Original version that used a `[x,y] -> char` dictionary:

```
M={};x=0,0
gets.scan(/.(\d+)/){(?1..$1).map{x[d=$&.ord%10%7-2]+=1|M[$y=x+[]]=d}}
M[$y]=2
a,*q=M.minmax.flatten
M.map{|(x,y),v|($*[y-M.map{|a,|a[1]}.min]||=?\s.*q[2]-a)[x-a]=">vX<^"[v]}
puts$*.map &:rstrip

```

# Answer
> 20 votes
# Python 2, ~~249~~ ~~248~~ ~~244~~ ~~239~~ 237 bytes

```
D={}
m=X=Y=0
for s in input().split(","):d=ord(s[0])%10%7;exec"a,b=X,Y;E=D[Y]=D.get(Y,{});E[X]='<^>v'[d];m=min(m,X);%c+=d-2|1;"%(88+d%2)*int(s[1:])
D[b][a]="X"
for Y in sorted(D):print"".join(D[Y].get(n," ")for n in range(m,max(D[Y])+1))

```

Input like `"E2,N4,E5,S2,W1,S3"`.

`NSEW` is mapped to `[1, 3, 2, 0]` by `d=ord(c)%10%7`. Whether to change `y` or `x` is then decided by `d%2`, and whether to increment or decrement is decided by `d-2|1`. The first and third expressions were found by brute force.

Other than that, it's a simple usage of a nested dictionary of the form `{y: {x: char}}`.

*(Thanks to @joriki for help with mapping)*

# Answer
> 14 votes
# Javascript (ES6), 260

This was an interesting one...

Thanks @ETHproductions, @edc65, and @vihan for the help!

```
s=>{z=o=""
m=[]
q=x=y=2e3
s.split`,`.map(v=>z+=v[0].repeat(+v.slice(1)))
for(i=0;d=z[i];q=x<q?x:q)(m[y]=m[y]||[])[x]=z[++i]?d=="N"&&--y?"^":d=="S"&&++y?"v":d=="W"&&--x?"<":++x?">":o:"X"
m.map(a=>a.map((b,j)=>o+=" ".repeat(-p-1+(p=j))+b,p=q-1,o+=`
`))
return o}

```

This defines an anonymous function, so to call it add `f=` to the beginning to give it a name.

To test: `console.log(f("E2,N4,E5,S2,W1,S3"))`

### Explanation:

```
s=>{ //define function w/ parameter s
z=o=""      //z=modified input, o=final output
m=[]        //map of characters
q=x=y=2e3   //q=minimum value of x; x+y=coordinates. These start high to leave room to go backwards
s.split`,`.map(v=>z+=v[0].repeat(+v.slice(1)))    //change "N3,E4" -> "NNNEEEE", and put in z
for(i=0;d=z[i];q=x<q?x:q)   //for each direction d in z, while updating q:
    (m[y]=m[y]||[])[x]=     //in the right place on the map, put:
        z[++i]?                 //if last character of z, "X"
            d=="N"&&--y?"^":
            d=="S"&&++y?"v":    //otherwise get the right character and change x+y accordingly
            d=="W"&&--x?"<":
            ++x?">":o
        :"X"
m.map(a=>a.map((b,j)=>o+=" ".repeat(-p-1+(p=j))+b,p=q-1,o+=`
`)) //dump map to o, with correct padding
return o}   //return

```

# Answer
> 7 votes
# PHP, ~~431~~ 417 bytes

```
$g=explode(',',$argv[1]);$x=$y=$a=$b=$c=$d=$e=$f=0;
foreach($g as$i=>$h){list($k,$l,$m)=
    ['N'=>[-1,0,'^'],'E'=>[0,1,'>'],'S'=>[1,0,'v'],'W'=>[0,-1,'<']][$h[0]];
    for($s=substr($h,1);$s--;){$z[$f=$y][$e=$x]=$m;$y+=$k;$x+=$l;}
    if($i==count($g)-1){$x=$e;$y=$f;}
    $a=min($a,$x);$b=max($b,$x);$c=min($c,$y);$d=max($d,$y);
}$z[$y][$x]='X';for($y=$c;$y<=$d;$y++)
{$o='';for($x=$a;$x<=$b;$x++)$o.=$z[$y][$x]?:' ';echo rtrim($o)."\n";}

```

Put it into a file (`treasure.php`), remove the indentation, join the lines (it is wrapped here for readability), put the `<?php` marker at the beginning of the file (not displayed here as it is technically not a part of the program).

Example of execution:

```
$ php -d error_reporting=0 treasure.php E2,N4,E5,S2,W1,S3
  >>>>>v
  ^    v
  ^   v<
  ^   v
>>^   X
$

```

The option `-d error_reporting=0` is needed to suppress notices about values not found at specified indices in `$z`.

**Update:**

While I was preparing the ungolfed version of the code for posting I discovered it contained two unneeded assignments (12 bytes) and a whitespace that can be removed(`as$i`); also, by replacing a `while` with a `for` loop and squeezing an assignment into it (not possible using the `while` loop) I saved another byte.

# Answer
> 7 votes
# Perl, 702 613 546 474 439 338 260 bytes

Thanks to Dom Hastings for his help and his supergolfed version.
The code uses a 2D array.

Version by Dom Hastings:

```
$x=$y=$a=$b=99;map{/^./;$a=($c=$x)<$a?$x:$a,$A=$x>$A?$x:$A,$b=($C=$y)<$b?$y:$b,$B=$y>$B?$y:$B,$q[$c][$C]={split'','W<E>N^Sv'}->{$&},$x+={W,-1,E,1}->{$&},$y+={N,-1,S,1}->{$&}for 1..$'}split',',pop;$q[$c][$C]=X;for$y($b..$B){print$q[$_][$y]||$"for$a..$A;print$/}

```

My lesser golfed version of 338 bytes (for reference):

```
@m=split(',',pop);$x=$y=$a=$b=99;map{($d,$s)=/^(.)(.+)$/;for(1..$s){$c=$x;$C=$y;if($x<$a){$a=$x}if($x>$A){$A=$x}if($y<$b){$b=$y}if($y>$B){$B=$y}if($d eq"W"){$r="<";$x--}if($d eq"E"){$r=">";$x++}if($d eq"N"){$r="^";$y--}if($d eq"S"){$r=v;$y++}$q[$c][$C]=$r}}@m;$q[$c][$C]=X;for$y($b..$B){for$x($a..$A){$t=$q[$x][$y];print$t?$t:$"}print$/}

```

Test

```
$ perl piratemap_golf.pl E4,N3,W6,S10,W1,S1,E5,N1,W2,N6,E6,N5,W10,S1,E2
v<<<<<<<<<<
>Xv<<<<<< ^
  v     ^ ^
  v     ^ ^
  v >>>>^ ^
  v >>>>>>^
  v ^
  v ^
  v ^
  v ^
  v ^
 v< ^<<
 >>>>>^

```

# Answer
> 5 votes
## Python 2, 394 bytes

Run the program then paste into standard input as e.g. `"E2,N4,E5,S2,W1,S3"`

```
m=input().split(',')
def f(x,y,h,o,s=[]):
 for c in m:
  for _ in range(int(c[1:])):
   a,b,l={'E':(1,0,'>'),'W':(-1,0,'<'),'N':(0,1,'^'),'S':(0,-1,'v')}[c[0]]
   if o:o[h-y][x]=l
   s+=[(x,y)];x+=a;y+=b
 if o:o[h-y+b][x-a]='X'
 return s
p,q=zip(*f(*[0]*4))
w,h=max(p)-min(p),max(q)-min(q)
o=[[' ']*-~w for _ in range(h+1)]
f(-min(p),-min(q),h,o)
print'\n'.join(["".join(l).rstrip()for l in o])

```

This is not very optimized. First it runs through the input to record the path. Then it does some math to determine the right starting position and size of `o`. Then it runs through again and sets the appropriate entries of `o` as one of `>v<^X`. The main cleverness is in reusing the same function for both these traversals.

# Answer
> 4 votes
# PHP, 496 ~~514~~ ~~528~~

I tried my luck in PHP, the result is rather long, I still want to post it, just for fun.

```
function a($c){global$a,$b;$a[$b[1]][$b[0]]=$c;}$c=explode(',',$argv[1]);$a=[];$b=[0,0];foreach($c as$d=>$e){$f=substr($e,1);if($d==count($c)-1)$f--;for($i=0;$i++<$f;){if($e[0]==N){a('^');$b[1]--;}elseif($e[0]==E){a('>');$b[0]++;}elseif($e[0]==S){a(v);$b[1]++;}else{a('<');$b[0]--;}}}a(X);$d=$e=$f=$g=0;foreach($a as$y=>$h){$f=min($f,$y);$g=max($g,$y);foreach($h as$x=>$i){$d=min($d,$x);$e=max($e,$x);}}for($y=$f;$y<=$g;$y++){for($x=$d;$x<=$e;$x++)echo isset($a[$y][$x])?$a[$y][$x]:' ';echo "
";}

```

## Ungolfed

```
<?php

    function setInMap($char) {
        global $map, $position;
        $map[$position[1]][$position[0]] = $char;
    }

    $instructions = explode(',', $argv[1]);

    $map = [];

    $position = [0, 0];

    foreach($instructions as $index => $instruction) {
        $count = substr($instruction, 1);
        if($index === count($instructions) - 1) {
            $count--;
        }
        for($i = 0; $i < $count; $i++) {
            if($instruction[0] === 'N') {
                setInMap('^');
                $position[1]--;
            } elseif($instruction[0] === 'E') {
                setInMap('>');
                $position[0]++;
            } elseif($instruction[0] === 'S') {
                setInMap('v');
                $position[1]++;
            } else($instruction[0] === 'W') {
                setInMap('<');
                $position[0]--;
            }
        }
    }
    setInMap('X');

    $minX = $maxX = $minY = $maxY = 0;
    foreach($map as $y => $row) {
        $minY = min($minY, $y);
        $maxY = max($maxY, $y);
        foreach($row as $x => $cell) {
            $minX = min($minX, $x);
            $maxX = max($maxX, $x);
        }
    }
    for($y = $minY; $y <= $maxY; $y++) {
        for($x = $minX; $x <= $maxX; $x++) {
            if(isset($map[$y][$x])) {
                echo $map[$y][$x];
            } else {
                echo ' ';
            }
        }
        echo "\n";
    }

?>

```

# Answer
> 4 votes
# XQuery 3.0, 498

```
declare variable $v external;let $m:=<v>{tokenize($v,',')!(for $j in(1 to xs:int(substring(.,2)))return<c>{translate(substring(.,1,1),'NESW','^>v<')}</c>)}</v>/c!(let $p:=./preceding-sibling::c return<p x="{count($p[.='>'])-count($p[.='<'])}" y="{count($p[.='v'])-count($p[.='^'])}">{if(./following::*)then .else'X'}</p>)for $y in(min(xs:int($m/@y))to max(xs:int($m/@y)))return string-join(for $x in(min(xs:int($m/@x))to max(xs:int($m/@x)))let $d:=$m[@x=$x and @y=$y]return if($d)then$d else' ','')

```

XQuery isn't often even slightly competitive, so this was fun.

## Ungolfed

```
declare variable $v external;
let $map := <vector>{ tokenize($v,',') !
        (for $j in (1 to xs:int(substring(.,2)))
            return <step>{ translate(substring(.,1,1),'NESW','^>v<') }</step> )
         }</vector>/step !
            (let $path_so_far := ./preceding-sibling::step
            return <point
                x="{ count($path_so_far[.='>']) - count($path_so_far[.='<']) }"
                y="{ count($path_so_far[.='v']) - count($path_so_far[.='^']) }">
                {if(./following::*) then string(.) else 'X'}
            </point>)
for $y in (min(xs:int($map/@y)) to max(xs:int($map/@y)))
return string-join(
    for $x in (min(xs:int($map/@x)) to max(xs:int($map/@x)))
    let $d := $map[@x=$x and @y=$y]
    return if($d) then string($d) else ' '
    ,'')

```

# Answer
> 3 votes
# JavaScript (ES6), 244 ~~249 274~~

Leading spaces and newlines added for clarity and not counted, **except** the newline near the end in the join call, that is significant and counted.

Test running the snippet (being ECMAScript 6, Firefox and Safari 9 only)

```
F=m=>(
  x=y=0,p=[],
  m.replace(/\w(\d+)/g,(d,z)=>{
    for(d='NWSE'.search(d[0]);
        z--&&(p=~x?~y?p:[y=0,...p]:p.map(r=>' '+r,x=0));
        p[u=y]=(w=r.slice(0,x))+'^<v>'[d]+(v=r.slice(x+1)),
        d&1?x+=d-2:y+=d-1)
      for(r=p[y]||'';!r[x];)r+=' ';
  }),
  p[u]=w+'X'+v,
  p.join`
`
)

// TEST

out=x=>O.innerHTML+=x.replace(/</g,'<')+'\n'

;['S5,W2','N1,E1,S1,E1,N1,E1,S2','N1','N6,E6,S6,W5,N5,E4,S4,W3,N3,E2,S2,W1,N2','E21,S2','N12,E11,S12,W2,N4']
.forEach(a=>out(a+'\n'+F(a)+'\n'))
```

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

# Answer
> 2 votes
# C, 557

```
main(_,a,minX,maxX,minY,maxY,x,y,v,dir,dist)char**a;char*v;{char o[998][999];for(y=0;y-998;++y){for(x=0;x-998;++x)o[y][x]=32;o[y][998]=0;}y=x=minY=minX=maxY=maxX=499;v=a[1];while(*v){dir=*v++;dist=atoi(v);while(*v&&*v!=44)v++;v+=!!*v;if(dir==78){while(dist--)o[y--][x]=94;if(y<minY)minY=y;y+=!*v;}if(dir==69){while(dist--)o[y][x++]=62;if(x>maxX)maxX=x;x-=!*v;}if(dir==83){while(dist--)o[y++][x]=86;if(y>maxY)maxY=y;y-=!*v;}if(dir==87){while(dist--)o[y][x--]=60;if(x<minX)minX=x;x+=!*v;}}o[y][x]=88;for(y=minY;y<=maxY;++y){o[y][maxX+1]=0;puts(o[y]+minX);}}

```

Ungolfed version:

```
#include <stdio.h>

#define MAX_WIDTH 998
#define MAX_HEIGHT 998

int main(int argc, char *argv[]) {
    int minX,maxX,minY,maxY;
    int x,y;
    char output[MAX_HEIGHT][MAX_WIDTH+1];
    char *v;

    for (y=0; y<MAX_HEIGHT; ++y) {
        for (x=0; x<MAX_WIDTH; ++x)
            output[y][x] = ' ';
        output[y][MAX_WIDTH] = 0;
    }

    x = minX = maxX = MAX_WIDTH/2;
    y = minY = maxY = MAX_HEIGHT/2;

    v = argv[1];
    while (*v) {
        char dir; int dist;
        dir = *(v++);
        dist = atoi(v);
        while (*v && *v != ',') v++;
        if (*v) v++;

        switch (dir) {
            case 'N':case 'n':
                while (dist--) output[y--][x] = '^';
                if (y < minY) minY = y;
                if (!*v) y++;
                break;
            case 'E':case 'e':
                while (dist--) output[y][x++] = '>';
                if (x > maxX) maxX = x;
                if (!*v) x--;
                break;
            case 'S':case 's':
                while (dist--) output[y++][x] = 'v';
                if (y > maxY) maxY = y;
                if (!*v) y--;
                break;
            case 'W':case 'w':
                while (dist--) output[y][x--] = '<';
                if (x < minX) minX = x;
                if (!*v) x++;
                break;
        }
    }

    output[y][x] = 'x';
    for (y = minY; y <= maxY; ++y) {
        output[y][maxX+1] = 0;
        puts(output[y]+minX);
    }

    return 0;
}

```

Dynamic memory allocation isn't much harder, but malloc is far too long an identifier to be used in code golf. I feel like there should be some kind of PCG.h header legally auto-included for golfing in c, just to shorted some identifiers.

# Answer
> 2 votes
# Jelly, ~~61~~ 60 bytes

```
“ESWN”iⱮo)µịØ.,U;N$¤Wẋɗ/€Ẏḣ1;Ɗ+\ṖZṂ€ạƊ‘ŒṬ€a"Œṙ-0¦$Sị“>v<^X ”

```

Try it online!

A monadic link taking as its argument the directions as a list of lists, each of which has the compass direction character as its first member and the number of moves as an integer as its second. Returns a list of Jelly strings representing the map.

# Answer
> 1 votes
# Groovy, 359

```
c=args[0].split(',').collect{[it[0],it[1..-1]as int]}
m=[[]]
x=y=0
d=["N":["^",0,1],"S":["v",0,-1],"E":[">",1,0],"W":["<",-1,0]]
c.each{z->(1..z[1]).each{if(x<0){m*.add(0," ");x=0};if(y<0){m.add(0,[]);y=0};m[y]=m[y]?:[];m[y][x]=d[z[0]][0];if(c.last()==z&&it==z[1])m[y][x]='X';y+=d[z[0]][2];x+=d[z[0]][1]}}
m.reverse().each{println it.collect{it?:" "}.join()}

```

# Answer
> 1 votes
# Common Lisp - 603

```
(lambda(s)(do((x 0)i(y 0)j(p 0)r(q 0)(g(mapcar(lambda(x)`(,(aref x 0),(parse-integer x :start 1)))(split-sequence:split-sequence #\, s))(cdr g))c)((not g)(setf x 0 y 0)(dolist(e(stable-sort(sort r #'<= :key #'car)#'< :key #'cadr))(dotimes(_(-(cadr e)p y))(terpri)(incf y)(setf x 0))(dotimes(_(-(car e)q x))(princ" ")(incf x))(princ(caddr e))(incf x)))(case(caar g)(#\N(setf i 0 j -1 c #\^))(#\E(setf i 1 j 0 c #\>))(#\W(setf i -1 j 0 c #\<))(#\S(setf i 0 j 1 c #\v)))(dotimes(_(-(cadar g)(if(cdr g)0 1)))(push`(,x,y,c)r)(incf x i)(incf y j))(setf q(min q x)p(min p y))(unless(cdr g)(push`(,x,y #\X)r))))

```

Array-free implementation: prints from top to bottom, from left to right.

* Parse and expands directions into a trace of `(x y char)` elements:

The simple "N3" input produces `((0 0 #\^) (0 -1 #\^) (0 -2 #\X))`
* Also, compute the minimal `x` and `y`
* Sort the resulting trace by `y` first and then by `x`
* Iterate over the sorted list while moving cursor

1. Add newlines and spaces to move current cursor at right position
    2. When at position `x - minx`, `y - miny`, print the desired character

### Examples

```
(loop for input in  '("N6,E6,S6,W5,N5,E4,S4,W3,N3,E2,S2,W1,N2"
                      "N1,E1,S1,E1,N1,E1,S2"
                      "N12,E11,S12,W2,N4")
      do (fresh-line)
         (terpri)
      (funcall *fun* input))

```

Result:

```
>>>>>>v
^>>>>vv
^^>>vvv
^^^Xvvv
^^^^<vv
^^^<<<v
^^<<<<<

>v>v
^>^X

>>>>>>>>>>>v
^          v
^          v
^          v
^          v
^          v
^          v
^          v
^          v
^        X v
^        ^ v
^        ^ v
^        ^<<

```

# Answer
> 1 votes
# CoffeeScript, ~~303~~ 285 bytes

```
Y=(s)->o=[];t=l=x=y=0;q='';q+=s[0]for[1..s[1..]]for s in s.split ',';q=q[..-2];(i='NWSE'.search c;(o[y]?=[])[x]='^<v>'[i];j=(i&2)-1;x+=j*(i&1);y+=j*(!(i&1));y<t&&t=y;x<l&&l=x)for c in q;(o[y]?=[])[x]='X';((o[y][x]||' 'for x in[l...o[y].length]).join ''for y in[t...o.length]).join '\n'

```

```
<script src="http://coffeescript.org/extras/coffee-script.js"></script>
<script type="text/coffeescript">
Y=(s)->o=[];t=l=x=y=0;q='';q+=s[0]for[1..s[1..]]for s in s.split ',';q=q[..-2];(i='NWSE'.search c;(o[y]?=[])[x]='^<v>'[i];j=(i&2)-1;x+=j*(i&1);y+=j*(!(i&1));y<t&&t=y;x<l&&l=x)for c in q;(o[y]?=[])[x]='X';((o[y][x]||' 'for x in[l...o[y].length]).join ''for y in[t...o.length]).join '\n'

#------------------
document.write '<pre>'
z=[
  'E2,N4,E5,S2,W1,S3'
  'S5,W2'
  'N1,E1,S1,E1,N1,E1,S2'
  'N1'
  'N6,E6,S6,W5,N5,E4,S4,W3,N3,E2,S2,W1,N2'
  'E21,S2'
  'N12,E11,S12,W2,N4'
]
for w in z
  document.write "\n\n#{w}\n"
  document.write Y(w).replace /</g,'<'

</script>
```

# Answer
> 1 votes
# Charcoal, 32 bytes

```
ＷＳ«≔⌕ENW§ι⁰θ✳⊗θ×§>^<vθΣι»Ｍ✳⁺⊗θ⁴X

```

Try it online!

Input taken as a multiline string.

Link is to verbose version of code.

Golfed from 43 bytes with Neil's help.

# Answer
> 1 votes
# Vyxal, 390 bitsv2, 48.75 bytes

```
⌐⌊›?Ǎf`NESW`kd√:£Ŀ:ṅ¥`^>v<`ĿfW∩vǔṫ⁽‹ẇwJ:tt\X1"pwJ⟑÷ø∧

```

Try it Online!

Bitstring:

```
000110000111010100000001000100000101011110110001100110111110111101111011001110011001001000011101100001111110011101110101110100100100110111110011000000010110101101110001011010011010000010011111100110010101010011010000110000010100000110001000100010100110010101010000110101110111100001000011001100000001110101110111000000101111101011000110101100100110111100111111000101110011110111110101001011

```

```
⌐⌊›?Ǎf`NESW`kd√:£Ŀ:ṅ¥`^>v<`ĿfW∩vǔṫ⁽‹ẇwJ:tt\X1"pwJ⟑÷ø∧
⌐⌊›                                                    # split by comma, get number part, increment
   ?Ǎf                                                 # get directions and flatten
      `NESW`                                           # Directions
            kd√                                        # "02468"
               :£                                      # duplicate and push to register
                 Ŀ                                     # transliterate directions to corresponding canvas numbers
                  :ṅ¥                                  # duplicate, join by nothing, push register
                     `^>v<`Ŀ                           # Transliterate each direction to corresponding arrow text
                            fW∩                        # flatten, wrap the stack and transpose
                               vǔ                      # rotate each sublist to order [text, length, direction] for canvas
                                 ṫ⁽‹ẇwJ                # decrement the middle of the last triplet
                                       :tt             # get the very last direction
                                          \X1"         # ["X", 1]
                                              pwJ      # prepend it to the direction and put it back (Draws the X)
                                                 ⟑÷ø∧  # draw each triplet to the canvas

```

Created with the help of Luminespire.

# Answer
> 0 votes
# 05AB1E, ~~37~~ 35 (or ~~42~~ 38) bytes

**38 bytes:** Input as comma-separated string, as mentioned in the challenge description:

```
',¡εć"NESW"skxs"^>v<"è)}øR`ā¤Ê+ŠΛ1'X0Λ

```

Try it online.

**35 bytes:** Input as a list of pairs of direction-character and distant-integer, by removing the first three bytes `',¡`:
Try it online.

**Explanation (of the strict I/O program):**

```
',¡           '# Split the (implicit) input-string on commas
   ε           # Map over each string:
    ć          #  Extract its head; push distant and direction-char separately
     "NESW"sk  #  Get the 0-based index of the character in "NESW"
             x #  Double it (without popping)
     s         #  Swap so the index is at the top again
      "^>v<"è  #  Convert the index to the correct output character
     )         #  Wrap all three values into a list
    }ø         # After the map: zip/transpose the list of triplets; swapping rows/columns
      R        # Reverse the list of triplets
       `       # Pop and push all three lists separately to the stack
        ā      # Push a list in the range [1,length]
         ¤     # Push its last item (without popping the list)
          Ê    # Check for each that it's NOT equal to this last item
           +   # Add the values at the same positions
               # (so 1 is added to all distances, except the last one)
        Š      # Triple-swap the three lists on the stack
         Λ     # Canvas builtin with these three arguments
               # (which is output immediately)
1'X0Λ         '# And another Canvas builtin with arguments 1,"X",0
               # (which is done on top of the other Canvas and also output)

```

The Canvas builtin `Λ` takes three arguments:

1. Length(s): which are the modified distances (+1 for every distance except the last one, since the Canvas builtin draws with overlapping corners)
2. The characters we want to display
3. The directions to draw in, which is in this case is \\$0\\$=North; \\$2\\$=South; \\$4\\$=South; \\$6\\$=West.

For example: input `E2,N4,E5,S2,W1,S3` will for `',¡εć"NESW"skxs"^>v<"è)}øR`ā¤Ê+Š` result in the three lists:

1. Lengths: `[3,5,6,3,2,3]`
2. Characters: `[">","^",">","v","<","v"]`
3. Directions: `[2,0,2,4,6,4]`

And will print them as:

```
  >>>>>v
  ^    v
  ^   v<
  ^   v
>>^   v

```

After which the `1'X0Λ` will overwrite the final `v` with `X`.

See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.

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


# Question
Title: The first n numbers without consecutive equal binary digits
The sequence contains the decimal representation of the binary numbers of the form: `10101...`, where the n-th term has n bits.

The sequence is probably easiest to explain by just showing the relationships between the binary and decimal representations of the numbers:

```
0       ->  0
1       ->  1
10      ->  2
101     ->  5
1010    ->  10
10101   ->  21
101010  ->  42

```

### Challenge:

Take an input integer `n`, and return the first n numbers in the sequence. You may choose to have the sequence 0-indexed or 1-indexed.

### Test cases:

```
n = 1   <- 1-indexed
0

n = 18
0, 1, 2, 5, 10, 21, 42, 85, 170, 341, 682, 1365, 2730, 5461, 10922, 21845, 43690, 87381

```

**Explanations are encouraged, as always.**

This is OEIS A000975.

# Answer
> 75 votes
# Python 2, 36 bytes

```
lambda n:[2**i*2/3for i in range(n)]

```

Try it online! Explanation: The binary representation of \\$\frac{2}3\\$ is `0.101010101...` so it simply remains to multiply it by an appropriate power of 2 and take the integer portion.

# Answer
> 11 votes
# 05AB1E, 4 bytes

2 bytes saved using Neil's 2/3 trick

```
Lo3÷

```

Try it online!

**Explanation**

```
L      # push range [1 ... input]
 o     # raise 2 to the power of each
  3÷   # integer division of each by 3

```

---

# 05AB1E, 6 bytes

```
TRI∍ηC

```

Try it online!

**Explanation**

```
T        # push 10
 R       # reverse it
  I∍     # extend to the lenght of the input
    η    # compute prefixes
     C   # convert each from base-2 to base-10

```

# Answer
> 9 votes
# Jelly, ~~...~~ 4 bytes

Thanks *miles* for -1 byte!

```
ḶḂḄƤ

```

Try it online!

Explanation:

```
owered range, or Unength. Get [0, 1, 2, 3, ..., n-1]
 Ḃ    it. Get the last bit of each number. [0, 1, 0, 1, ...]
   Ƥ  for each **Ƥ**refixes [0], [0, 1], [0, 1, 0], [0, 1, 0, 1], ...
  Ḅ   convert it from inary to integer.

```

---

# Jelly, 4 bytes

Jonathan Allan's version.

```
Ḷ€ḂḄ

```

Try it online!

```
owered range, or Unength.
 €    Apply for each. Automatically convert the number **n**
      to the range *[1,2,..,n]*. Get *[[0],[0,1],[0,1,2],..]*.
  Ḃ   it. Get the last bit from each number.
      Current value: *[[0],[0,1],[0,1,0],..]*
   Ḅ  Convert each list from inary to integer.

```

---

A version based on Neil's 2/3 trick gives 5 bytes, see revision history.

# Answer
> 5 votes
# MATL, 5 bytes

```
:WI/k

```

Based on Neil's answer.

### Explanation

```
:       % Implicit input, n. Push range [1 2 ... n]
W       % 2 raised to that, element-wise. Gives [2 4 ...2^n]
I       % Push 3
/       % Divide, element-wise
k       % Round down, element-wise. Implicit display

```

Try it online!

---

# MATL, 9 bytes

```
:q"@:oXBs

```

Try it online!

### Explanation

```
:       % Implicit input n. Range [1 2 ... n]
q       % Subtract 1, element-wise: gives [0 1 ... n-1]
"       % For each k in [0 1 ... n-1]
  @     %   Push k
  :     %   Range [1 2 ... k]
  o     %   Modulo 2, element-wise: gives [1 0 1 ...]
  XB    %   Convert from binary to decimal
  s     %   Sum. This is needed for k=0, to transform the empty array into 0
        % Implicit end. Implicit display

```

# Answer
> 5 votes
# Python 3, ~~68~~ ~~61~~ ~~54~~ ~~48~~ 43 bytes

```
c=lambda x,r=0:x and[r]+c(x-1,2*r+~r%2)or[]

```

Thanks to user202729 for helping save 19 bytes and ovs for helping save 6 bytes.

Try It Online

# Answer
> 5 votes
# Python 2, ~~45~~ ~~37~~ 36 bytes

-3 bytes thanks to user202729
-1 byte thanks to mathmandan

```
s=0
exec"print s;s+=s+~s%2;"*input()

```

Try it online!

# Answer
> 4 votes
## Husk, 7 bytes

```
mḋḣ↑Θİ¬

```

Try it online!

1-based, so input **n** gives the first **n** results.

### Explanation

```
     İ¬   The infinite list [1, 0, 1, 0, 1, ...]
    Θ     Prepend a zero.
   ↑      Take the first n elements.
  ḣ       Get the prefixes of that list.
mḋ        Interpret each prefix as base 2.

```

# Answer
> 4 votes
# Haskell, 47 40 53 49 44 40 34 bytes

-4 bytes thanks to user202729
-6 bytes thanks to Laikoni

```
(`take`l)
l=0:[2*a+1-a`mod`2|a<-l]

```

Try it online!

# Answer
> 4 votes
# APL (Dyalog), 7 bytes

```
⌊3÷⍨2*⍳

```

Try it online!

---

# APL (Dyalog), 11 bytes

```
(2⊥2|⍳)¨1+⍳

```

Try it online!

Uses `⎕IO←0`.

# Answer
> 4 votes
# Perl `v5.10` `-n`, 24+1 bytes

-3 bytes thanks to Nahuel Fouilleul!

```
say$v=$v*2|$|--while$_--

```

Try it online!

Same logic as my Ruby version, but shorter because perl is more concise. For some odd reason, `print` wouldn't do a seperator (dammit!), so I had to use `say` from `v5.10;` in order for this to run, I'm not sure how to score this, so I'm leaving it out for now?...

## Explanation

```
say    # Like shouting, but milder.
  $v = $v*2 | $|-- # Next element is this element times 2 bitwise-OR
                   # with alternating 0 1 0 1..., so 0b0, 0b1, 0b10, 0b101...
                   # $. is OUTPUT_AUTOFLUSH, which is initially 0 and
                   #   setting all non-zero values seem to be treated as 1
  while $_-- # do for [input] times

```

# Answer
> 4 votes
# Haskell, 33 bytes

```
l=1:0:l
($scanl((+).(2*))0l).take

```

Try it online!

# Answer
> 4 votes
# APL (Dyalog Unicode), 11 bytesSBCS

Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems. Anonymous tacit prefix function. 1-indexed.

```
(2⊥⍴∘1 0)¨⍳

```

Try it online!

**ɩ**ndices 0…n−1

`(` apply the following tacit function to each

`⍴∘1 0` cyclically reshape the list `[1,0]` to that length

`2⊥` convert from base-2 (binary) to normal number

# Answer
> 4 votes
# , ~~81 55~~ 59 bytes

1 indexed.

```
i,j;f(c){for(i=j=0;i<c;)printf("%d ",i++&1?j+=j+1:(j+=j));}

```

Full program, less golfed:

```
i;j;main(c,v)char**v;{c=atoi(*++v);for(;i<c;i++)printf("%d ",i&1?j+=j+1:(j+=j));}

```

Try it online!

EDIT 2: I was under the assumption that functions didn't need to be reusable now that I think of it, it makes perfect sense that they would have to be reusable :P

EDIT: I was under the misconception that I had to include the entire program in the answer, turns out I only needed the function that does it. That's nice.

I'm decently sure I can shave off a few bytes here and there. I've already employed a few tricks. A large chunk of the program is dedicated to getting the argument and turning it into an int. This is my first code golf. If I'm doing anything wrong tell me :P

# Answer
> 4 votes
# , 9 bytes

```
[:#.\2|i.

```

## How it works?

`i.` \- list 0..n-1

`2|` \- the list items mod 2

`\` \- all prefixes

`#.` \- to decimal

`[:` \- caps the fork (as I have even number (4) of verbs)

Try it online!

# Answer
> 4 votes
# Ruby, 26 bytes

```
->n{(1..n).map{|i|2**i/3}}

```

Try it online!

Beats all the older ruby answers.

## Explanation

`1/3` in binary looks like `0.01010101...`, so If you multiply it by powers of two, you get:

```
n| 2^n/3
-+---------
1|0.1010101...
2|01.010101...
3|010.10101...
4|0101.0101...
5|01010.101...
6|010101.01...

```

But Ruby floors the numbers on int division, giving me the sequence I need.

# Answer
> 3 votes
## Retina, 28 bytes

```
)K`0
"$+"+¶<`.+
$.(*__2*$-1*

```

Try it online!

0-based, so input **n** gives the first **n+1** results.

### Explanation

Uses the recursion from OEIS:

```
a(n) = a(n-1) + 2*a(n-2) + 1

```

Let's go through the program:

```
)K`0

```

This is a constant stage: it discards the input and sets the working string to `0`, the initial value of the sequence. The `)` wraps this stage in a group. That group itself does nothing, but almost every stage (including group stages) records its result in a log, and we'll need two copies of the `0` on that log for the program to work.

```
"$+"+¶<`.+
$.(*__2*$-1*

```

There's a bunch of configuration here: `"$+"+` wraps the stage in a loop. The `"$+"` is treated as a substitution, and `$+` refers to the program's input, i.e. **n**. This means that the loop is run **n** times.

Then `¶<` wraps each iteration in an output stage, which prints the stage's *input* with a trailing linefeed (so the first iteration prints the zero, the second iteration prints the first iteration's result and so on).

The stage itself replaces the entire working string with the substitution on the last line. That one makes use of an implicit closing parenthesis and implicit arguments for the repetition operator `*`, so it's actually short for:

```
$.($&*__2*$-1*_)

```

The stuff inside the parentheses can be broken up into three parts:

* `$&*_`: gives a string of **a(n-1)** `_`s.
* `_`: gives a single `_`.
* `2*$-1*_`: gives a string of **2\*a(n-1)** `_`. The `$-1` refers to the penultimate result in the result log, i.e. the loop iteration before the last. That's why we needed to copies of the zero on the log to begin with, otherwise this would refer to the program's input on the first iteration.

Then `$.(…)` measures the length of the resulting string. In other words, we've computed `a(n) = a(n-1) + 1 + 2*a(n-2)` by going through unary (not really though: `$.(…)` is lazy and doesn't actually evaluate its content if it can determine the resulting length directly through arithmetic, so this is even quite efficient).

The result of the final loop iteration (the **n+1**th element of the sequence) is printed due to Retina's implicit output at the end of the program.

# Answer
> 3 votes
# Ruby ~~42 41 43 41 37 35 31 33~~ 30 bytes

-2 bytes thanks to Unihedron

-3 bytes thanks to G B

```
->x{a=0;x.times{a-=~a+p(a)%2}}

```

Try it online!

# Answer
> 3 votes
# Java 8, ~~115~~ ~~81~~ ~~80~~ 52 bytes

```
n->{for(int i=2;n-->0;i*=2)System.out.println(i/3);}

```

Port of *@Neil*'s Python 2 answer.
1-indexed and outputted directly, each value on a separated line.

**Explanation:**

Try it online.

```
n->{                           // Method with integer parameter and no return-type
  for(int i=2;                 //  Start integer `i` at 2
      n-->0;                   //  Loop `n` times:
      i*=2)                    //    Multiply `i` by 2 after every iteration
    System.out.println(i/3);}  //   Print `i` integer-divided by 3 and a new-line

```

---

**Old 80 bytes answer:**

```
n->{String t="",r=t;for(Long i=0L;i<n;)r+=i.parseLong(t+=i++%2,2)+" ";return r;}

```

1-indexed input and space-delimited `String` output

**Explanation:**

Try it online.

```
n->{                             // Method with integer parameter and String return-type
  String t="",r=t;               //  Temp and result-Strings, both starting empty
  for(Long i=0L;i<n;)            //  Loop from 0 to `n` (exclusive)
    r+=                          //   Append the result-String with:
       i.parseLong(        ,2);  //    Binary to integer conversion
                   t+=           //     append the temp-String with:
                      i  %2      //      current index `i` modulo-2
                       ++        //      and increase `i` by one afterwards
       +" ";                     //    + a space
  return r;}                     //  Return the result-String

```

# Answer
> 3 votes
# Brain-Flak, 36 bytes

```
{([()]{}<((({}<>)<>){}([{}]()))>)}<>

```

Try it online!

## Explanation:

The next number in the sequence is obtained by `n*2+1` or `n*2+0`.

```
{([()]{}< Loop input times
  (
   (({}<>)<>){} Copy n to other stack; n*2
   ([{}]())  i = 1-i
  ) push n*2 + i
>)} End loop
<> Output other stack

```

# Answer
> 2 votes
# Japt, ~~10~~ ~~9~~ ~~7~~ 6 bytes

All derived independently from other solutions.

1-indexed.

```
õ!²mz3

```

Try it

---

## Explanation

```
õ        :[1,input]
 !²      :Raise 2 to the power of each
   m     :Map
    z3   :Floor divide by 3

```

Try it

---

## 7 byte version

```
õ_ou ì2

```

Try it

```
õ            :[1,input]
 _           :Pass each through a function
   o         :[0,current element)
    u        :Modulo 2 on above
      ì2     :Convert above from base-2 array to base-10

```

---

## 9 byte version

```
õ_îA¤w)n2

```

Try it

```
õ            :[1,input]
 _           :Pass each through a function
   A         :10
    ¤        :Convert to binary
     w       :Reverse
  î          :Repeat the above until it's length equals the current element
      )      :Close nested methods
       n2    :Convert from binary to base-10

```

# Answer
> 2 votes
# \>\<\>, 22 + 3 (-v flag) bytes

```
0:nao::1+2%++$1-:?!;$!

```

Try it online!

### Explanation

The stack gets initialized with the loop counter.

```
0:nao                  : Push 0 to the stack, duplicate and print with a new line.
                         [7] -> [7, 0]
     ::1+              : Duplicate the stack top twice more then add 1 to it.
                         [7, 0] -> [7, 0, 0, 1]
         2%++          : Mod the stack top by 2 then add all values on the stack bar the loop counter.
                         [7, 0, 0, 1] -> [7, 1]
             $1-:?!;$! : Swap the loop counter to the top, minus 1 from it and check if zero, if zero stop the program else continue.

```

# Answer
> 2 votes
# Perl 6,  ~~35 30 27 25~~  20 bytes

```
{[\~](0,+!*...*)[^$_]».&{:2(~$_)}}

```

Try it (35)

```
{(0,{$_*2+|($+^=1)}…*)[^$_]}

```

Try it (30)

```
{(⅓X*(2,4,8…2**$_))».Int}

```

Try it (30)

```
{(⅔,* *2…*)[^$_]».Int}

```

Try it (27)

```
{((2 X**1..$_)X/3)».Int}

```

Try it (25)

```
{(2 X**1..$_)Xdiv 3}

```

Try it (20)

## Expanded:

```
{
 (
  2                  # 2
    X**              # cross to the power of
       1..$_         # Range from 1 to the input (inclusive)
            )

             Xdiv    # cross using integer divide
                  3  # by 3
}

```

# Answer
> 2 votes
# C, ~~47~~ 46 bytes

```
a;f(n){for(a=0;n--;a+=a-~a%2)printf("%d ",a);}

```

The accumulator `a` begins with zero. At each step, we double it (`a+=a`) and add one if the previous least-significant bit was zero (`!(a%2)`, or equivalently, `-(~a)%2`).

## Test program

```
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    while (*++argv) {
        f(atoi(*argv));
        puts("");
    }
}

```

## Results

```
$ ./153783 1 2 3 4 5 6
0
0 1
0 1 2
0 1 2 5
0 1 2 5 10
0 1 2 5 10 21

```

# Answer
> 2 votes
# Python 2, 33 bytes

```
s=2
exec"print s/3;s*=2;"*input()

```

Try it online!

---

# Python 2, 34 bytes

```
f=lambda n:n*[f]and[2**n/3]+f(n-1)

```

Try it online!

Returns in reverse order.

# Answer
> 2 votes
# Thunno 2, 4 bytes

```
RO3÷

```

Attempt This Online!

Port of Neil's Python answer.

#### Explanation

```
RO3÷  # Implicit input       ->  5
R     # Push [1..input]      ->  [1,2,3,4,5]
 O    # Two power of each    ->  [2,4,8,16,32]
  3÷  # Integer divide by 3  ->  [0,1,2,5,10]
      # Implicit output

```

# Answer
> 1 votes
# Ruby `-n`, ~~32~~ 30+1 bytes

Since we have exactly 1 line of input, `$.` is godly convenient!

EDIT: I'm amazed that I managed to outgolf myself, but it seems using `-n` which counts as 1 (by rule 2 in default special conditions, since Ruby can be run with `ruby -e 'full program'` (thus `-n` is 1) all instances of `gets` which is only used once can be golfed down 1 char this way; I believe this is a milestone for ruby, please speak up if you disagree with this train of thought before I repeatedly reuse it in the future)

```
v=0
?1.upto($_){p v=v*2|$.^=1}

```

Try it online!

## Explanation

```
# while gets(); -- assumed by -n
v=0            # First element of the sequence
?1.upto($_){   # Do from "1" to "$LAST_READ_LINE" aka: Repeat [input] times
  p            # print expression
  v=v*2|$.^=1  # Next element is current element times two
               # bitwise-or 0 or 1 alternating
               # $. = lines of input read so far = 1 (initially)
}
# end           -- assumed by -n

```

# Answer
> 1 votes
# JavaScript (ES7), ~~39~~ ~~35~~ ~~31~~ 30 bytes

1-indexed with output in reverse order.

```
f=n=>n?[2**n/3|0,...f(--n)]:[]

```

---

## Try it

```
o.innerText=(
f=n=>n?[2**n/3|0,...f(--n)]:[]
)(i.value=8);oninput=_=>o.innerText=f(+i.value)
```

```
<input id=i type=number><pre id=o>
```

---

## 35 byte version, without recursion

```
n=>[...Array(n)].map(_=>2**n--/3|0)

```

```
o.innerText=(f=
n=>[...Array(n)].map(_=>2**n--/3|0)
)(i.value=8);oninput=_=>o.innerText=f(+i.value)
```

```
<input id=i type=number><pre id=o>
```

# Answer
> 1 votes
# Haskell, 52 bytes

```
(`take`map a[0..])
a 0=0
a 1=1
a n=a(n-1)+2*a(n-2)+1

```

Try it online!

# Answer
> 1 votes
# MATL, 7 bytes

```
:&+oRXB

```

Try it online!

**Explanation:**

```
         % Implicitly grab input, n
:        % Range: 1 2 ... n

 &+      % Add the range to itself, transposed
         % 2 3 4 5 ...
         % 3 4 5 6 ...
         % 4 5 6 7 ...
         % 5 6 7 8 ...

   o     % Parity (or modulus 2)
         % 0 1 0 1 ...
         % 1 0 1 0 ...
         % 0 1 0 1 ...
         % 1 0 1 0 ...

    R    % Upper triangular matrix:
         % 0 1 0 1
         % 0 0 1 0
         % 0 0 0 1
         % 0 0 0 0

    XB   % Convert rows to decimal:
         % [5, 2, 1, 0]
         % Implicitly output

```

The output would be `0, 1, 2, 5 ...` if `P` was added to the end (`flip`), making it 8 bytes.

# Answer
> 1 votes
# brainfuck, 40 bytes

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

```

Try it online!

0-indexed. Input as char code, output as unary with null bytes separating series of char code 1s. Assumes 8-bit cells unless you want to input over 255. Assumes negative cells, though this could be fixed at the expense of several bytes.

### Previously, 50 bytes

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

```

Try it online!

Inputs as char code, outputs as char code. 1-indexed. Probably could be golfed a little.

@Unihedron points out I forgot to specify that this needs infinite sized cells, otherwise it tops out at the 8th number.

# Answer
> 1 votes
# AWK `a=0`, 31 bytes

```
{for(;$1--;a=a*2+1-a%2)print a}

```

Try it online!

Uses the formula shamelessly stolen from this other Ruby answer.

While not having `a=0` would work (awk treats "empty" as 0), the first element of 0 won't get printed and instead be an `empty` line, which while I would argue is a valid output probably won't pass, so there's `a=0` which can be inserted as command line argument.

# Answer
> 1 votes
# C, 52 bytes

```
i,k;f(n){for(i=k=0;i<n;k=++i%2+2*k)printf("%d ",k);}

```

1-indexed

Try it online!

# Answer
> 1 votes
# , 21 bytes

```
cat(2^(1:scan())%/%3)

```

Try it online!

Based on the same algorithm as many here. 1-indexed.

# , 37 bytes

```
for(i in 0:scan())cat(F<-2*F+i%%2,"")

```

Try it online!

0-indexed. Doubling and adding `n mod 2` at each iteration yields the correct result. `F` is initialized to zero.

# Answer
> 1 votes
# Julia 0.6, ~~15~~ 14 bytes

```
!n=2.^(1:n)÷3

```

Try it online!

Using the 2/3 method. `÷` does integer division in Julia and `.` is element-wise function application.

-1 Byte thanks to Dennis.

# Answer
> 1 votes
# Ruby, 27 bytes

```
->n{n.times{|i|p 2**i*2/3}}

```

Try it online!

It's just a Ruby port of this awesome Python answer.

# Answer
> 1 votes
# Actually, 14 bytes

```
r⌠;"10"*H2@¿⌡M

```

Try it online!

Explanation:

```
r⌠;"10"*H2@¿⌡M
r               range(0, input)
 ⌠;"10"*H2@¿⌡M  map (for n in range):
   "10"*          repeat "10" n times
  ;     H         first n characters
         2@¿      interpret as binary integer

```

# Answer
> 1 votes
# Pyt, 5 bytes

```
1←ř«₃

```

Explanation:

```
1        Pushes 1
 ←       Gets input
  ř      Pushes [1,2,...,input]
   «     Bit-shift 1 to the left by each element in the array
    ₃    Python 2-style division by 3 (2^k/3)

```

Try it online!

# Answer
> 1 votes
# Octave, 20 bytes

```
@(x)fix(2.^(1:x)./3)

```

Try it online!

Using @Neils Python method (+1 to him) saves a heck of a lot of bytes.

---

Previous answer (independent creation):

# Octave, ~~49~~ 40 bytes

```
@(n)arrayfun(@(x)sum(2.^(x-1:-2:0)),0:n)

```

Try it online!

Basically for each value `x` in `0:n` where `n` is the input (0-indexed), we take a range of `x-1:-2:0`, and raise 2 to the power of each element in the range. The range results in alternating powers of 2, starting with an empty array `[]` for 0, then `[],[1]` for 0:1, then `[],[1],[1 4]` for 0:2, and so on.

If we then sum each of the produced alternating powers of two, we end up with the required sequence. This only works because in Octave the sum of an empty array is 0, so we can produce the first number 0 by producing no powers of two.

The resulting array, which contains all numbers in the pattern up to and including `n` is then returned.

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

In ascending order. Simple recursion. 1-indexed.

```
f=(n,i=0,a=[])=>n?f(n-1,~i&1+i*2,[...a,i]):a

```

Try it online!

# JavaScript (Node.js), ~~43~~ ~~41~~ ~~38~~ 35 bytes

... or return as string. Still in ascending order. 0-indexed.

```
f=(n,i=0)=>n?i+[,f(n-1,~i&1+i*2)]:i

```

Try it online!

# JavaScript (Node.js), 40 bytes

In ascending order. `2**n/3` trick. 1-indexed.

```
n=>Array(n).fill(i=0).map(_=>2**++i/3|0)

```

Try it online!

# Answer
> 1 votes
## Ruby, 72 68 61 bytes

```
->n{a=[0]*n;n.times{|i|i.times{|j|a[i]|=1<<j if i%2!=j%2}};a}

```

Explained:

```
def f(n)
  a = [0] * n
  n.times do |i|
    i.times do |j|
      if i.even? != j.even?
        a[i] |= (1 << j)
      end
    end
  end
  a
end

```

This approach uses n'th bit installation using x | (1 \<\< n). We start from the last bit and proceeding to the first, setting each 2'nd, alternating ones and zeros 'even?' check tells where to start.

Try Now!

I am new in both code golf and Ruby, so any comments will be appreciated!

# Answer
> 1 votes
# Pip, 11 bytes

```
Lai+:i+!%Pi

```

Attempt This Online!

### Explanation

We can compute this sequence without using binary via the following recurrence relation:

\\$ a\_{n+1} = \left\\{ \begin{array}{ll} 2 a\_n + 1 & \text{ if } a\_n \text{ even,} \\ 2 a\_n & \text{ if } a\_n \text{ odd.} \end{array} \right. \\$

```
Lai+:i+!%Pi
             i (preset to 0) represents the current item in the sequence
 a           First command-line input
L            Loop that many times:
         Pi    Print i
        %      Take i mod 2
       !       Logically negate (1 -> 0 and 0 -> 1)
     i+        Plus current value of i
  i+:          Add that whole expression to i in-place to get next value in sequence

```

# Answer
> 1 votes
# Vyxal, 5 bytes

```
ʁEd3ḭ

```

Try it Online!

Port of Neil's Python answer.

## How?

```
ʁEd3ḭ
ʁ     # Exclusive zero range of (implicit) input
 E    # Square, implicit vectorization
  d   # Double, implicit vectorization
   3ḭ # Floor divide by three, implicit vectorization again

```

# Answer
> 1 votes
# Arturo, 18 bytes

```
$=>[map&=>[/2^&3]]

```

Try it!

Port of The Thonnu's Thunno 2 answer.

# Answer
> 1 votes
# Labyrinth, 22 bytes

```
1?+:_
 }: 3
 " !/
@({\

```

Try it online!

Uses the "power of 2 divided by 3" formula.

```
Intro: 1?
1      Push 1 [1]
?      Input  [1 n]

Loop:  }:+:_3/!\{(  [2^i n-i] -> [2^(i+1) n-(i+1)]
}      Backup top   [2^i | n-i]
:+     Double       [2^(i+1) | n-i]
:      Dup          [2^(i+1) 2^(i+1) | n-i]
_3/    Divide by 3  [2^(i+1) a_(i+1) | n-i]
!\     Print with newline [2^(i+1) | n-i]
{(     Pull and decrement [2^(i+1) n-(i+1)]

Exit:  @ (Halt)

```

# Answer
> 0 votes
# Python 3 53 bytes

```
lambda n:[int(('0'+'10'*i)[:i+1],2)for i in range(n)]

```

Try it online

# Answer
> 0 votes
# Red, 71 67 bytes

```
f: func[n][d: 0 loop n - 1[print d d: d * 2 + either odd? d[0][1]]]

```

1-indexed

Try it online!

And here's the Red impementation of Neil's 2/3 trick:

# Red, 51 bytes

```
f: func[n][repeat i n[print to-integer 2 ** i / 3]]

```

Try it online!

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), 64 bytes

```
	N =INPUT
I	X =LT(X,N) X + 1	:F(END)
	OUTPUT =2 ^ X / 3	:(I)
END

```

Try it online!

1-indexed. Uses the `2^i/3` method.

# Answer
> 0 votes
# 52 bytes

```
i,a;f(n){for(;i++<n;){printf("%d ",a);a=a*2+1-a%2;}}

```

Try it online!

### Without error messages (61 bytes):

```
int i,a;void f(n){for(;i++<n;){printf("%d ",a);a=a*2+1-a%2;}}

```

Try it online!

# Answer
> 0 votes
# Clean, 61 bytes

```
import StdEnv
$i=[sum[2^(n-p)\\p<-[1..n]|isOdd p]\\n<-[0..i]]

```

Try it online!

# Answer
> 0 votes
# Perl 5, 44 + 2 (`-pa`) = 46 bytes

```
$\+=(length sprintf'%b',$_)/$F[0]while$_--}{

```

Try it online!

# Answer
> 0 votes
# clojure, 61 bytes

```
(fn f[n r](if(> n 0)(cons r(f(- n 1)(+ r r 1(-(mod r 2)))))))

```

Usage:

```
user> (f 10 0)
(0 1 2 5 10 21 42 85 170 341)

```

# Answer
> 0 votes
# Dart, 49 bytes

```
f(n,{a:0})=>new List.generate(n,(x)=>a=a<<1|x&1);

```

Use as

```
main() {
 print(f(31));
}

```

See DartPad

# Answer
> 0 votes
# Jelly, 5 bytes

```
R2*:3

```

Try it online!

Took Emigna's strategy and ported it to Jelly.

# Answer
> 0 votes
# Scala, 64 bytes

```
val f=(n:Int)=>Stream from 1 map(i=>(1<<i)/3)take n mkString " "

```

1-indexed. A call to `f(7)` for example would return `0 1 2 5 10 21 42`.

# Answer
> 0 votes
# Jelly, 13 bytes

```
Rṁ@⁾10VDḄ
ḶÇ€

```

Try it online!

# Answer
> 0 votes
# YASEPL, 39 bytes

```
=n=a'(`1!b$2^n-*/3!s$b(}5,b,2+`2<!+}2,a

```

## explanation:

```
=n=a'(`1!b$2^n-*/3!s$b(}5,b,2+`2<!+}2,a       packed
=n                                            declare increment
  =a'(                                        get user input and make it integer
      `1                           }2,a       while n < a...
        !b$2^n-*/3                            b = 2*(2^n-1)/3
                  !s$b(                       set s to floor(b)
                       }5,b,2 `2              if s < b...
                             +                then add one to s.
                                <             print s
                                 !+           add one to n

```

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


title: Say What You See

text:
# Question
Title: Say What You See
The "Look and say" or "Say what you see" sequence is a series of numbers where each describes the last.

```
1
11 (one one)
21 (two ones)
1211 (one two, one one)
111221 (one one, one two, two ones)
312211 (three ones, two twos, one one)

```

and on and on... https://oeis.org/A005150

Anyway, this is a regular code golf challenge (least byte count wins) to make a program that takes two arguments, an initial number and the amount of iterations. For example if you plugged in "1" and "2" the result would be "21". If you plugged in "2" and "4" the result would be "132112". Have fun!

# Answer
> 10 votes
## Pyth, ~~10~~ 8 bytes

*-2 bytes by @FryAmTheEggman*

```
ussrG8Qz

```

Explanation:

```
            Implicit: z=first line as string, Q=second line
u         the result of reducing lambda G:
  s s rG8   flattened run-length-encoded G
  Q       Q times
  z     starting with z

```

Try it here.

# Answer
> 8 votes
## CJam, 8 bytes

```
q~{se`}*

```

Input format is the initial number first, iterations second, separated by some whitespace.

Test it here.

### Explanation

```
q~   e# Read and evaluate input, dumping both numbers on the stack.
{    e# Run this block once for each iteration...
  s  e#   Convert to string... in the first iteration this just stringifies the input
     e#   number again. In subsequent iterations it flattens and then stringifies the
     e#   array we get from the run-length encoding.
  e` e#   Run-length encode.
}*

```

The array is also flattened before being printed so the result is just the required number.

# Answer
> 7 votes
# JavaScript, 57 bytes

```
F=(a,b)=>b?F(a.replace(/(.)\1*/g,c=>c.length+c[0]),b-1):a

```

Recursion works well for this problem. The first parameter is the initial number as a string, and the second is the number of iterations.

# Answer
> 6 votes
## R, 87 bytes

```
function(a,n){for(i in 1:n){r=rle(el(strsplit(a,"")));a=paste0(r$l,r$v,collapse="")};a}

```

**Ungolfed & explained**

```
f=function(a,n){
    for(i in 1:n){                      # For 1...n
        r=rle(el(strsplit(a,"")))       # Run length encoding
        a=paste0(r$l,r$v,collapse="")   # concatenate length vector and values vector and collapse
    };
    a                                   # print final result
}

```

# Answer
> 4 votes
# MATL, 9 bytes

```
:"Y'wvX:!

```

Inputs are: number of iterations, initial number.

**Try it online!**

```
:      % implicit input: number of iterations. Create vector with that size
"      % for loop
  Y'   %   RLE. Pushes two arrays: elements and numbers of repetitions.
       %   First time implicitly asks for input: initial number
  w    %   swap
  v    %   concatenate vertically
  X:   %   linearize to column array
  !    %   transpose to row array
       % implicitly end loop
       % implicitly display

```

# Answer
> 4 votes
# Ruby, 63 bytes

A full program, since the question seems to ask for that. Takes input as command line arguments.

```
i,n=$*
n.to_i.times{i=i.gsub(/(.)\1*/){"#{$&.size}#$1"}}
puts i

```

No, `gsub!` can't be used, since the strings in `$*` are frozen :/

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

-4 thanks to @JayCe, just when I was sure it couldn't be done any simpler!

```
f=function(a,n)`if`(n,f(t(sapply(rle(c(a)),c)),n-1),c(a))

```

Try it online!

# Answer
> 3 votes
# Perl 6, 63 bytes

```
say (@*ARGS[0],*.trans(/(.)$0*/=>{$/.chars~$0})…*)[@*ARGS[1]]

```

This is as short as I could get it for now, there might be some tricky flags that could reduce it, I'm not sure

# Answer
> 3 votes
# Retina, ~~46~~ ~~45~~ 27 bytes

Martin did lots to help golf this.

```
+`(\d)(\1?)*(?=.*_)_?
$#2$1

```

**Try it online**

Takes input in the format:

```
<start><count>

```

`<start>` is the initial number.

`<count>` is in unary, all underscores, and is how many iterations are performed.

### Single iteration, ~~20~~ 16 bytes:

```
(\d)(\1?)*
$#2$1

```

# Answer
> 3 votes
# Haskell, 62 bytes

```
import Data.List
0%y=y
x%y=do x<-group$(x-1)%y;[length x,x!!0]

```

Try it online!

# Answer
> 2 votes
# JavaScript ES6, 71 bytes

```
(m,n)=>[...Array(n)].map(_=>m=m.replace(/(.)\1*/g,x=>x.length+x[0]))&&m

```

Takes input as a string and a number.

# Answer
> 2 votes
# Perl 5, 50 bytes

```
$_=pop;for$i(1..pop){s/(.)\1*/length($&).$1/ge}say

```

The arguments are in reverse order (number of iterations then seed). Example:

```
> perl -E'$_=pop;for$i(1..pop){s/(.)\1*/length($&).$1/ge}say' 4 2
132112
> perl -E'$_=pop;for$i(1..pop){s/(.)\1*/length($&).$1/ge}say' 0 2
2
> perl -E'$_=pop;for$i(1..pop){s/(.)\1*/length($&).$1/ge}say' 2 0
1110
> perl -E'$_=pop;for$i(1..pop){s/(.)\1*/length($&).$1/ge}say' 1 10
1110
> perl -E'$_=pop;for$i(1..pop){s/(.)\1*/length($&).$1/ge}say' 11 1
3113112221232112111312211312113211

```

# Answer
> 2 votes
# Jelly, 6 bytes

```
ŒrUFµ¡

```

Try it online!

```
           Implicit input: first argument.
     µ¡    Do this to it <second argument> times:
Œr            Run-length encode into [value, times] pairs
  U           Flip them
   F          Flatten list

```

# Answer
> 2 votes
# Python 3.6, ~~100~~ ~~98~~ 93 bytes

```
import re
f=lambda s,n:n and eval("f'"+re.sub(r'((.)\2*)',r'{len("\1")}\2',f(s,n-1))+"'")or s

```

Try it online!

Note this creates a lambda that takes a string and an integer, and returns a string. Example: `f('1', 5) == '312211'`

Finds all repeated characters (`((.)\2*)` regex), makes a f-string out of their length and the character itself (`r'{len("\1")}\2'`), then evaluates it. Uses recursion on the counter (`n and ...f(s,n-1)... or s`) to avoid having to define a proper function and a loop.

# Answer
> 1 votes
# Mathematica, ~~81~~ 73 bytes

```
FromDigits@Nest[Flatten[(Tally/@Split@#)~Reverse~3]&,IntegerDigits@#,#2]&

```

# Answer
> 1 votes
## Perl, 38 + 2 bytes

```
for$i(1..<>){s/(.)\1*/(length$&).$1/ge}

```

Requires the `-p` flag:

```
$ perl -pe'for$i(1..<>){s/(.)\1*/(length$&).$1/ge}' <<< $'1\n5'
312211

```

Input is a multi line string:

```
input number
numbers of iterations

```

If all the steps are required as well then we can change it to the following, which is 44 + 2 bytes:

```
$ perl -nE'for$i(1..<>){s/(.)\1*/(length$&).$1/ge,print}' <<< $'1\n5'
11
21
1211
111221
312211

```

# Answer
> 1 votes
# 05AB1E, 9 bytes (Non-competing)

*Corrected due to Emigna's comments, see below/edits.*

```
F.¡vygyÙJ

```

Try it online!

# Answer
> 1 votes
# Stax, 10 bytes

```
Çα▲ì4↔┌j█♀

```

Run and debug online!

Spent too many bytes on proper IO format ...

## Explanation

Uses the unpacked version to explain.

```
DE|R{rm:f$e
D              Do `2nd parameter` times
 E             Convert number to digits
                   Starting from the `1st parmeter`
  |R           Convert to [element, count] pairs for each run
    {rm        Revert each pair
       :f      Flatten the array
         $     Convert array to string of digits
          e    Convert string of digits to integer

```

The essential part is `D|R{rm:f`(8 bytes).

If the first input can be taken as an array of digits, the whole program can be written in 9 bytes: Run and debug online!

# Answer
> 1 votes
# K (ngn/k), 30 bytes

```
{y{,/{(#x;*x)}'(&~=':x)_x}/,x}

```

Try it online!

# Answer
> 1 votes
# , 26 bytes

```
2&([:;](#<@,{.);.1~1,~:/\)

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 6 bytes

```
FÅγøí˜

```

Try it online!

```
FÅγøí˜  # full program
F       # for N in [0, 1, ...,
        # ..., implicit input...
F       # ... minus 1]...
     ˜  # flatten...
   ø    # zipped...
 Åγ     # list of chars used in runs of the same char in...
        # implicit input...
 Åγ     # or top of stack if not first iteration...
   ø    # with...
 Åγ     # list of lengths of runs of the same char in...
        # implicit input...
 Åγ     # or top of stack if not first iteration...
    í   # with each element of the list reversed
        # (implicit) exit loop
        # implicit output

```

`øí` can also be  with no change in functionality. Try it online!

# Answer
> 1 votes
# Husk, 11 bytes

```
!¡(dṁ§eL←gd

```

Try it online!

```
!              # get the arg2-th element of
 ¡             # the infinite list by repeatedly applying
               # (starting with arg1):
  (d           # get the digits of
    ṁ          # applying to each of
         gd    # the groups of identical neighbouring digits:
     §eL←      # combine length + first element

```

# Answer
> 1 votes
# Go, 175 bytes

```
import."fmt"
func g(n int,s string)string{for N:=0;N<n;N++{c,o,f,k:=1,"",rune(s[0]),s[1:]+"_"
for _,r:=range k{if r==f{c++}else{o+=Sprintf("%d%c",c,f);f,c=r,1}}
s=o}
return s}

```

Attempt This Online!

A non-recursive port of Ogaday's answer.

# Answer
> 1 votes
# J-uby, 41 bytes

Takes curried arguments with number of iterations first.

```
:**&(~(:gsub+:+%[:+@|S,~:[]&0])&/(.)\1*/)

```

Attempt This Online!

## Non-regex solution, 47 bytes

```
:**&(A|:slice_when+:!=|:*&-[:+@,~:[]&0]|~:*&"")

```

Attempt This Online!

# Answer
> 1 votes
# Vyxal, 31 bitsv2, 3.875 bytes

```
(øeRf

```

Try it Online!

Bitstring:

```
0011010110011001011100101001100

```

inputs are reversed

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

```
ÆV=ìÈòÎcÈâ iXÊ

```

Try it

# Answer
> 1 votes
# YASEPL, 132 bytes

```
=p'=n'(+`2£s©1`1=q)""=x=l®"p"`3=t$x!h¥t,"p"`4!x+}1,l,5!y¥x,"p"}3,h,4`5!f$x-tſ""!q+f+h!x}2,l,3!n-!p$q<!o$p(!s©o!pſ""!n}!s<!i+}2,n,2

```

prompts you twice. enter starting number and amount of iterations

# Answer
> 0 votes
# Python 3, 138 bytes

I used a recursive approach.

```
def g(a,b):
 if b<1:return a
 else:
  c,n=1,'';f,*a=str(a)+'_'
  for i in a:
   if i==f:c+=1
   else:n+=str(c)+f;f,c=i,1
  return g(n,b-1)

```

The function accepts two ints, `a` and `b` as described.

I'm amazed at how terse the entries here are! Maybe someone will come along with a better Python method too.

# Answer
> 0 votes
# Pylons, 11

```
i:At,{n,A}j

```

How it works:

```
i      # Get input from command line.
:A     # Initialize A
  t    # Set A to the top of the stack.
,      # Pop the top of the stack.
{      # Start a for loop.
 n     # Run length encode the stack.
  ,    # Seperate command and iteration
   A   # Repeat A times.
    }  # End for loop.
j      # Join the stack with '' and print it and then exit.

```

# Answer
> 0 votes
# SmileBASIC, ~~100~~ 98 bytes

```
DEF S N,T?N
WHILE""<N
C=C+1C$=SHIFT(N)IF C$!=(N+@L)[0]THEN O$=O$+STR$(C)+C$C=0
WEND
S O$,T-T/T
END

```

Prints out all the steps. `T/T` is there to end the program when T is 0.

# Answer
> 0 votes
# APL (Dyalog Classic), 22 bytes

```
{∊(≢,⊃)¨⍵⊂⍨1,2≠/⍵}⍣⎕,⎕

```

Try it online!

# Answer
> 0 votes
# Retina, 27 bytes

```
~(`^
K`
$
+`(.)\1$*¶$$.&$$1

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 7 bytes

```
FÅγs.ιJ

```

Try it online!

# Answer
> 0 votes
# GolfScript, 32 bytes

```
~{-1%1/(1@{.3$={;)}1if}/]{\+}*}*

```

Try it online!

Input with first arg as string, +2 bytes for first arg as num:

```
~{`-1%1/(1@{.3$={;)}1if}/]{\+}*~}*

```

---
Tags: code-golf, string, number, sequence, counting
---