title: Find the paths!

text:
# Question
Title: Find the paths!
You must write a program or function.

The input is a 'map' of numbers. You can choose to take the map as either a string with new line characters (`\n`) or a 2D array of strings.

All maps are 5 characters by 5 characters, and the characters are always either digits greater than 0 or spaces.

Here is an example of a map:

```
12 45
11233
  233
    1
2 899

```

Your task is to find the connected components in the map. A valid component is a series of at least three horizontally and/or vertically (*not diagonally*) connected identical digits (*not spaces*). You will then need to replace the characters of the valid connected components with `x`s and print or return that result.

So, the output for the above example would be:

```
x2 45
xx2xx
  2xx
    1
2 899

```

Here's another test case (thanks to Martin Ender):

```
Input:
2   3
    4
 1  5
111 6
11  7

Output:
2   3
    4
 x  5
xxx 6
xx  7

```

This is code golf so shortest code in bytes wins!

# Answer
> 2 votes
# JavaScript (ES6), ~~171~~ ~~161~~ ~~139~~ ~~137~~ ~~136~~ ~~133~~ 132 bytes

```
f=(a,i=0)=>(F=i=>" "<c&&a[i]===c&&(a[i]=n,1+F(i-1)+F(i+1)+F(i-6)+F(i+6)),n=1,c=a[i],n=F(i)>2?"x":c,c=1,F(i),i>28?a:f(a,++i+(i%6>4)))
```

```
<!-- this HTML included just for testing --><textarea rows=5 cols=6 oninput="document.querySelector`pre`.innerHTML=this.value.length==29?f([...this.value]).join``:'invalid input'">12 45
11233
  233
    1
2 899</textarea><br/><pre></pre>
```

This is a translation of my Python answer. I/O as character arrays.

Too bad there's no efficient way of doing `sum`...

# Answer
> 5 votes
# Python 3, ~~238~~ ~~237~~ ~~200~~ ~~199~~ ~~192~~ 181 bytes

```
def f(a,i=0):F=lambda i,n,c:29>i>=0!=" "!=a[i]==c!=n and(a.__setitem__(i,n)or-~sum(F(i+j,n,c)for j in[-1,1,-6,6]));j=i+i//5;F(j,[a[j],"x"][2<F(j,1,a[j])],1);i>23or f(a,i+1);return a

```

Defines a function `f(a)` that takes the input as an array of characters and returns the same array modified. (Arrays of characters are acceptable as strings by default.)

### Ungolfed with explanation

The modified code is recursive, but works the same.

```
# The main function; fills all continuous nonempty areas of size >= 3 in array
# with x's. Both modifies and returns array.
def findpaths(array):
    # Fills a continuous area of curr_char in array with new_char, starting
    # from index. Returns the number of cells affected.
    def floodfill(index, new_char, curr_char):
        if (0 <= index < 29                   # Check that the position is in bounds
                and (index + 1) % 6 != 0      # Don't fill newlines
                and array[index] != " "       # Don't fill empty cells
                and array[index] == curr_char # Don't fill over other characters
                and curr_char != new_char):   # Don't fill already filled-in cells
            array[index] = new_char # Fill current position
            return (1 # Add neighboring cells' results, plus 1 for this cell
                    + floodfill(index + 1, new_char, curr_char)  # Next char
                    + floodfill(index - 1, new_char, curr_char)  # Previous char
                    + floodfill(index + 6, new_char, curr_char)  # Next line
                    + floodfill(index - 6, new_char, curr_char)) # Previous line
        return 0 # Nothing was filled. The golfed solution returns False here,
                 # but that's coerced to 0 when adding.

    for i in range(25): # Loop through the 25 cells
        i += i // 5 # Accommodate for newlines in input
        curr_char = array[i] # Get the cell's contents
        # Fill the area from the cell with dummies
        area_size = floodfill(i, 1, curr_char)
        # Convert dummies to "x" if area was large enough, back to original otherwise
        fill_char = "x" if 2 < area_size else curr_char
        floodfill(i, fill_char, 1)
    return array

```

# Answer
> 3 votes
# Ruby, 304 bytes

```
def b(s,i)
  @v=[]
  b2(s,i,s[i])
end
def b2(s,i,c)
  if(0...s.size)===i&&s[i]==c&&!@v[i]
    @v[i]=s[i]='x'
    [1,-1,6,-6].each{|j|b2(s,i+j,c)}
  end
  s
end
def f(s)
  z = s.dup
  ps = ->(i){b(z.dup,i).scan('x').size}
  (0...s.size).each{|i|b(s, i)if ![' ',"\n"].include?(s[i])&&ps.call(i)>2}
  s
end

```

example usage:

```
puts f(File.read("map.txt"))

```

the code reuses the 'blot' method to calculate the path length.

variables/methods:

* f(s): function to convert map string, returns new map with 'x's
* ps(i): path size from map index i (where x = i % 6, y = i / 6)
* s: input string, map lines separated by "\n"
* z: copy of input string
* b(s,i): 'blot' function: writes 'x' from map index i over paths
* @v: 'visited' array

## Attempt at more detailed explanation:

make a copy of the input string, which we use for finding the length of the path from any given point in the map.

```
z = s.dup

```

define a 'ps' (path length) anonymous function (lambda) which takes the map index i as an argument. it returns the length of the path from that point. it does this by calling the 'b' (blot) method to insert x's on a copy of the original map and then counting the number of x's in the returned string.

```
  ps = ->(i){b(z.dup,i).scan('x').size}

```

the following part iterates over each character in the map (index i, character s\[i\]). it calls the 'b' (blot) function on map position i if the path length from position i is greater than 2, and if it's not a space or newline character.

```
  (0...s.size).each { |i|
     b(s, i) if ![' ',"\n"].include?(s[i]) && ps.call(i) > 2
  }

```

the b (blot) function takes the map string and an index as argument. it initialises @v (visited array) and calls the b2 helper function.

```
def b(s,i)
  @v=[]
  b2(s,i,s[i])
end

```

the b2 function takes the map string, a map position (i), and a character in the current path (c). it calls itself recursively to replace connected sections of digits with the 'x' character. it returns the input string (this is so the ps function can call scan() on the return value).

this if statement is checking that the map position (i) given is within the bounds of the string (0...s.size) and that the character at s\[i\] is the same as the starting character. also @v\[i\] is checked to avoid infinite recursion.

```
if(0...s.size) === i && s[i] == c && !@v[i]

```

this is the bit that replaces the character at index (i) with the 'x' character. it also marks that index as visited.

```
@v[i] = s[i] = 'x'

```

this is where b2 calls itself recursively searching for the path. i+1 is one character to the right, i-1 is one character to the left, i+6 is one row down (5 digits + 1 newline = 6 characters), i-6 is one row up.

```
[1,-1,6,-6].each { |j| b2(s, i+j, c) }

```

# Answer
> 1 votes
# C(Ansi), ~~243~~ ~~233~~ ~~179~~ 188 Bytes

## Golfed:

```
#define O o[1][l]
x,n,l,L;r(o,l)char**o;{if(!(l>L|l<0|O<47|O!=x))n++,O++,r(o,l-1),r(o,l+6),r(o,l-6),r(o,l+1),n>2?O='x':O--;}main(g,o)char**o;{for(;(L=30)>l;l++)n=0,x=O,r(o,l);puts(o[1]);}

```

## With Annotations:

```
#define O o[1][l]
x,n,l,L;      /*-------------------------- Globals*/
r(o,l)char**o;{ /*------------------------ Recursive Function*/
    if(!(l>L|l<0|O<47|O!=x)) /*----------- if this cell is valid(in
                                              range, is a number, is the
                                              same as the parent number*/
    n++,     /*--------------------------- Increment count*/
    O++,     /*--------------------------- Increment character to mark*/
    r(o,l-1),  /*------------------------- Recurse left*/
    r(o,l+6),  /*------------------------- Recurse down*/
    r(o,l-6),  /*------------------------- Recurse down*/
    r(o,l+1),  /*------------------------- Recurse right*/
    n>2?O='x':O--;  /*---------------------If greater than 3, replace with x, else decrement character*/
}          /*----------------------------- Return*/

main(g,o)char**o;{ /*--------------------- Main*/
    for(;l<(L=30);l++){ /*---------------- For entire string and set L*/
        n=0;
        x=O;        /*-------------------- set counter to 0*/
        r(o,l); /*------------------------ Recurse*/
    } /*---------------------------------- End While*/
    puts(o[1]); /*------------------------ Print*/

```

}

## Input:

Expects a newline at the beginning and end of the string.

### Example Input:

```
./findPaths "
12 45
11233
  233
    1
2 899
"

```

### Example Output:

```
x2 45
xx2xx
  2xx
    1
2 899

```

## Update

Making the grid fixed allowed me to shave off nearly 60 bytes.

# Answer
> 1 votes
## Mathematica, 180 bytes

```
(f=Flatten@#;p=Partition)[If[Tr[1^VertexComponent[r~Graph~Cases[##&@@p[#,2,1]&/@Join[g=p[r,5],g],{a_,b_}/;(A=f[[a]])==f[[b]]&&A!=" ":>a<->b],#]]<3,f[[#]],"x"]&/@(r=Range@25),5]&

```

Explanation:

```
(f=Flatten@#;p=Partition)[
  If[
    Tr[1^VertexComponent[
        r~Graph~Cases[
          ##&@@p[#,2,1]&/@Join[g=p[r,5],g],
          {a_,b_}/;(A=f[[a]])==f[[b]]&&A!=" ":>a<->b
        ],
        #
      ]]<3,
    f[[#]],
    "x"
  ]&/@(r=Range@25),
  5
]&

```

Pure function which accepts a `5x5` array.  is the 3-byte private-use character `U+F3C7` representing the postfix transpose operator `\[Transpose]`.

`(f=Flatten@#;p=Partition)`: Flattens the input list and stores it in `f`. Sets `p = Partition` and returns it.

`g=p[r,5]`: The array `{{1,2,3,4,5}, ..., {21,22,23,24,25}}` (this is because `r` gets set to `Range@25`).

`Join[g=p[r,5],g]`: the list of rows and columns of `g`.

`p[#,2,1]&`: Pure function which partitions the list `#` into sublists of length `2` with overlap `1`; i.e., the list of adjacent pairs in `#`.

`##&@@p[#,2,1]&`: Same as above except it returns a `Sequence`.

`##&@@p[#,2,1]&/@Join[g=p[r,5],g]`: Maps the previous function of the rows and columns of `g` to obtain a list of all of the adjacent entries in `g`. My gut says there is a shorter way to do this.

`r~Graph~Cases[...]`: Graph whose vertices are the integers `1, ..., 25` and whose edges are the edges between adjacent entries in `g` which have the same corresponding entries in the input array (other than `" "`)

`{a_,b_}/;(A=f[[a]])==f[[b]]&&A!=" "`: Pattern which matches `{a,b}` such that `f[[a]] == f[[b]]` (same value in the input array) and which are not equal to `" "`. Set `A = f[[a]]` to save `1` byte.

`...:>a<->b`: Replace every match with an undirected edge from a to b.

`VertexComponent`: Returns the connected component of the second argument (a vertex) in the first argument (a graph).

`Tr[1^VertexComponent[...]]`: The size of the connected component. Saves `1` byte from `Length@VertexComponent[...]`.

`If[Tr[...]<3,f[[#]],"x"]&`: Pure function which takes an entry `#` in `g`. If the size of its connected component is less than `3`, replace it with the corresponding entry in the input. Otherwise, replace it with `"x"`.

`(f=Flatten@#;p=Partition)[...,5]`: And finally reshape the result to be a `5x5` array.

# Answer
> 0 votes
## Clojure, 188 bytes

This is quite overwhelming :D

```
#(apply str(map-indexed(fn[i v](if((set(flatten(for[m(range 30)](let[n(for[p[-1 -6 1 6]:when(=(get %(+ m p)0)((set"123456789")(% m)))](+ m p))](if(< 1(count n))(conj n m)[])))))i)\x v))%))

```

Called like this (it takes a 1D vector of characters):

```
(def f #(apply str(...))

(print (str "\n" (f (vec (str "12 45\n"
                              "11233\n"
                              "  233\n"
                              "    1\n"
                              "2 899\n")))))

(print (str "\n" (f (vec (str "2   3\n"
                              "    4\n"
                              " 1  5\n"
                              "111 6\n"
                              "11  7\n")))))

```

Too lazy to ungolf it but basically `for[m(range 30)]` visits each index and for each index the inner `let[n(for[p[-1 -6 1 6]...(+ m p))]` makes a list of 0 to 4 elements which lists locations which had the same value (1 - 9) as the middle location. If more than 1 neighbour matches the mid piece it means that all these form a cluster, so those locations are added to the set used at `(if((set(flatten(...)))i)`. If index `i` is found from the set then `\x` is emitted and the original value otherwise. That `:when( ... )` is quite interesting...

# Answer
> 0 votes
# Julia

## 256 bytes

too long...

readable version:

```
~A=(
  B=hcat(collect.(split(A,"\n"))...);C=copy(B);
  s\T=(
    L=[s];
    C[s...]='_';
    [(-1,0),(1,0),(0,-1),(0,1)].|>y->get(C,y.+s,'_')==T&&(L=vcat(L,(y.+s)\T));
    L
  );
  keys(C).|>x->isdigit(C[x])&&length((L=Tuple(x)\C[x];L))>2&&L.|>y->B[y...]='x';
  join(eachcol(B).|>join,"\n")
)

```

Attempt This Online!

* classical floodfill
* converts the input to char matrix (`B`), copy it (`C`, it is used for admin the visitedness), then performs floodfill from each (current) digits of `C`. `\` returns the vector of connected component `L` and if it fulfills the reqs then modify `B`. At the end it builds a string from `B`.
* works for arbitrary, "rectangular" strings

## 194 bytes

input as char matrix (split+join are outsourced):

```
~B=(
  C=copy(B);
  s\T=(
    L=[s];
    C[s...]='_';
    [(-1,0),(1,0),(0,-1),(0,1)].|>y->get(C,y.+s,'_')==T&&(L=vcat(L,(y.+s)\T));
    L
  );
  keys(C).|>x->isdigit(C[x])&&length((L=Tuple(x)\C[x];L))>2&&L.|>y->B[y...]='x';
  B
)

```

Attempt This Online!

---
Tags: code-golf, string, graph-theory
---


title: Sum the diagonals

text:
# Question
Title: Sum the diagonals
Take a matrix of positive integers as input, and output the individual sums of the elements on the diagonal lines through the matrix.

You shall only count the lines that goes diagonally down and to the right. You must start with the diagonal that contains only the bottom-left element, then the length-two diagonal above that (if it exists) and so on through to the diagonal that contains only the top-right element, as illustrated below.

**Example:**

```
Input:
 8   14    5    1
10    5    5    8
 6    6    8   10
15   15    4   11

Output:
15, 21, 20, 32, 29, 13, 1
(Diagonals: {{15},{6,15},{10,6,4},{8,5,8,11},{14,5,10},{5,8},{1}})

Input:
1
Output:
1

Input:
1 5
Output:
1, 5

Input:
4
1

Output:
1, 4

Input:
17    4    5
24   16    5
 9   24   10
 1   14   22
 1   21   24
 4    4   17
24   25   17

Output:
24, 29, 22, 39, 47, 70, 43, 9, 5

```

Input and output formats are optional as always.

This is , so the shortest submission in each language wins.

# Answer
> 6 votes
# Mathematica, ~~53~~ 54 bytes

```
l=Length@#-1&;Tr@Diagonal[#,k]~Table~{k,-l@#,l@#&@@#}&

```

Pure function taking a 2D-array as input and returning a list. (Entries don't have to be integers or even numbers.) `Diagonal[#,k]` returns the `k`th diagonal above (or below, if `k` is negative) the main diagonal. `{k,-l@#,l@#&@@#}` computes the range of diagonals needed based on the dimensions of the input array. And `Tr` sums the entries of each diagonal.

# Answer
> 6 votes
# Haskell, ~~40~~ 37 bytes

```
z=0:z
foldl1$(.(++z)).zipWith(+).(0:)

```

Try it online! Usage: `(foldl1$(.(++z)).zipWith(+).(0:)) [[1,2,3],[4,5,6]]`.

**Edit:** Thanks to Ørjan Johansen for -3 bytes!

### Ungolfed:

```
z = 0:z
s#t = zipWith(+)(0:s)(t++z)
f m = foldl1 (#) m

```

`z` is a list of infinitely many zeros. In `f` we fold over the list of lists `m` by combining two lists with the function `#`. In `#` the first list `s` contains the accumulated column sums so far and the second list `t` is the new row which should be added. We shift `s` one element to the right by adding a zero to the front and element-wise add `s` and `t` with `zipWith(+)`. Because `s` might be arbitrarily large, we have to pad `t` with enough zeros by appending `z`.

# Answer
> 5 votes
## JavaScript (ES6), ~~65~~ 58 bytes

```
a=>a.map(b=>b.map((c,i)=>r[i]=~~r[i]+c,r=[,...r]),r=[])&&r

```

# Answer
> 5 votes
# MATL, 6 bytes

```
T&XdXs

```

Try it online! Or verify all test cases.

### Explanation

```
T&Xd   % All diagonals of implicit input arranged as zero-padded columns
Xs     % Sum of each column. Implicitly display

```

# Answer
> 5 votes
# Jelly, 5 bytes

```
0;+µ/

```

Try it online!

### How it works

```
0;+µ/  Main link. Argument: M (matrix / array of rows)

   µ   Combine all links to the left into a chain (arity unknown at parse time) and
       begin a new monadic chain.
    /  Reduce M by that chain. This makes the chain dyadic.
       Let's call the arguments of the chain L and R (both flat arrays).
0;         Prepend a 0 to L.
  +        Perform element-wise addition of the result and R.
           When the chain is called for the n-th time, R has n less elements, so
           the last n elements of L won't have matching elements in R and will be
           left unaltered.

```

# Answer
> 3 votes
# CJam, ~~22~~ 21 bytes

Saved 1 byte thanks to Martin Ender

```
{_,({0\f+}*ee::m<:.+}

```

Anonymous block expecting the argument on the stack and leaves the result on the stack.

Try it online!

**How it works**

```
_                   e# Duplicate the matrix
 ,(                 e# Get its length (# of rows) minus 1
   {0\f+}*          e# Prepend that many 0s to each row
          ee        e# Enumerate; map each row to [index, row]
            ::m<    e# Rotate each row left a number of spaces equal to its index
                :.+ e# Sum each column

```

# Answer
> 2 votes
# 05AB1E, 17 bytes

```
Rvy¹gÅ0«NFÁ}})øO¨

```

Try it online!

**Explanation**

```
R                  # reverse input
 v                 # for each N,y (index, item)
  y¹gÅ0«           # pad y with as many zeroes as the number of rows in the input
        NFÁ}       # rotate each row N times right
            })     # wrap the result in a list
              øO   # sum the columns
                ¨  # remove the last element of the resulting list (the padded zeroes)

```

# Answer
> 2 votes
# , 7 bytes

```
+//.@|.

```

Try it online!

This is pretty simple:

```
+//.@|.
+/        sum
  /.      on oblique lines
    @|.   on the reversed array

```

Oblique reversed lines are the diagonals of the array, so this is just summing the diagonals.

# Answer
> 2 votes
# Python 2, 62 bytes

```
lambda M:reduce(lambda x,y:map(sum,zip([0]+x,y+[0]*len(x))),M)

```

Try it online!

# Answer
> 1 votes
# Jelly, 8 bytes

```
ŒDS€ṙZL$

```

**Try it online!**

Half of the code is used to put the results into the correct order.

### How?

```
ŒDS€ṙZL$ - Main link: list of lists of numbers
ŒD       - diagonals (starts with the diagonal containing the top left element,
         -            then the next diagonal to the right, and so on wrapping around)
  S€     - sum €each
       $ - last two links as a monad
     Z   - transpose the matrix
      L  - length (width of the matrix)
    ṙ    - rotate the results left by that amount

```

# Answer
> 1 votes
# Perl 5, 47 bytes

```
map{$j=--$.;map{@a[$j++]+=$_}split}<>
print"@a"

```

# Answer
> 1 votes
## R, 45 bytes

Unnamed function taking a matrix-class object as input:

```
function(x)sapply(split(x,col(x)-row(x)),sum)

```

Using the idea explained in this answer.

# Answer
> 1 votes
# Octave, 71 bytes

Assuming A is a matrix, for example:

```
A = [17 4 5;24 16 5; 9 24 10; 1 14 22; 1 21 24; 4 4 17;24 25 17];

```

Then we have:

```
[m,n]=size(A);
a=[zeros(m,m-1),A]';
for i=1:m+n-1
trace(a(i:end,:))
end

```

Notice that transposing the matrix reverses the ordering of the diagonal sums, which saved an overall two bytes in the for loop.

Output:

```
ans =  24
ans =  29
ans =  22
ans =  39
ans =  47
ans =  70
ans =  43
ans =  9
ans =  5

```

# Answer
> 1 votes
# Vyxal, 7 bytes

```
ÞD?L‹ǔṠ

```

Try it Online!

Takes 4 bytes to get it in the right order. If the order didn't matter, it would be 3 bytes (remove the `?L‹ǔ`).

# Answer
> 0 votes
# Python, 126 bytes

```
x=input()
f=lambda k:[x[i+k][i]for i in range(len(x)-k)]
a=map(f,range(4)[::-1])
x=zip(*x)
print(map(sum,a+map(f,range(1,4))))

```

`f` only works on the lower triangular section, so I transpose it and get the upper triangular section that way. Don't know why the `f` function doesn't work for negative values (I changed `f` to be shorter because the part to get the negatives didn't work).

# Answer
> 0 votes
# C, 148 bytes

**Try Online**

```
s;g(int i,int j,int**m,int x){for(s=0;x;x--)s+=m[i++][j++];printf(" %d",s);}
k;f(int n,int**m){for(k=n;--k;)g(k,0,m,n-k);for(;k<n;k++)g(0,k,m,n-k);}

```

# Answer
> 0 votes
# PHP, 81 Bytes

Take Input as 2 D Array

```
<?foreach($_GET as$k=>$v)foreach($v as$x=>$y)$r[$x-$k]+=$y;ksort($r);print_r($r);

```

Try it online!

# Answer
> 0 votes
# Awk, 67 Bytes

```
{for(f=0;f++<NF;)s[NF-NR+f]+=$f}END{i=0;while(i++<NR*2)print s[i]}

```

Ungolfed:

```
{
    for (f = 0; f++ < NF;)
        s[NF-NR+f] += $f
}
END {
    i = 0
    while (i++ < NR*2)
        print s[i]
}

```

Awk splits on whitespace `$n` is the `n`th field (1-indexed); `NF` is the number of fields on the line, `NR` is the number of the current row. Undefined variables are 0 and created on first use.

# Answer
> 0 votes
# PHP, 86 bytes

a memory friendly solution in two variants:

```
<?for($i=$c=count($a=$_GET);--$i>-$c;print$s._)for($s=0,$d=$c;$d--;)$s+=$a[$i+$d][$d];
<?for($i=$c=count($a=$_GET);--$i>-$c;print$s._)for($s=$d=0;$d<$c;)$s+=$a[$i+$d][$d++];

```

takes input from script parameters, uses underscore as delimiter;
use default settings (not default php.ini) or try them online

# Answer
> 0 votes
## Clojure, 81 bytes

```
#(apply map +(map(fn[i c](concat(repeat(-(count %)i 1)0)c(repeat i 0)))(range)%))

```

Quite verbose, as it pads lists with zeros so that we can just calculate the column-wise sum.

# Answer
> 0 votes
## mathematica 73 bytes

```
Plus@@@Table[Diagonal[Partition[#1,#2[[1]]],k],{k,-#2[[2]]+1,#2[[1]]-1}]&

```

This one works for ANY 2D-array m x n (not only nxn)
input the array at the end of the code like this (the last test case)

```
[{17,4,5,24,16,5,9,24,10,1,14,22,1,21,24,4,4,17,24,25,17},{3,7}]

```

> {24, 29, 22, 39, 47, 70, 43, 9, 5}

input in form \[{a,b,c,d...},{m,n}\]

# Answer
> 0 votes
# Husk, 6 bytes

```
mΣ∂m↔T

```

Try it online.

**Explanation:**

```
     T  # Transpose the (implicit) argument; swapping rows/columns
   m↔   # Reverse each row
  ∂     # Take the anti-diagonals of this matrix
mΣ      # And sum each inner anti-diagonal list
        # (after which the result is output implicitly)

```

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


title: Print N Squared

text:
# Question
Title: Print N Squared
Write a program or function that takes in a non-negative integer N from stdin or as a function argument. It must print or return a string of a hollow ASCII-art square whose sides are each made with N copies of the number N.

### Specifically:

If N is `0`, no copies of N are used, so there should be no output (or only a single trailing newline).

If N is `1`, the output is:

```
1

```

If N is `2`:

```
22
22

```

If N is `3`:

```
333
3 3
333

```

If N is `4`:

```
4444
4  4
4  4
4444

```

If N is `5`:

```
55555
5   5
5   5
5   5
55555

```

The pattern continues for `6` through `9`.

If N is `10`, the output is:

```
10101010101010101010
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10101010101010101010

```

**Notice that this is not actually square.** It is 10 rows tall but 20 columns wide because `10` is two characters long. This is intended. The point is that each side of the "square" contains N copies of N. **So all inputs beyond `9` will technically be ASCII rectangles.**

For example, if N is `23`, the output is:

```
2323232323232323232323232323232323232323232323
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
2323232323232323232323232323232323232323232323
```

Here are Pastebins of the required outputs for `99`, `100`, `111`, and `123` (they may look wrong in a browser but in a text editor they'll look correct). The output for `1000` is to large for Pastebin but it would have 1000 rows and 4000 columns. **Numbers with 4 or more digits must work just like smaller numbers.**

### Details:

* N must be written in the usual decimal number representation, with no `+` sign or other non-digits.
* The hollow area must only be filled with spaces.
* No lines should have leading or trailing spaces.
* A single newline after the squares' last line is optionally allowed.
* Languages written after this challenge was made are welcome, they just aren't eligible to win.
* **The shortest code in bytes wins!**

# Answer
> 5 votes
# Jolf, ~~31~~ ~~27~~ ~~25~~ 23 bytes

```
?=1i1ρρ,aii+*3έέi*li

```

This is encoded in the ISO-8859-7 encoding and contains unprintables, so here's a hexdump:

```
0000000: 3f3d 3169 31f1 f12c 6169 692b 2a33 dd05  ?=1i1..,aii+*3..
0000010: dd69 052a 056c 69                        .i.*.li

```

Try this fiddle online or verify all test cases at once (use the full run button).

This exits with an error for n = 0, which is allowed by default.

Massive thanks to Conor for golfing off ~~4~~ 6! bytes. inb4 crossed out four still looks like a four comment

## Explanation

```
?=1i1ρρ,aii+*3έ\x05έi\x05*\x05li

?=1i1                             if input is 1 return 1, otherwise...
       ,aii+*3έ\x05               draw an input x input hollow box of tabs
      ρ            έi             replace all tabs with input
     ρ               \x05*\x05li  replace all spaces with spaces * length of input

```

# Answer
> 16 votes
# Shtriped, 317 bytes

While I'm making the question, I may as show off my new "purist" language.

```
@ f x
 d x
 f
 @ f x
+ x y
 +
  i x
 @ + y
 h x
} x y
 e 1
 i 1
 d y
 d 1
 d x
 } x y
e 0
e 2
i 2
i 2
e 6
+ 2 2 6
+ 2 6 6
e T
+ 2 2 T
+ 6 T T
e N
t N
e P
+ T 0 P
e L
i L
*
 e x
 *
  + P x x
 @ * T
 h x
~
 } N P 0
 d 0
 i L
 * P
 ~
~
#
 p N
-
 s 6
_
 @ - L
$
 #
 @ _ n
 #
 s 2
@ # N
e n
+ N 0 n
d n
d n
s 2
@ $ n
@ # N
```

(definitely works in v1.0.0)

There are no math operations built into Shtriped except increment and decrement. There's also no looping or conditionals, so all of these thing need to be built up from scratch in every program.

That's what my program does, e.g. `@` is essentially a for loop, `+` is an addition function, `}` is `>=`. The actual output is only produced in the last 8 lines of the program.

There are no strings either in Shtriped. You can take in and print out strings, but they are all represented internally as arbitrary precision integers that can only be incremented and decremented. So there's no easy way get the length of the string `10` for filling in the the square center with the right amount of spaces. I had to cobble together the function `~` that effectively computes `floor(log10(N)) + 1` to find the length of N in decimal.

This could probably be golfed a bit more by rearranging where and how which variables are used, but not *that* much more. There's no getting around Shtriped's inherent limitations. (It was never meant to be a golfing language anyway.)

**Commented code (a backslash is a comment):**

```
@ f x \ function that calls f() x times, returns 0
 d x
 f
 @ f x
+ x y \ returns x + y
 +
  i x
 @ + y
 h x
} x y \ returns 1 if x >= y, else 0
 e 1
 i 1
 d y
 d 1
 d x
 } x y

\ declare and set up variables for the numbers 0, 2, 6, 10
e 0 \ 0 is used to help copy values via +
e 2 \ 2 is used for printing newlines
i 2
i 2
e 6 \ 6 is used for printing spaces
+ 2 2 6
+ 2 6 6
e T \ 10 is used for finding the string length of N
+ 2 2 T
+ 6 T T

e N \ declare N
t N \ and set it to what the user inputs

\ all the code from here to the last ~ is for finding the length of N as a string

e P \ P is the current power of 10 (10, 100, 1000...), starting with 10
+ T 0 P
e L \ L will be the length of N in decimal digits
i L

* \ function that returns P times 10 by adding P to itself 10 times
 e x
 *
  + P x x
 @ * T
 h x

~ \ function that increments L and multiplies P by 10 until N < P, at which point L will be the string length of N
 } N P 0 \ the 0 variable can be used as a dummy now since we don't need it anymore
 d 0
 i L
 * P \ multiply P by 10 to
 ~
~

\ helper functions for displaying the output
# \ simply prints N as a decimal integer
 p N
- \ prints a single space
 s 6
_ \ prints L spaces (L = digit length of N)
 @ - L
$ \ prints one of the central N-2 lines of the square
 #
 @ _ n
 #
 s 2

\ finally, call these functions to display the output
@ # N \ print N copies of N (top line of square)
e n \ declare n and set it to N - 2
+ N 0 n
d n
d n \ if N was 0 or 1 the program will end here, having printed nothing if 0 or just the top line if 1
s 2 \ print a newline
@ $ n \ print the central line of the square N-2 times
@ # N \ print N copies of N (bottom line of square)

\ the output always prints without a trailing newline

```

# Answer
> 8 votes
## Seriously, ~~32~~ ~~31~~ ~~30~~ 29 bytes

```
╩╜ó$╝╜Dbu╜╛*n╜¬;╛l*' *╛+╛@+n(

```

Try it online!

Explanation:

```
╩╜ó$╝╜Dbu╜╛*n╜¬;╛l*' *╛+╛@+n(
╩                              push each input to its own register
                                 (we'll call register 0 "n")
 ╜                             push n to the stack
  ó                            terminate if 0
   $╝                          push str(n) to register 1
                                 (we'll call register 1 "s")
     ╜Dbu╜╛*n                  make min(2,n) copies of s*n (the top and bottom)
                                 (this avoids an extra copy if n is 1)
             ╜¬;               push n-2 twice
                ╛l*' *         push (n-2)*len(s) spaces
                      ╛+╛@+    put s on the front and end of the string (a middle piece)
                           n   push (n-2) total copies of the middle piece
                            (  bring the top piece to the top

```

# Answer
> 6 votes
# C++14, 156 chars

I thought it was a pretty cool solution though obviously can not beat most other entries here.

```
#define f for(i=0;i++<n;c<<t);
[](string t){auto&c=cout;int n=stoi(t),i;f c<<'\n';for(i=0;++i<n-1;c<<t,c.width(~-n*size(t)+1),c.fill(0),c<<t+'\n');if(n-1)f}

```

Ungolfed:

```
#define f for ( i = 0; i++ < n; c << t ); // print top/bot row
[](string t) {
  auto& c = cout;
  int n = stoi(t), i;
  f // print first row
  c << '\n'; // kind of annoying but no way to get rid of (yes I tried
             // c << '\n'+t instead of c << t+'\n')
  for ( i = 0; ++i < n - 1; ) {
    c << t; // output the number
    // then we we get the width of necessary spaces
    c.width(~-n*size(t)+1); // Equivalent to (n-1)*size(t) + 1, but we save
                            // two bytes since ~- takes precedence over
                            // multiplication
    c.fill(0); // fill with spaces, ' ' == 0
    c << t+'\n';
   }
   if ( n-1 ) f // This if statement is dissapointing
}

```

And like always, to call the function use `[](string t) { ... }("10");`

# Answer
> 5 votes
# JavaScript (ES6), ~~73 82~~ 78 bytes

*Saved a4 bytes thanks to @user81655*

```
n=>(a=n[r='repeat'](n),n<2?a:a+`
${n+' '[r](n.length*(n-2))+n}`[r](n-2)+`
`+a)

```

Takes a string, not a number for input.

Try it online (all browsers work)

# Answer
> 5 votes
# MATL, ~~34~~ ~~29~~ 26 bytes

```
:G\2<t!+gQ"@!2GVYX1GVnZ"YX

```

This works with current release (13.0.0) of the language/compiler

**Try it online!**

```
:            % array [1,2,...,N], where N is input, taken implicitly
G\           % modulo N. Gives [1,2,...,N-1,0]
2<           % smaller than 2? Gives [1,0,...,0,1]
t!           % duplicate, transpose
+            % addition with broadcast. Gives 2D array with nonzeros in the border
             % and zeros in the interior
gQ           % convert to logical, add 1: twos in the border, ones in the interior
"            % for each column of that array (note the array is a symmetric matrix,
             % so columns and rows are the same)
  @!         %   push column. Transpose into a row
  2GVYX      %   replace twos by the string representation of N, via regexp
  1GVnZ"YX   %   replace ones by as many spaces as length of that string, via regexp
             % end for each, implicitly
             % display stack contents, implicitly

```

# Answer
> 5 votes
# T-SQL/SQL Server 2012+, 167 161 bytes

```
DECLARE @ INT = 6;

SELECT IIF(u IN(1,s),REPLICATE(s,s),CONCAT(s,REPLICATE(' ',s-2*LEN(s)),s))
FROM(SELECT @ s)z CROSS APPLY(SELECT TOP(s)ROW_NUMBER()OVER(ORDER BY 1/0)u FROM sys.messages)v

```

Output:

```
666666
6    6
6    6
6    6
6    6
666666

```

`**`LiveDemo`**`

Enter desired size and click `Run query` to get text representation.

Please note that this demo does not display **fixed-width font**. So `7` is thicker than `1`.

---

**EDIT:**

If we treat input as string:

```
DECLARE @ VARCHAR(10) = '7';

SELECT IIF(u IN(1,s),REPLICATE(s,s),s+REPLICATE(' ',s-2*LEN(s))+s)
FROM(SELECT @ s)z CROSS APPLY(SELECT TOP(s+0)ROW_NUMBER()OVER(ORDER BY 1/0)u FROM sys.messages)v

```

`**`LiveDemo2`**`

# Answer
> 4 votes
# Julia, 78 bytes

```
n->(s="$n";(p=println)(s^n);[p(s*" "^(n-2)endof(s)*s)for i=2:n-1];n>1&&p(s^n))

```

This is an anonymous function that accepts an integer and prints the ASCII rectangle to STDOUT. To call it, assign it to a variable.

Ungolfed:

```
function f(n)
    # Save a string version of n
    s = "$n"

    # Print the top line
    println(s^n)

    # Print each middle line
    [println(s * " "^(n-2)endof(s) * s) for i = 2:n-1]

    # Print the last line if there is one
    n > 1 && println(s^n)
end

```

Try it online

# Answer
> 4 votes
# Ruby, 100 bytes

```
->n{s="";n.times{|i|s+=(i<1||i>n-2?"#{n}"*n :"#{n}#{' '*[(n-2)*n.to_s.size,0].max}#{n}")+$/};puts s}

```

Too bad I couldn't even manage to beat JS. Any further help golfing it down would be appreciated.

Here's a more or less ungolfed version:

```
def f(n)
    n.times{|num|
        if num == 0 || num == n-1
            s += "#{n}" * n
        else
            s += "#{n}"+" "*[(n-2)*n.to_s.length,0].max+"#{n}"
        end
        s += "\n"
    }
    puts s
end

```

# Answer
> 4 votes
# Retina, 76 bytes

```
.+
$0$*n$0
n(?=n*(\d+))|.
$1_
\d+_
$_¶
T`d` `(?<=¶.*_.*).(?=.*_\d.*¶\d)
\`_
[empty line]

```

Explanation maybe comes tomorrow.

Try it online here.

# Answer
> 4 votes
## TSQL, ~~112~~ 104 bytes

```
DECLARE @ varchar(10)='12'

PRINT REPLICATE(@,@)+ISNULL('
'+REPLICATE(@+ISNULL(SPACE((@-2)*len(@))+@,'')+'
',@-2)+REPLICATE(@,@),'')

```

> ```
> 1. generating first line
> 2. adding hollow lines + line breaks
> 3. adding last line(when needed)
>
> ```

# Answer
> 3 votes
## Minkolang 0.15, 57 bytes

```
nd?.d1-2&N.$z01FlOz2-[lz6Z" "I2-z2-*Dz6Z$O]01F.
z[z6Z]$Of

```

Try it here!

### Explanation

```
n                Read number from input
 d?.             Stop if n=0, continue otherwise
    d1-2&N.      Print 1 and stop if n=1, continue otherwise
           $z    Store top of stack in register (z, which is n)

01F                                   Gosub to second line
   lO                                 Print newline
     z2-                              Push value from register and subtract 2
        [                             Pop k and run body of for loop k times
                                      (Does not run if k <= 0)
         l                            Push a newline
          z6Z                         Push z and convert to string
             " "                      Push a space
                I2-                   Push length of stack minus 2
                   z2-                Push z minus 2
                      *               Pop b,a and push a,b
                       D              Pop k and duplicate top of stack k times
                        z6Z           Push z and convert to string
                           $O         Output whole stack as characters
                             ]        Close for loop
                              01F.    Gosub to second line and stop after returning.

z[   ]       For loop that runs z times
  z6Z        Push z and convert to string
      $O     Output whole stack as characters
        f    Return to position called from

```

# Answer
> 3 votes
# Pyth - 26 bytes

```

K*`QQjbm++Q**l`Q;ttQQttQK
```

Try it online here.

# Answer
> 3 votes
# Perl, ~~79~~ ~~76~~ 74 bytes

```
$_=$.=pop;s/./ /g;print$.x$.,$/,($.,$_ x($.-2),$.,$/)x($.-2),$.>1?$.x$.:''

```

Pretty straightforward. The first commandline argument is taken as the number. Place the script in a file and run with `perl file.pl 1`.

# Answer
> 3 votes
## Perl, ~~62~~ ~~60~~ 58 + 2 = 60 bytes

```
for$.(1..$_){say$.>1&$.<$_?$_.$"x(y...c*($_-2)).$_:$_ x$_}

```

Requires `-nlE` flags:

```
$ perl -nlE'for$.(1..$_){say$.>1&$.<$_?$_.$"x(y...c*($_-2)).$_:$_ x$_}' <<< 5
55555
5   5
5   5
5   5
55555

```

With spaces added:

```
for$.(1..$_) {
  say(
    $. > 1 & $. < $_
      ? $_ . $"x(length$_*($_-2)) . $_
      : $_ x $_
  )
}

```

# Answer
> 3 votes
# R, 90 bytes

```
x=scan();m=matrix(x,x,x);k=2:(x-1)*(x>2);m[k,k]=format("",w=nchar(x));write(m,"",n=x,s="")

```

---

This creates a matrix of `x*x` size and then fills with spaces of size `nchar(x)` . If `x` smaller than 2, then nothing is being filled.

# Answer
> 3 votes
# Pip `-l`, 21 bytes

*Uses language features newer than the question, which is allowed per current policy; if the wording of the question is interpreted to override said policy, see 25-byte answer below.*

```
Yq{MN++g%y>1?sMyy}MCy

```

Try it online!

Thanks to Luis Mendo's MATL answer for the `(a+1)%n<2` trick.

### Explanation

`Yq` reads a line from stdin and yanks it into `y`. Then:

```
{              }MCy  Map this function to each coordinate pair in a y-by-y grid
                     (Inside the function, the list of both coords is g)
   ++g                Increment both coordinates
      %y              Take them mod y
 MN     >1?           Test whether the min of the resulting list is 2 or greater
           sMy         If so, it's in the center; use len(y) spaces
              y        If not, it's an edge; use the number y
                     Print result with newlines between rows (implicit, -l flag)

```

---

Original 2016 answer, **25 bytes** (plus `-l` flag):

```
Yq{MN++*a%y<2?ysX#y}MMCGy

```

Changelog:

* `MC` was added more recently; at the time, I used `MMCG` (map-map + coordinate-grid).
* There was a bug in the current interpreter that prevented using `++` on lists, so I had to do `++*` (apply `++` to each element) instead.
* `M`ap has been extended: now `<string1> M <string2>` returns a list of `len(<string2>)` copies of `<string1>`; at the time, I used `sX#y`, string-repeating space by `len(y)`.

# Answer
> 2 votes
## Pyth, ~~37~~ 30 bytes

```
J*K`QQI>Q1JV-Q2++Q*d-lJ*2lKQ;J

```

Try it here.

```
J*K`QQ                          set K to repr(input); that is, stringified
                                  set J to K repeated (input) times
      I>Q1                  ;   if input is greater than 1...
          J                     output J (stringified input times input)
           V-Q2                 do this (input - 2) times...
               ++               output the following on one line:
                 Q              the input number
                  *d-lJ*2lK     n spaces, where n = len(J) - 2*len(K)
                           Q    the input number again
                            ;   break out of everything
                             J  output J (str(input)*input) one last time,
                                  regardless of whether input > 1

```

# Answer
> 2 votes
# Retina, 90

Again, I'm pretty sure this will be greatly golfable by the experts:

```
.+
$&$&$*:$&$*;
+`(\d+:):
$1$1
+`([\d+:]+;);
$1$1
T`d` `(?<=;\d+:)[^;]+(?=:\d+:;\d)
:

;
¶

```

Try it online.

# Answer
> 2 votes
## Pyke, 33 bytes (noncompetitive)

```
QD`i*Djli2*lR-k*iRi]3J"bR+2Q-*jR+

```

Explanation:

```
                                  - autoassign Q = eval_or_not(input())
QD`i*                             - Get the input multiplied by itself
Q                                 - [Q]
 D                                - [Q, Q]
  `                               - [repr(Q), Q]
   i                              - i = stack[0]
    *                             - [stack[0]*stack[1]]

     Djli2*lR-                    - Get number of spaces
     D                            - [^,^]
      j                           - j = stack[0]
       l                          - len(stack[0])
        i2*                       - i*2
           l                      - len(stack[0])
            R                     - rotate_2()
             -                    - stack[0]-stack[1]

              k*iRi               - Get middle line
              k*                  - " "*^
                iRi               - [i,^,i]

                   ]3J"bR+        - Join middle line together
                   ]3             - list(stack[:3])
                     J"           - "".join(stack[0])
                       bR+        - ^+"\n"

                          2Q-     - Get middle lines
                          2Q-*    - Q-2

                              jR+ - Add end line
                              jR+ - ^+j

```

# Answer
> 2 votes
# Jelly, 28 bytes

Grr, can’t tell if Jelly is bad at strings, or if I’m bad at Jelly.

```
ŒṘ©L⁶xWẋWẋ$®W¤1¦€U'Z$$4¡j⁷ȯ⁷

```

Try it online.

# Answer
> 2 votes
## CJam, 27 bytes

```
ri:X,_ff{a+[0X(]&XXs,S*?}N*

```

Thanks to @MartinBüttner for suggesting `ff`. The `a+[0X(]&` is pretty fishy, but oh well.

Try it online!

```
ri:X              Read input integer and save as variable X
,_                Range, i.e. [0 1 ... X-1] and make a copy
ff{...}           Map with extra parameter, twice. This is like doing a Cartesian product
                  between two 1D arrays, but we get a nice X by X array at the end

                  For each coordinate pair,
a+                Put the two coordinates into an array
[0X(]&            Set intersection with the array [0 X-1]
X                 Push X
Xs,S*             Push a number of spaces equal to the length of X
?                 Ternary: choose one of the previous two depending on the set intersection

N*                Join X by X array with newlines

```

# Answer
> 2 votes
## Haskell, 78 bytes

```
i x=unlines$take x$1#s:3#[s++(3#s>>" ")++s]++[1#s]where s=show x;z#s=[z..x]>>s

```

Usage example:

```
*Main> putStr $ i 4
4444
4  4
4  4
4444

```

The function `>>` comes in handy: `<list> >> <string>` makes `length <list>` copies of `<string>`, e.g. top and bottom lines for `x=10` are `[1..10] >> "10"` -\> `"10101010101010101010"`.

# Answer
> 2 votes
## Perl, 72 bytes

```
$_=($.=pop)-2;say for($.x$.,($..($.x$_)=~s/./ /rg.$.)x$_,$.x$.)[0..$.-1]

```

Relies on modern Perl features :

> **say** 'something'

is automatically available since Perl 5.10 (simply use v5.10 or later).

> str\_expr =~ s/.../.../**r**

happily accepts to work on a rvalue (an str\_expr not necessarily reduced to a scalar variable) to yield a **r**esult (the '**r**' option at the end of the regex) without altering the initial str\_expr.

# Answer
> 2 votes
# PHP, 151 bytes

```
function s($n){for($r=0;$r<$n;$r++){for($c=0;$c<$n;$c++){if($r*$c&&$r!=$n-1&&$c!=$n-1){for($d=0;$d<=log10($n);$d++){echo' ';}}else{echo$n;}}echo"\n";}}

```

Absolute mess, need more time to optimize. `s(Number)` gives you the output.

# Answer
> 2 votes
## Python 3, ~~108~~ ~~96~~ 148 bytes

```
a=input()
b=c=int(a)-2 if a!="1" else 0
print(a*int(a))
while b:print(a+" "*int(len(a))*c+a);b-=1
if a!="1":print(a*int(a))

```

Ungolfed/explained:

```
number = input() # Gets a number as input
iterator = var = int(number) - 2 if number != "1" else 0 # Assigns two variables, one of them an iterator, to the number minus 2 (the amount of middle rows in the square) if the number isn't 1. If it is, it sets the vars to 0 so the while doesn't trigger.
print(number * int(number)) # Prints the top row of the square.
while iterator != 0: # Loops for the middle rows
    print(number + " " * int(len(number)) * var + number) # Prints the number, then as many spaces as needed, and the number.
    iterator -= 1 # De-increments the iterator.
if number != 1: # Makes sure the number isn't 1, because 1 should return 1.
    print(a * int(a)) # Same as the first row, it prints the bottom row.

```

As this is my first answer, some constructive criticism and/or suggestions would be helpful!

# Answer
> 2 votes
## Java 8, 280 bytes

```
interface A{static<T>void p(T o){System.out.print(o);}static void main(String[]a){long n=new Long(a[0]),l=a[0].length();for(long i=0;i<n;i++,p(a[0]));p("\n"+(n>1?a[0]:""));for(long j=2;j<n;j++,p(a[0])){for(long i=l*2;i<n*l;i++,p(' '));p(a[0]+"\n");}for(long i=1;i<n;i++)p(a[0]);}}

```

It's only about 10 times as long as the shortest answers, which is really good for Java!

Example run:

```
$ java A 10
10101010101010101010
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10101010101010101010

```

# Answer
> 2 votes
# Rust, 141 137 bytes

Abused some formatting stuff, otherwise this would've been a lot longer.

```
|i|{let f=||{for _ in 0..i{print!("{}",i)}println!("")};f();if i>1{for _ in 0..i-2{println!("{}{0:1$}",i,i.to_string().len()*(i-1))}f()}}

```

Unpacked:

```
|i| {
    let f = || {
        for _ in 0..i {
            print!("{}",i)
        }
        println!("")
    };

    f();

    if i>1 {
        for _ in 0..i-2 {
            println!("{}{0:1$}",i,i.to_string().len()*(i-1))
        }
        f()
    }
}

```

Playground Link

# Answer
> 2 votes
# Powershell, ~~98~~ ~~96~~ ~~95~~ ~~83~~ ~~82~~ 75 bytes

```
param($n)($l="$n"*$n)
if(($m=$n-2)-ge0){,"$n$(' '*"$n".Length*$m)$n"*$m
$l}

```

Ungolfed and explained test script:

```
$f = {

    param($n)
    ($l="$n"*$n)                #   let $l is a string contains N only and return this value as a first line
    $m=$n-2
    if($m-ge0){                 # if(N>1)
        $s=' '*"$n".Length*$m   #   let $s is spaces inside repeated (length of string represented of n * m)
        ,"$n$s$n"*$m            #   return $m strings contains: N, spaces and N
        $l                      #   retrun the first line again
    }

}

&$f 1
&$f 2
&$f 3
&$f 4
&$f 10

```

Output:

```
1
22
22
333
3 3
333
4444
4  4
4  4
4444
10101010101010101010
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10101010101010101010

```

# Answer
> 2 votes
# MathGolf, ~~28~~ ~~25~~ 19 bytes

```
░*k┴╜o\⌡{khí **k++p

```

Try it online!

## Explanation

This was a fun challenge. Disclaimer: this language is younger than the challenge itself, but the methods used for this answer are not designed for this challenge in particular. I realised that I can save a byte for the 1-case, and by reducing the number of print statements.

```
░                     convert implicit input to string
 *                    pop a, b : push(a*b)
  k                   read integer from input
   ┴                  check if equal to 1
    ╜                 else without if
     o                print TOS without popping (handles the 1-case)
      \               swap top elements
       ⌡              decrement twice
        {             start block or arbitrary length
         k            read integer from input
          h           length of array/string without popping
           í          get total number of iterations of for loop
                      space character
             *        pop a, b : push(a*b)
              *       pop a, b : push(a*b) (this results in (n-2)*numdigits(n)*" ")
               k      read integer from input
                +     pop a, b : push(a+b)
                 +    pop a, b : push(a+b)
                  p   print with newline

```

# Answer
> 2 votes
# Vyxal, 20 bytes

```
ẋṅ,⇩(L⁰‹*$S↲₴,)ċ[ẋṅ,

```

Try it Online!

## How?

```
ẋṅ,⇩(L⁰‹*$S↲₴,)ċ[ẋṅ,
ẋ                    # Repeat the (implicit) input the (implicit) input number of times (returns a list)
 ṅ                   # Join by nothing
  ,                  # Print with trailing newline
   ⇩(                # Loop (implicit) input minus 2 times:
     L               #  Get the length of the (implicit) input
      ⁰‹             #  Push the input minus 1
        *            #  Multiply the length by that
         $           #  Swap to make (implicit) input at top
          S          #  Convert the input to a string
           ↲         #  Pad the stringified input with leading spaces until its length is len(input) * (input - 1) calculated earlier
            ₴        #  Print this without a trailing newline
             ,       #  Print the (implicit) input with trailing newline
              )      # Close loop
               ċ[    # If the (implicit) input is not one:
                 ẋ   #  Repeat the (implicit) input the (implicit) input amount of times
                  ṅ  #  Join by nothing to make it a string
                   , #  Print with trailing newline

```

# Answer
> 1 votes
## Pyth, 27 bytes

```
jsMmm?sqM*,dk,0tQ`Q*\ l`QQQ

```

Test suite.

# Answer
> 1 votes
# 05AB1E, ~~34~~ ~~30~~ 29 bytes

Code:

```
F¹}JDU,¹!#¹DÍF¹gFð}}¹J¹ÍF=}X,

```

Try it online!

I didn't have some kind of fancy string multiplication function, but here is the submission *with* the function. It's something I added after the challenge and is therefore non-competing:

**26 bytes:**

Code:

```
D×DU,¹¹Í¹g*ð×¹J¹ÍF=}¹1›iX,

```

Uses **CP-1252** encoding.

# Answer
> 1 votes
# Python 2, 70 characters

```
def p(i):
 k=`i`;j=i-2;h=k*i;print h+'\n'+(k+' '*j*len(k)+k+'\n')*j+h

```

# Answer
> 1 votes
## Ruby, 79 bytes

```
->n{s=n.to_s
puts s*n
$><<(s+" "*s.size*(a=n-2)+s+$/)*a if n>2
$><<s*n if n>1}

```

Some cases print a trailing line after the last line and some do not, but the question does not disallow this.

# Answer
> 1 votes
# PHP 112 ~~114~~ ~~120~~ bytes

```
<?php $z=$j=$argv[1];while($j){$i=(--$j&&$i)?$z.str_pad('',strlen($z)*($z-2)).$z:str_repeat($z,$z);echo"$i\n";}

```

Command line usage: `php scriptname.php [n]`

ideone demo

This golf uses `str_repeat` for the first and last row and `str_pad` for the rows in between.

# Answer
> 1 votes
# Dyalog APL, 41 bytes

```
{1≥⍵:⍵⍴⍵⋄(' '≠⍕⍵/⍵)/⍕⍵⍪⍨⍵⍪⍵,⍵,⍨''⍴⍨2/⍵-2}

```

# Answer
> 1 votes
# Python 2, 73 characters

```
def l(i):s=`i`;n='\n';l=i-2;b=s*i+n;print b+(s+' '*l*len(s)+s+n)*l+b*(i>1)

```

# Answer
> 1 votes
# Python 3.5, 101 135 bytes:

(*+34 since apparently an input of 1 should just output 1 and an input of 0 should output nothing*)

```
def y(g):g=str(g);i=len(g);[print(g*(int(g))+('\n'+g+' '*((int(g)*i)-(i*2))+g)*(int(g)-2)+'\n'+g*int(g))if int(g)>1 else print(g*int(g))]

```

Prints out all the correct values for any integer input, whether in string form or not.

**Sample Inputs and Outputs:**

```
Input: y(10)

Output:

    10101010101010101010
    10                10
    10                10
    10                10
    10                10
    10                10
    10                10
    10                10
    10                10
    10101010101010101010

Input: y(1)

Output:

    1

Input: y(2)

Output:

    22
    22

Input: y(4)

Output:

    4444
    4  4
    4  4
    4444

```

However, for triple digit numbers, it was just too big to fit on my monitor, so I hope that comes out correct if someone else tries it. I suspect it should since all 1 and 2 digit numbers come out correctly.

# Answer
> 1 votes
## Python 3, 75 characters

```
def q(n):s=str(n);m=n-2;print(s*n,*[s+" "*len(s)*m+s]*m,s*n*(n>1),sep="\n")

```

# Answer
> 1 votes
# PHP, 86 Bytes

```
for(;$i<$a=$argn;)echo str_pad($a>1?$a:"",($a-1)*strlen($a),$i++&&$i<$a?" ":$a)."$a
";

```

Try it online!

# Answer
> 1 votes
# JS to ES6 compatibilized, ~~136~~ 76 B

```
function x(a){var c='';function Q(){for(var b=0;b<a;++b)c+=a}Q();c+='\n';
for(b=2;b<a;++b){c+=a;for(let A=2;A<a;++a)c+=' ';c+=a+'\n'}Q()}

```

Works way smaller:

```
x=(a,c)=>{Q=(í,k)=>{for(;í<a;++í)c+=k}Q(0,a);c+='\n';Q(2,a+Q(2,' ')+a+'\n')}

```

# Answer
> 1 votes
**Python 2,96 bytes**

```
s=raw_input()
n=int(s)
for i in range(n):
 if 0<i<n-1:print s+' '*(n-2)*len(s)+s
 else:print s*n

```

**Python 3,94 bytes**

```
s=input()
n=int(s)
for i in range(n):
 if 0<i<n-1:print(s+' '*(n-2)*len(s)+s)
 else:print(s*n)

```

# Answer
> 1 votes
# Python 3, 78 bytes

```
N=input()
n=int(N)
m=n-2
b=N*n+"\n"
print(b+(N+" "*len(N)*m+N+"\n")*m+b*(n>1))

```

Try it online!

I went back and forth over multiple approaches to this (even using `exec()` at one point, then ditching it because it was unnecessary), but I figured out that this is the shortest Python 3 approach.

# Answer
> 1 votes
# 05AB1E, 16 bytes

```
×,<GgIÍ*ú«,}≠i×,

```

Try it online or verify all test cases.

**Explanation:**

```
×          # Repeat the (implicit) input the (implicit) input amount of times as string
 ,         # Pop and print this string with trailing newline
<G         # Loop the (implicit) input-2 amount of times:
  g        #  Get the length of the (implicit) input
   IÍ      #  Push the input-2
     *     #  Multiply it by the length
      ú    #  Pad the (implicit) input with that many leading spaces
       «   #  Append it to the (implicit) input
        ,  #  Pop and print it with trailing newline
 }         # Close the loop
  ≠i       # If the (implicit) input is NOT 1:
    ×      #  Repeat the (implicit) input the (implicit) input amount of times as string
     ,     #  Pop and print this string with trailing newline

```

I don't think I've ever used the fact that input can be implicitly as many times in a single program as this one. xD

# Answer
> 1 votes
# Regenerate, 42 bytes

```
(($~1){$~1})((
$2 {#2}{$2-2}$2){$2-2}
$1!)

```

Attempt This Online!

For clarity, space is replaced with `_` and newline is replaced with :

```
(                    # Capture the first line as $1, for reuse as the last line.
    ($~1){$~1}       # Repeat N in decimal, N times. Capture N in $2 for golf,
                     # which allows referring to it as "$2" instead of "$~1" and
                     # its length as "#2" instead of "#~1".
)
(
    (
        ¶
        $2           # Output N in decimal for the left edge.
        _{#2}{$2-2}  # Output length(N)*(N-2) spaces
        $2           # Output N in decimal for the right edge.
    ){$2-2}          # Repeat the above N-2 times. This will cause a non-match
                     # if N == 1, preventing this entire block from matching,
                     # which will also prevent the top line from being repeated
                     # as the bottom line below.
    ¶
    $1               # Repeat the top line as the bottom line.
!
                     # If N == 1, the above alternative won't be able to match;
                     # do nothing here, to prevent it from triggering a top-level
                     # non-match.
)

```

# Answer
> 0 votes
# Mathematica,116 bytes

```
Switch[#,0,"",1,1,_,#5<>#4[#<>#4[" ",StringLength@#*#3]<>#<>"\n",#3]<>#5&[##,#~#4~#2<>"\n"]&[ToString@#,#,#-2,Table]]&

```

Somewhat long, but oh well.

# Answer
> 0 votes
# Oracle SQL 11.2, ~~106~~ ~~105~~ 115 bytes

```
SELECT RPAD(:1,(:1-1)*LENGTH(:1),DECODE(LEVEL,1,:1||'',:1,:1||'',' '))||:1 FROM DUAL WHERE:1>0 CONNECT BY:1>=LEVEL;

```

10 bytes added to manage 0

# Answer
> 0 votes
# SmileBASIC, 89 bytes

```
INPUT N$N=VAL(N$)Q=N>1FOR I=1TO N?N$*!!N*G;" "*LEN(N$*(N-Q*2))*G;N$*(Q*G+N*!G)G=I<N-1NEXT

```

# Answer
> 0 votes
# Common Lisp, SBCL, 151 bytes

```
(defun c(x)(if(< x 10)1(1+(c(/ x 10)))))(lambda(a)(format t"~:[~v{~a~:*~}~&~v@{~v<~a~;~a~>~4@*~&~}~*~v@{~a~:*~}~;1~]"(= a 1)a`(,a)(- a 2)(*(c a)a)a a))

```

function for counting digits adjusted to CL from Joshua's answer here

### Ungolfed

```
(defun c(x)
    (if(< x 10) 1
    (1+ (c(/ x 10))))) ;counting digits
(lambda(a)
    (format t"~:[~v{~a~:*~}~&~v@{~v<~a~;~a~>~4@*~&~}~*~v@{~a~:*~}~;1~]"(= a 1)a`(,a)(- a 2)(*(c a)a)a a))
;~[~] checks whether agument is equal 1 (if it is equal 1 then print out only "1") - without it we would print out 1\Newline 1
;first loop: ~v{~a~:*~} - printing first line of N
;second loop: uses justification "~<~>" to output enough spaces between N's on sides
;third loop: -printing last line of N

```

# Answer
> 0 votes
## QBIC, ~~61~~ 58 bytes

```
;_LA|x=!A!~x=1|?A\Y=A+space$((x-2)*a)+A[x|Z=Z+A]?Z[x-2|?Y]

```

Explanation

```
;          Read A$ from the cmd line
_LA|       Take the length of A$ and assign to a
x=!A!      Cast A$ to int, assign to x
~x=1|?A    If x == 1, quit printing just the 1
\Y=A       Else, setup Y$ as the middle of the square; it starts as the literal input
  +space$( Followed by X spaces
  (x-2)*a) where X is the length of the string x the value, minus start and end
  +A       Followed by the input again
[x|        This FOR loop creates the top row
Z=Z+A]     By concatenating the input x times to itself and assigning it to Z$
?Z         Print the top row
[x-2|?Y]   Print the right amount of middle rows
           And the bottom row (Z$) is implicitly printed at EOF.

```

# Answer
> 0 votes
# Lua, 101 bytes

```
p,n=print,io.read()d,s=#n,n:rep(n)p(s)for i=3,n do p(n..(" "):rep(d*(n-2))..n)end p(n+0>1 and s or"")

```

Alternate 102 bytes:

```
l,n="\n",io.read()d,s=#n,n:rep(n)print(s..l..(n..(" "):rep(d*(n-2))..n..l):rep(n-2)..(n+0>1 and s or""))

```

101 Readable:

```
p,n=print,io.read()
d,s=#n,n:rep(n)
p(s)
for i=3,n do
  p(n..(" "):rep(d*(n-2))..n)
end
p(n+0>1 and s or"")

```

Lua naturally has a small trick here by being able to convert a number as a string (e.g. "123") into a string or a number as needed based on context. It's not 100% intelligent though as you can see in my "ternary" statement at the end for handling the 0 and 1 cases- I had to use n+0 to coax it into a number before comparing it to 1.

# Answer
> 0 votes
# Perl 5, 67+2=69 bytes

Requires the flags `-lp`.

```
$@=($,=$"=$_)-2;$,x=$,;s/./ /g;$"=$".$_ x$@.$".$/;$_=$,.$/.$"x$@.$,

```

Has all the length of a mainstream language, and the unreadability of a more esoteric language!

# Answer
> 0 votes
# WC, 146 bytes

```
;>_0|;>_0|$-;>_0|;>=_0|[<]$'[>]$--[>]$--[>];>_0|$''_0|!$?#@3|//#;>(?[>]$-!!_0|;>@5|$''[<<<<]!!$?!$[>>>>>>];<?[>]##@3|/#)?##@10|[>>>>>]*$#?[>>>>]!$

```

Try it online!

Ungolfed/commented:

```
;>_0|;>_0|       var n, var c
$-               decrement c
;>_0|;>=_0|      var i, var len = length(X)
[<]              move to i
$'[>]            multply i by len
$--[>]$--[>]     i -= len (x2)
;>_0|$''_0|      var full = X repeated X times
!$               print full
?                reset index
#@3|             if n == 0
  //             terminate
#                end if
;>(              new function
  ?[>]           set index to 1
  $-!!_0|        decrement c and print it
  ;>@5|          var spaces
  $''[<<<<]      repeat i times
  !!$            print spaces
  ?              reset index
  !$             print n
  [>>>>>>]       move to spaces
  ;<             delete spaces var
  ?[>]           set index to 1
  ##@3|          if c != 0
    /            restart context (this function)
  #              end if
)                end function
?                reset index
##@10|           if n != 2 (10th global)
  [>>>>>]        set index to 5
  *$             call the function
#                end if
?[>>>>]          set index to 4
!$                print full

```

# Answer
> 0 votes
# APL(NARS), 69 chars, 138 bytes

```
{⍵≤1:⍕⍳⍵⋄f←{⊂∊⍺/⊂⍕⍵}⋄y←((⍴⊃x←f⍨⍵)-2×⍴r←⍕⍵)f' '⋄⊃x,((⊂∊r,y,r)/⍨⍵-2),x}

```

test:

```
  g←{⍵≤1:⍕⍳⍵⋄f←{⊂∊⍺/⊂⍕⍵}⋄y←((⍴⊃x←f⍨⍵)-2×⍴r←⍕⍵)f' '⋄⊃x,((⊂∊r,y,r)/⍨⍵-2),x}
  ⎕fmt   g¨0 1 2 3 11
┌5──────────────────────────────────────────┐
│┌0┐ ┌1┐ ┌2─┐ ┌3──┐ ┌22────────────────────┐│
││ │ │1│ 222│ 3333│ 11111111111111111111111││
│└¯┘ └─┘ │22│ │3 3│ 111                  11││
│        └──┘ │333│ │11                  11││
│             └───┘ │11                  11││
│                   │11                  11││
│                   │11                  11││
│                   │11                  11││
│                   │11                  11││
│                   │11                  11││
│                   │11                  11││
│                   │1111111111111111111111││
│                   └──────────────────────┘2
└∊──────────────────────────────────────────┘

```

# Answer
> 0 votes
# Pyth, 29 bytes

```
*zKszVSJ-K2p+z*J*lzdz)I>K1*zK

```

Try it online!

Properly handles "1" case, even if it cost me 3 more characters to do so. Still new to Pyth, and there's some interesting stuff happening with that Pyth answer that uses all the joins.

```
*zKsz        #input auto-assigned to z as string, assign K to int(z), and print z*K
VSJ-K2       #set J to K-2, for N in range J
p+z*J*lzdz   #print with no newline: z + (" " * len(z)) * (K - 2), print z
)I>K1*zK     #close for loop and print z*K if K greater than 1

```

# Answer
> 0 votes
# C# (.NET Core), 146 bytes

```
a=>{string b=a.ToString(),s="";for(int i=0,j,k;++i<=a;s+="\n")for(j=0;++j<=a;)if(i>1&i<a&j>1&j<a)for(k=0;k++<b.Length;)s+=" ";else s+=b;return s;}

```

Try it online!

Ungolfed:

```
a => {
    string b = a.ToString(), s = "";            // initialize b (saves 4 bytes) and s (return variable)
    for(int i = 0, j, k; ++i <= a; s += "\n")   // for each row of the square
        for(j = 0; ++j <= a;)                       // for each column of the square
            if(i > 1 & i < a & j > 1 & j < a)           // if not an edge of the square
                for(k = 0; k++ < b.Length;)                 // for each digit in a
                    s += " ";                                   // add a space
            else                                        // if an edge of the square
                s += b;                                     // add the input num
    return s;                                   // output the full string

```

# Answer
> 0 votes
# Japt, 22 bytes

```

_hUçU)z3
NgV gV gV gV

```

Try it online!

More competitive than I expected, though I wouldn't be surprised if Charcoal or something has a really short answer that just hasn't been found yet.

Explanation:

```

                :Empty line preserves the input as U

_hUçU)z3        :Declare a function V taking an argument Z:
_h   )          : Set the first line of Z to
    U           :  U as a string
  Uç            :  Repeated U times
      z3        : Rotate Z 90 degrees counterclockwise

NgV gV gV gV    :Main program
N               : Start with an arbitrary array (in this case [U])
 gV gV gV gV    : Apply V 4 times

```

It's necessary to rotate counterclockwise in `V` because a single-line array always ends up left-aligned when rotated, making clockwise rotations take an extra `gV`. The 1 extra byte for `z3` instead of `z` was better.

# Answer
> 0 votes
# Japt `-R`, 18 bytes

```
îU
U+ÕÅ+UÔÅ Õ·hJUw

```

Test it online!

# Answer
> 0 votes
# Batch, 264 bytes

```
@echo off&setlocal enabledelayedexpansion&set o=&set m=
for /l %%i in (1,1,%1)do set o=!o!%1&if %%i gtr 2 set m=!m!%1
if %1 gtr 0 echo %o%&if %1 gtr 2 (for /l %%i in (0,1,9)do set m=!m:%%i= !
set/an=%1-2
for /l %%i in (1,1,!n!)do echo %1!m!%1)
if %1 gtr 1 echo %o%

```

Only works for numbers up to 2029 because of the length limitations of `echo`.

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


title: Print the sequence

text:
# Question
Title: Print the sequence
## **21, 21, 23, 20, 5, 25, 31, 24, ?**

Inspired by this Puzzle, given an integer \\$n\>0\\$ , print out the following sequence until you reach a non-Integer (spoilered, in case you want to solve the puzzle yourself first)

> \\$a\_0 = n\\$
> \\$a\_{4k+1} = a\_{4k} \cdot(4k+1) \\$
> \\$a\_{4k+2} = a\_{4k+1} + (4k+2)\\$
> \\$a\_{4k+3} = a\_{4k+2} - (4k+3)\\$
> \\$a\_{4k+4} = a\_{4k+3} / (4k+4)\\$
> or more intuitively: \*1, +2, -3, /4, \*5, +6, -7, /8, ...

**TestCases:**

> 1: 1, 1, 3, 0, 0, 0, 6, -1
> 2: 2, 2, 4, 1
> 3: 3, 3, 5, 2
> 4: 4, 4, 6, 3
> 5: 5, 5, 7, 4, 1, 5, 11, 4
> 6: 6, 6, 8, 5
> 9: 9, 9, 11, 8, 2, 10, 16, 9
> 21: 21, 21, 23, 20, 5, 25, 31, 24, 3, 27, 37, 26

**Input** and **Output** may be taken in any reasonable format, standard loopholes are as forbidden as usual.

**In the spirit of , the shortest answer in byte wins!**

Sandbox: https://codegolf.meta.stackexchange.com/a/18142/59642

# Answer
# 05AB1E (legacy), ~~18~~ 17 bytes

```
[N"/*+-"Nè.VÐïÊ#=

```

Try it online or verify all test cases.

**Explanation:**

```
[                # Start an infinite loop:
 N               #  Push the 0-based loop-index
  "/*+-"         #  Push string "/*+-"
        Nè       #  Index into this string with the loop-index
          .V     #  And use a 05AB1E-eval to calculate the next number
 Ð               #  Triplicate this number
  ï              #  Cast it to an integer
   Ê             #  And if it's NOT equal to the number we triplicated:
    #            #   Stop the infinite loop
  =              #  Print the number without popping

```

I'm using the legacy version of 05AB1E here, and also first calculate the next number before printing it, because the loop is 0-based and it will do a `/0` in the very first iteration. This saved a byte in comparison to the previous `N>` and `"*+-/"`. This only works, because in the legacy version a number that's being divided by 0 remains the same; whereas in the new version it would become 0; and in actual math it would give a division by zero error.
> 6 votes

# Answer
# Scratch 3.0 39 blocks/323 bytes

Try it on~~line~~ scratch!

*Alternatively, as SB syntax:*

```
when gf clicked
delete[all v]of[o v
ask()and wait
set[. v]to(answer
set[n v]to(1
repeat until<(n)contains[.
if<((n)mod(4))=(0
set[. v]to((. )*(n
else
if<((n)mod(4))=(1
change[. v]by(n
else
if<((n)mod(4))=(2
change[. v]by((0)-(n
else
set[. v]to((. )/(n
end
end
end
add(n)to[o v
change[n v]by(1
end
delete(length of(o))of[o v

```

Look at you guys, having fun with your fancy `eval` statements! Well, not me! **No**... Scratch doesn't have evals, so I had to do things the hard way... if statements.

At least it isn't `goto`s...
> 13 votes

# Answer
# Haskell, ~~75 74~~ 73 bytes

*-1 byte thanks to Will Ness* *-1 byte thanks to nimi*

```
(#1)
n#i|i`mod`4<1,n`mod`i>0=[n]|y<-i+1=n:(x!!i)n i#y
x=div:(*):(+):(-):x

```

Try it online!

Avoids the use of fractional ints to save on bytes
> 8 votes

# Answer
# Whitespace, ~~251~~ ~~227~~ 202 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][N
S S N
_Create_Label_LOOP][S N
S _Duplicate_top][T N
S T _Print_as_integer][S S S T  S T S N
_Push_10_newline][T N
S S _Print_as_character][S N
T   _Swap_top_two][S S S T  N
_Push_1][T  S S S _Add][S T S S T   N
_Copy_2nd_item][S T S S T   N
_Copy_2nd_item][S N
S _Duplicate_top][S S S T   S S N
_Push_4][T  S T T   _Modulo][S N
S _Duplicate_top][N
T   S S N
_If_0_Jump_to_Label_DIVIDE][S S S T N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate_top][N
T   S T N
_If_0_Jump_to_Label_MULTIPLY][S S S T   N
_Push_1][T  S S T   _Subtract][N
T   S S S N
_If_0_Jump_to_Label_ADD][S N
T   _Swap_top_two][S T  S S T   N
_Copy_2nd_item][T   S S T   _Subtract][N
S N
N
_Jump_to_LOOP][N
S S S N
_Create_Label_DIVIDE][S N
N
_Discard_top][T S T S _Divide][S T  S S T   S N
_Copy_3nd_item][S T S S T   S N
_Copy_3nd_item][T   S T T   _Modulo][N
T   S N
_If_0_Jump_to_Label_LOOP][N
N
N
_Exit_Program][N
S S T   N
_Create_Label_MULTIPLY][S N
N
_Discard_top][T S S N
_Multiply][N
S N
N
_Jump_to_Label_LOOP][N
S S S S N
_Create_Label_ADD][T    S S S _Add][N
S N
N
_Jump_to_Label_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

-24 bytes after a comment of *@JoKing* suggesting `n%i > 0`. Although only `if(x < 0)` and `if(x == 0)` are available in Whitespace, simply checking `if(x*-1 < 0)` is basically the same as `if(x > 0)`.
An additional -25 bytes thanks to *@JoKing*.

**Explanation:**

Quote from the Scratch answer:

> At least it isn't `goto`s...

Did someone say `goto`? Whitespace has nothing else than `goto` to create both loops and if-statements. xD In addition it's a stack-based language, so I have to swap/discard/copy pretty often. And to top things off: Whitespace doesn't even have floating points and only integer-division, so I've used `n % i * -1 < 0` to exit the program if the integer cannot divide the current number.

*Pseudo-code:*

```
Integer n = STDIN as input
Integer i = 0
Label LOOP:
  Print n as number
  i = i + 1
  Integer t = i % 4
  If(t == 0):
    Jump to Label DIVIDE
  t = t - 1
  If(t == 0):
    Jump to Label MULTIPLY
  t = t - 1
  If(t == 0):
    Jump to Label ADD
  n = n - i
  Jump to Label LOOP
Label DIVIDE:
  n = n / i
  Integer m = n % i
  If(m == 0):
    Jump to Label LOOP
  Exit program
Label MULTIPLY:
  n = n * i
  Jump to Label LOOP
Label ADD:
  n = n + i
  Jump to Label LOOP

```
> 8 votes

# Answer
# JavaScript (V8), 52 bytes

Prints groups of 4 terms. Inspired by GB's Ruby answer.

```
n=>{for(k=0;n%1==0;n/=k+=3)print(n,n*=++k,n-~k,--n)}

```

Try it online!

---

# JavaScript (V8), 54 bytes

Prints the terms of the sequence.

```
n=>{for(k=0;n%1==0;n=eval(n+'*+-/'[k++&3]+k))print(n)}

```

Try it online!

---

# JavaScript (ES6),  ~~59~~  58 bytes

Returns an array.

```
f=(n,k)=>k&&(n=eval(n+'/*+-'[k&3]+k))%1?[]:[n,...f(n,-~k)]

```

Try it online!
> 7 votes

# Answer
# Piet, 297 190 144 codels (432 bytes)

Tried a new approach using a `pointer` command as switch(k mod 4) to unify the output code, resulting in a denser 10x19 code picture. Then I golfed that down by 1 row and 2 collumns to 8x18.

Here is a trace, to see how it works:

The first line pushes a 0 on the stack as starting index (since we can only `push` natural numbers, we push 2 ones and then substract), then reads the input as number.

The leftmost collumn has the shared code of duplicating the number and popping one into output, then moving the index on top of the stack, incrementing it and then duplicating it thrice. We then enter the pastel red r-shaped block through the dark cyan codel for a `pointer` command which gives us different paths for the remainder of our index mod 4.

Mod 1, we exit through the top to multiply. We first shuffle a copy of our index down for later, then perform the multiplication. After passing through the white for a noop, we enter the collumn above to fix the cc parity (it needs to be flipped an even number of times to keep the loop stable), followed by a `pointer (1)` from entering the magenta bar: It acts as a catch for our four paths and send us back into the loop.

Mod 2, we exit backwards to sum. The shape of the pastel code block means we exit a row above from where we entered, and we use the 3 we push onto the stack by exiting through the red codel to `pointer (3)` ourselves upwards. This collumns has the white space before the arithmetic and a slightly different order of pushing and switching cc, because otherwise we would have colour overlap with integer-valued codels in the neighbouring collumn.

Mod 3 send us downwards for subtraction. Same deal as multiplication, except we cross over the division path on the way up (As the cc has differing parity when entering the pastel green bar, the two executions exit that bar at different ends). While doing so, we pick up an unwanted `duplicate` command, so we `pop` it back off with the dark green codel before entering the cc correction and collection bar.

Mod 4, we go straight ahead to divide. Here, we first have to re-shuffle the stack more severely to get two pairs of n and a to perform operations on, because we need to test if it's integer. We do that my doing `mod` on the first pair, then `not` on the result, then use that for a `pointer` \- if it's not divisible, we keep going straight, which sends us with two `pointer` commands into the opposite corner into the inescapable block and thus ends program. Otherwise, we turn right and get a `divide` command from entering the magenta bar.

### Old Version

Very straightforward code: Pushes a 1 and the input on the stack, then loops through the four operations by: Shuffling the index on top of the stack, incrementing it by 1, duplicating it, shuffling one copy back down, performing the arithmetic operation, duplicating the number and popping one into output.

For division, which is the only one where the sequence can end, it creates a more complicated stack to first check if n mod index == 0, otherwise it enters the inescapable codel and terminates. Otherwise, it uses its second copy of i and n to perform the division.
> 6 votes

# Answer
# Perl 6, 44 bytes

```
{$_,{($_,<* + - />[$++%4]~++$).EVAL}...^*%1}

```

Try it online!

Anonymous code block that takes a number and returns a sequence. If we could skip the first element (which is always the same as the second element anyway), we could save 3 bytes by removing the `$_,`
> 5 votes

# Answer
# Python 3, 60 bytes

```
f=lambda n,i=1:[]if n%1else[n]+f([n/i,n*i,n+i,n-i][i%4],i+1)

```

Try it online!
> 5 votes

# Answer
# Ruby, ~~56 54~~ 52 bytes

```
f=->n,z=1{n%1>0?[]:[n,n*=z,n-~z,n-=1]+f[n/=z+3,z+4]}

```

Try it online!

After some (failed) attempt with `eval`, I found out that the happiest solution is building the array with 4 elements at once, at least in ruby.

Thanks to Arnauld for -2 bytes.
> 4 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~72~~, ~~70~~, 69 bytes

```
n=>{for(int i=1;n%1==0;n=new[]{n/i,n*i,n+i,n-i}[i++%4])Write(n+" ");}

```

Try it online!
> 4 votes

# Answer
# , ~~90 bytes, ~~87 bytes~~ ~~85 bytes~~ ~~80 bytes~~ 74~~ 73 bytes

A plain implementation of the rules:

```
a=scan();while(T<13)a=c(a,d<-a[T]*T,d+T+1,e<-d-1,e/((T<-T+4)-1));a[!a%%1]

```

Try it online!

with the `T<13` following from a deeper analysis of the puzzle. Indeed there are only three kinds of sequences: those of length 4, when a⁰ is not congruent to 1 modulo 8; those of length 12 when a⁰ is congruent to 21 modulo 32; and those of length 8 for the remaining cases.

An alternative code avoiding loops ends up being longer with 87 bytes:

```
`~`=rep;b=(scan()-1)*c(32~4,8,40~3,1,9~3)/32+c(1,1,3,0~3,6,-c(8,1,9,-71,17)/8);b[!b%%1]

```

Try it online!
> 4 votes

# Answer
# Haskell, ~~104~~ ~~86~~ 85 bytes

```
n#i=n:(cycle[(/),(*),(+),(-)]!!floor i)n i#(i+1)
takeWhile((==).ceiling<*>floor).(#1)

```

Try it online!

The `h=` can be omitted since it's only used for testing.

Ah, code golf, where a quadratic increase in time complexity is worth it for the reduction of one character.

# 104 bytes

```
f=flip
g x=scanl(f($))x.zipWith(f($))[1..].cycle$f<$>[(*),(+),(-),(/)]
takeWhile((==).ceiling<*>floor).g

```

Try it online!

I like this answer better, but alas it is longer.
> 3 votes

# Answer
# Japt, ~~25~~ 24 bytes

Another adaptation of GB's Ruby solution.

```
%1ª[UU*=°VU´ÒVU]cßU/=V±3

```

Try it

The main trick here is in the overloading of the `c` method for arrays. Pass it another array as an argument and it concatenates it to the original array. Pass it a number as an argument, as happens on the last recursive call, and it flattens the original array by that many levels - `1` in this case, after rounding. But, as the array is only ever one level deep, flattening it has no effect.

```
%1ª[UU*=°VU´ÒVU]cßU/=V±3     :Implicit input of integer U
%1                           :U modulo 1
  ª                          :Logical OR with
   [                         :Construct and array containing
    U                        :  U
     U*=                     :  U multiplied by
        °V                   :    V (initially 0) prefix incremented
          U´                 :  The new value of U, postfix decremented
            ÒV               :    Subtract the bitwise negation of V
              U              :  The now-decrmented U
               ]             :End array
                c            :Concatenate, or flatten by
                 ß           :  Recursive call to the programme with argument
                  U/=        :    U divided by
                     V±3     :      V incremented by 3

```
> 3 votes

# Answer
# Husk, 16 bytes

```
↑¦1G`I⁰zI¢ë*+-/N

```

Try it online!

## Explanation

```
↑¦1G`I⁰zI¢ë*+-/N   Input is a number n, accessible via ⁰.
          ë*+-/    Four-element list containing the functions *, +, - and /.
         ¢         Cycle infinitely.
       z       N   Zip with the list [1,2,3,4,5,..
        I          using the identity function (which works as function application since e.g. I+2 == (I+)2 == +2).
   G               Cumulative reduce from the left
    `I             using flipped identity function
      ⁰            with initial value n.
                   This results in [n, n*1, (n*1)+2, ((n*1)+2)-3, ..
↑                  Take the maximal prefix of elements
 ¦1                that are divisible by 1, or in other words are integers.

```
> 3 votes

# Answer
# Java 8, 84 bytes

```
n->{for(int i=1;n%1==0;n=new float[]{n/i,n*i,n+i,n-i}[i++%4])System.out.println(n);}

```

Try it online.

Creating an array with all four values is inspired by *@GB*'s Ruby answer, although I now notice that using a ternary if-statement is the same amount of bytes:

```
n->{for(int i=0;n%1==0;n=++i%4<1?n/i:i%4<2?n*i:i%4<3?n+i:n-i)System.out.println(n);}

```

Try it online.
> 2 votes

# Answer
# Perl 5, 53 bytes

```
@a=qw(/ * + -);say,eval"\$_$a[++$i%4]=$i"while$_==int

```

Try it online!
> 2 votes

# Answer
# Red, 102 bytes

```
func[n][k: m: 0 until[foreach o[* + - /][print n t: n
n: do reduce[n o m: m + 1]]k: k + 1 t % m <> 0]]

```

Try it online!
> 2 votes

# Answer
# AWK, 57 bytes

```
{n=$1;for(k=1;n%1==0;n/=k++)print n,n*=k++,n+=k++,n-=k++}

```

Try it online!
> 2 votes

# Answer
# Rutger, 310 bytes

```
n=e=$Input;
a=0;
w=While[{m=Modulo[$e];Not[m[1]];}];
w=w[{f=For[4];f=f[@x];f=f[{Print[$e];q=Equal[$x];i=If[{q[1];}];i=i[{k=Times[$e];}];Do[$i];i=If[{q[2];}];i=i[{k=Add[$e];}];Do[$i];i=If[{q[3];}];i=i[{k=Subtract[$e];}];Do[$i];i=If[{q[4];}];i=i[{k=Divide[$e];}];Do[$i];e=k[a=Increment[$a]];}];Do[$f];}];
Do[$w];

```

Try it online!

It's about time I used Rutger again. Unfortunately, it may not be the best language for the task, as it has no form of `eval`, forcing me to use four if statements

## How it works

### How Rutger works

A brief foreword on how the language works: Everything is either an assignment or a function, and every function takes exactly one argument. For operations that require more than one argument (e.g. multiplication), the first call returns a *partial function*, that, when called again with the second argument, returns the expected result. For example:

```
left = Times[5];
Print[left[6]];

```

will print out 30: Try it online!. While usually this is longer than the usual alternative, it can at times save bytes, if a function is called repeatedly with one constant argument, and one changing argument, for instance when printing out times tables.

This one argument rule applies to everything that isn't a constant or a variable, including loops and conditionals. However, loops and conditionals (`For`, `Each`, `While`, `DoWhile`, `If` and `IfElse`) are *doable*, meaning that in order to actually run them, the `Do` function must be called (see the last line in the answer). Again, this can save bytes when repeatedly running the same loop, or allow you to run arbitrary code between the definition and running of loops.

Finally, there are three ways of referring to variables, all of which are used in this program. The first is *direct referencing*, where the variable name is prefixed with a `$` symbol. This accesses the value of the variable directly and returns it. The second is *functional referencing*, which doesn't have a prefixing character. This allows the code to distinguish between (potentially partial) functions assigned to variables, and actual variables containing a specific value. Finally, *indirect referencing*, prefixed with an `@` symbol, creates a variable (if it doesn't already exist) and returns the variable object within a given scope. This allows you to create a loop variable (e.g. `i` in `for i in range(...)`).

### How the actual solution works

Here is the ungolfed code:

```
n = elem = $Input;
var = 0;
while = While[{
	mod = Modulo[$elem];
	Not[mod[1]];
}];
while = while[{
for = For[4];
for = for[@index];
for = for[{
	Print[$elem];
	equal = Equal[$index];

	if = If[{ equal[1]; }];
	if = if[{ func = Times[$elem]; }];
	Do[$if];

	if = If[{ equal[2];}];
	if = if[{ func = Add[$elem];}];
	Do[$if];

	if = If[{ equal[3];}];
	if = if[{ func = Subtract[$elem];}];
	Do[$if];

	if=If[{ equal[4];}];
	if=if[{ func = Divide[$elem];}];
	Do[$if];

	elem = func[var = Increment[$var]];
	}];
	Do[$for];
}];
Do[$while];

```

Try it online!

As you can see, it starts by assigning the three variables `n`, `e` and `a`, which represent the input, the changing element in the sequence, and the modification number for each new element respectively. We then create a while loop:

```
w=While[{m=Modulo[$e];Not[m[1]];}];

```

The braces (`{` and `}`) define a *block* of code, where the final statement in the block is the condition for the while loop. In this case, we start by defining a partial modulo function, which will take in a second argument `m`, and return `e % m`. We then call this partial function with \\$1\\$ as its second argument, returning \\$0\\$ for integers and a non-zero integer for floats. We then calculate the logical not of this, mapping \\$0 \to 1\\$ and \\$n \to 0, n \ne 0\\$.

Next we come to the absolute monstrosity consisting of the while loop's body:

```
w=w[{f=For[4];f=f[@x];f=f[{Print[$e];q=Equal[$x];i=If[{q[1];}];i=i[{k=Times[$e];}];Do[$i];i=If[{q[2];}];i=i[{k=Add[$e];}];Do[$i];i=If[{q[3];}];i=i[{k=Subtract[$e];}];Do[$i];i=If[{q[4];}];i=i[{k=Divide[$e];}];Do[$i];e=k[a=Increment[$a]];}];Do[$f];}];

```

The primary part of this loop is a for loop, that iterates \\$4\\$ times each iteration of the while loop, has an iteration variable of `x` and consists of:

```
Print[$e];
q=Equal[$x];
i=If[{q[1];}];i=i[{k=Times[$e]    ;}];Do[$i];
i=If[{q[2];}];i=i[{k=Add[$e]      ;}];Do[$i];
i=If[{q[3];}];i=i[{k=Subtract[$e] ;}];Do[$i];
i=If[{q[4];}];i=i[{k=Divide[$e]   ;}];Do[$i];
e=k[a=Increment[$a]];

```

The first statement prints out each iteration of the sequence before modifying it. We then create a partial function to check equality with the loop variable `x`, and encounter four if statements. Each statement checks if `x` is equal to 1, 2, 3 or 4 respectively, and then assigns `k` to each function in `*`, `+`, `-` and `/`, then makes it into a partial function with `e` as its argument. Finally, we assign `e` to `k` run with `a` as its second argument, and increment `a`.
> 2 votes

# Answer
# Ruby, 52 bytes

```
->n{i=0.0;n=[p(n)/i+=1,n*i,n+i,n-i][i%4]until 0<n%1}

```

Try it online!
> 2 votes

# Answer
# dzaima/APL, ~~34~~ 33 bytes

```
⌽1↓{⍵,⍨⊃⍵(⍎⊃'÷×+-'⌽⍨≢⍵)≢⍵}⍣{⍵≢⌊⍵}

```

Try it online!

-1 thanks to ngn
> 2 votes

# Answer
# TI BASIC, 68 Bytes

```
1→A
DelVar L1Prompt N
Repeat fPart(N
N→L1(A
NA-1→O
augment(L1,{NA,Ans+A+2,Ans→L1
O/(A+3→N
A+4→A
End
L1

```

We set up a counter in A and clear L1 so we can use it to track the sequence. We then repeat until the division step causes a fraction. Inside the loop we first store N to the list. Storing to one element past the end of a list or an empty list creates that element, so this one store both adds the result of the division when it doesn't cause a fraction, and initializes the list during the first pass. We then use augment to append the next 3 terms of the sequence. The math works out a few bytes smaller by calculating term A4k+3 in variable O and then basing A4k+2 and A4k+4 off O. Then we do the division separately to reset N for the repeat check and add 4 to A.
> 2 votes

# Answer
# Charcoal, 29 bytes

```
ＮθＷ¬﹪θ¹«Ｉθ⸿≔§⟦∕θⅉ×θⅉ⁺θⅉ⁻θⅉ⟧ⅉθ

```

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

```
Ｎθ

```

Input the initial value.

```
Ｗ¬﹪θ¹«

```

Repeat until the value is no longer an integer.

```
Ｉθ⸿

```

Print the value on its own line.

```
≔§⟦∕θⅉ×θⅉ⁺θⅉ⁻θⅉ⟧ⅉθ

```

Calculate the four available arithmetic operations and select the correct one depending on the current output line number.
> 1 votes

# Answer
# C (clang), 80 bytes

```
i;f(n){for(i=0;~i;n=++i%4?i%4-1?i%4-2?n-i:n+i:n*i:n%i?i=-1:n/i)printf("%d ",n);}

```

Try it online!

```
A golfed switch statement.

```

Thanks to many @ceilingcat improvements.
> 1 votes

# Answer
# Python 3, ~~78~~ 76 bytes

```
f=lambda n:n[-1]%1and n[:-1]or f(n+[eval(f"n[-1]{'/*+-'[len(n)%4]}len(n)")])

```

Try it online!

Takes input as a list of 1 item and recursively appends the next item of the sequence until it's a non-integer.

In the case that taking input as a list is not allowed, here is a very quickly patched version which takes input as an int.

# Input as an integer, 102 bytes

```
f=lambda n:type(n)==int and f([n])or n[-1]%1and n[:-1]or f(n+[eval(f"n[-1]{'/*+-'[len(n)%4]}len(n)")])

```

Try it online!

+2 bytes thanks to me forgetting to name the recursive function...
-4 bytes thanks to Jitse
> 1 votes

# Answer
# Twig, 164 bytes

Okay, this was actually horribly horrible to write.

Limitations:

* No `returns`! You either output or don't output
* No `while` loops. You **must** use recursion or nothing
* No easy way to output! You have to repeat the output everytime
* You can't give variables a value without using the `set` tag
* No easy way to get out of a loop. There's no `break`, `continue`, `goto` or similar. This makes a loop impossible to use.
* There is only 1 loop: `for ... in ....`, and it loops over all the elements in an array, with no way to stop.

All those made the code massive!
Hey, I even made it longer than the Java answer!
It's as long as @Arnauld's JavaScript answer! ... With all 3 alternatives combined.

**Here's the code:**

```
{%macro a(b,n=1)%}{{n<2?b}}{%set b=b*n%},{{b}}{%set b=b+n+1%},{{b}}{%set b=b-(n+2)%},{{b}}{%set b=b/(n+3)%}{%if(b//1)==b%},{{b~_self.a(b,n+4)}}{%endif%}{%endmacro%}

```

You can try it on https://twigfiddle.com/zw5zls

---

## How to use:

Simply import the file and call the first macro.

```
{% import 'file.twig' as a %}

{{ a.a(21) }} {# 21,21,23,20,5,25,31,24,3,27,37,26 #}

```

To have an usable array, you can do `a.a(21)|split(',')`.

---

## Ungolfed:

```
{% macro calc(number, index = 1) %}
    {% if index < 2 %}
        {{ number }}
    {% endif %}

    {% set number = number * index %},{{ number }}
    {% set number = number + index + 1 %},{{ number }}
    {% set number = number - (index + 2) %},{{ number }}
    {% set number = number / (index + 3) %}

    {#
        verifies if it is an integer.
        this is done with an integer division with 1 and compare with itself
        if both values are the same, the number is an integer
        otherwise, it is a floating-point number
    #}
    {% if (number // 1) == number %}
        ,{{ number ~ _self.calc(number, index + 4) }}
    {% endif %}
{% endmacro %}

```

Should be easy to read.
This ungolfed answer will NOT give the correct output, as it will throw random whitespaces.
It exists merely to be humanly readable.
> 1 votes

# Answer
# Jelly, 14 bytes

```
×+_÷4ƭ‘ɼ$ḞƑÐ¿Ṗ

```

A full program\* that accepts an integer and prints the resulting sequence.

**Try it online!**

### How?

```
×+_÷4ƭ‘ɼ$ḞƑÐ¿Ṗ - Main Link: integer, n
           Ð¿  - collect while X, initially n, is:
          Ƒ    - ...invariant under
         Ḟ     -     floor to the nearest integer
        $      - ...last two links as a monad - f(X):
       ɼ       -   apply to the register (initially zero) and yield:
      ‘        -     increment (i.e. get the next right operand)
    4ƭ         -   calling these four links in turn:
×              -     multiply
 +             -     add
  _            -     subtract
   ÷           -     divide
             Ṗ - pop off the trailing, non-integer
               - implicit print

```

* Note: this is not a reusable Link since the tie quick, `ƭ`, does not reset between calls to a Link.
> 0 votes

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