title: Draw the Devil's Staircase

text:
# Question
Title: Draw the Devil's Staircase
The Devil's Staircase is a fractal-like function related to the Cantor set.

Your task is to replicate this funky function — in ASCII art!

# Input

A single integer `n >= 0`, indicating the size of the output. Input may be given via STDIN, function argument or command-line argument.

# Output

The ASCII-art rendition of the Devil's staircase at size `n`, either returned as a string or printed to STDOUT. Trailing spaces at the end of each row are okay, but leading spaces are not. You may optionally print a single trailing newline.

For size `0`, the output is just:

```
x

```

(If you wish, you may use any other printable ASCII character other than space, in place of `x`.)

For size `n > 0`, we:

* Take the output of size `n-1` and stretch each row by a factor of three
* Riffle between rows of single `x`s
* Shift the rows rightward so that there is exactly one `x` in each column, and the position of the first `x` are minimal while decreasing with the rows

For example, the output for `n = 1` is:

```
    x
 xxx
x

```

To get the output for `n = 2`, we stretch each row by a factor of three:

```
            xxx
   xxxxxxxxx
xxx

```

Riffle between rows of single `x`'s:

```
x
            xxx
x
   xxxxxxxxx
x
xxx
x

```

Shift rightward:

```
                  x
               xxx
              x
     xxxxxxxxx
    x
 xxx
x

```

As another example, here is `n = 3`.

# Scoring

This is code-golf, so the solution in the fewest bytes wins.

# Answer
## Pyth, 30

```
jb_u+G+*leGd*HNu+N+^3hTNUQ]1]k

```

This is a program that takes input from STDIN and uses grc's method of finding the Cantor set. Uses the " character to display the curve.

Try it online here.

Explanation:

I will explain the code in two parts, first, the cantor set generation:

```
u+N+^3hTNUQ]1
u        UQ]1         : reduce( ... , over range(input), starting with [1])
 +N                   : lambda N,T: N + ...
   +^3hTN             : 3 ** (T+1) + N   (int + list in pyth is interpreted as [int] + list)

```

And the output formatting:

```
jb_u+G+*leGd*HN    ]k
jb_                    : "\n".join(reversed(...)
   u               ]k  : reduce(lambda G,H: ... , over cantor set, starting with [""])
    +G+*leGd           : G + len(G[-1]) * " " + ...
            *HN        : H * '"'

```

Note that in pyth N = '"' by default.
> 7 votes

# Answer
## J (~~73~~ ~~68~~ ~~58~~ ~~41~~ ~~39~~ ~~38~~ ~~35~~ 34 characters)

After thinking about the problem for some time, I found an entirely different way to generate the Devil's Staircase pattern. The old answer including its explanation has been removed, you can look into the revisions of this answer to figure out how it was.

This answer returns an array of blanks and sharps, representing the devil's staircase.

```
' #'{~1(]|.@=@#~[:,3^q:)2}.@i.@^>:

```

Here is the answer split into its two parts in explicit notation:

```
f =: 3 : '|. = (, 3 ^ 1 q: y) # y'
g =: 3 : '(f }. i. 2 ^ >: y) { '' #'''

```

## Explanation

The approach is a bit different, so observe and be amazed.

1. `>: 3` – three incremented, that is,

```
4

```
2. `2 ^ >: 3` – two to the power of three incremented, that is,

```
16

```
3. `i. 2 ^ >: 3` – the first `2 ^ >: 3` integers, that is,

```
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

```
4. `}. i. 2 ^ 4` – the first `2 ^ >: 3` integers, beheaded, that is,

```
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

```

Let's call this sequence `s`; we enter `f` now.
5. `1 q: s` – the exponents of 2 in the prime decomposition of each item of `s`. In general, `x q: y` yields a table of the exponents for the first `x` primes in the prime decomposition of `y`. This yields:

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

```
6. `3 ^ 1 q: s` – three to the power of these exponents, that is,

```
 1
 3
 1
 9
 1
 3
 1
27
 1
 3
 1
 9
 1
 3
 1

```
7. `, 3 ^ 1 q: s` – the ravel (that is, the argument with it's structure collapsed into a vector) of the previous result. This is needed because `q:` introduces an unwanted trailing axis. This yields

```
 1 3 1 9 1 3 1 27 1 3 1 9 1 3 1

```
8. `(, 3 ^ 1 q: s) # s` – each item of `s` replicated as often as the corresponding item in the previous result, that is,

```
1 2 2 2 3 4 4 4 4 4 4 4 4 4 5 6 6 6 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 9 10 10 10 11 12 12 12 12 12 12 12 12 12 13 14 14 14 15

```
9. `= (, 3 ^ 1 q: s) # s` – the self classification of the previous result, this is, a matrix where each row represents one of the unique items of the argument, each column represents the corresponding item of the argument and each cell represents whether the items of row and column are equal, that is,

```
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1

```
10. `|. = (, 3 ^ 1 q: s) # s` – the previous result flipped along the vertical axis.
11. `(|. = (, 3 ^ 1 q: s) # s) { ' #'` – the items of the previous result used as indices into the array `' #'`, so `0` is replaced by  and `1` is replaced by `#`, that is,

```
                                                                #
                                                             ###
                                                            #
                                                   #########
                                                  #
                                               ###
                                              #
                   ###########################
                  #
               ###
              #
     #########
    #
 ###
#

```

the result we want.
> 36 votes

# Answer
# Hexagony, 217 bytes

This was immensely fun. Thank you for posting this challenge.

Full disclosure: The language (Hexagony) did not exist at the time this challenge was posted. However, I did not invent it, and the language was not designed for this challenge (or any other specific challenge).

```
){_2"_{\"{{""}"{'2//_.\><*\"\/_><[\]/3\'\_;|#__/(\2\'3_'}(#:|{$#{>_\//(#={/;01*&"\\_|[##={|}$_#></)]$_##|){*_.>.(/?#//~-="{}<_"=#/\}.>"%<.{#{x\"<#_/=&{./1#_#>__<_'\/"#|@_|/{=/'|\"".{/>}]#]>(_<\'{\&#|>=&{{(\=/\{*'"]<$_

```

Laid out hexagonally:

```
        ) { _ 2 " _ { \ "
       { { " " } " { ' 2 /
      / _ . \ > < * \ " \ /
     _ > < [ \ ] / 3 \ ' \ _
    ; | # _ _ / ( \ 2 \ ' 3 _
   ' } ( # : | { $ # { > _ \ /
  / ( # = { / ; 0 1 * & " \ \ _
 | [ # # = { | } $ _ # > < / ) ]
$ _ # # | ) { * _ . > . ( / ? # /
 / ~ - = " { } < _ " = # / \ } .
  > " % < . { # { x \ " < # _ /
   = & { . / 1 # _ # > _ _ < _
    ' \ / " # | @ _ | / { = /
     ' | \ " " . { / > } ] #
      ] > ( _ < \ ' { \ & #
       | > = & { { ( \ = /
        \ { * ' " ] < $ _

```

The program does not actually use the `#` instruction, so I used that character to show which cells are genuinely unused.

How does this program work? That depends. Do you want the short version, or the long?

# Short explanation

To illustrate what I mean by “line” and “segment” in the following explanation, consider this dissection of the intended output:

```
segments →
 │   │ │         │ │   │x   lines
─┼───┼─┼─────────┼─┼───┼─     ↓
 │   │ │         │ │xxx│
─┼───┼─┼─────────┼─┼───┘
 │   │ │         │x│
─┼───┼─┼─────────┼─┘
 │   │ │xxxxxxxxx│
─┼───┼─┼─────────┘
 │   │x│
─┼───┼─┘
 │xxx│
─┼───┘
x│

```

With that explained, the program corresponds to the following pseudocode:

```
n = get integer from stdin

# Calculate the number of lines we need to output.
line = pow(2, n+1)

while line > 0:
    line = line - 1

    # For all segments except the last, the character to use is spaces.
    ch = ' ' (space, ASCII 32)

    # The number of segments in each line is
    # equal to the line number, counting down.
    seg = line

    while seg > 0:
        seg = seg - 1

        # For the last segment, use x’s.
        if seg = 0:
            ch = 'x' (ASCII 120)

        # Calculate the actual segment number, where the leftmost is 1
        n = line - seg

        # Output the segment
        i = pow(3, number of times n can be divided by 2)
        i times: output ch

    output '\n' (newline, ASCII 10)

end program

```

# Long explanation

Please refer to this color-coded code path diagram.

Execution starts in the top left corner. The sequence of instructions `){2'"''3''"2}?)` is executed (plus a few redundant cancelations, like `"{` etc.) by pursuing a fairly convoluted path. We start with Instruction Pointer #0, highlighted in crimson. Halfway through, we switch to #1, starting in the top-right corner and painted in forest green. When IP #2 starts out in cornflower blue (middle right), the memory layout is this:

Throughout the entire program, the edges labeled **2a** and **2b** will always have the value `2` (we use them to calculate 2ⁿ⁺¹ and to divide by 2, respectively) and the edge labeled **3** will always be `3` (we use that to calculate 3ⁱ).

We get to business as we enter our first loop, highlighted in cornflower blue. This loop executes the instructions `(}*{=&}{=` to calculate the value 2ⁿ⁺¹. When the loop exits, the saddle brown path is taken, which takes us to Instruction Pointer #3. This IP merely dabbles along the bottom edge westwards in goldenrod yellow and soon passes control to IP #4.

The fuchsia path indicates how IP #4, starting in the bottom left, proceeds swiftly to decrement **line**, set **ch** to `32` (the space character) and **seg** to (the new value of) **line**. It is due to the early decrement that we actually start with 2ⁿ⁺¹−1 and eventually experience a last iteration with the value 0. We then enter the first *nested* loop.

We turn our attention to the branching indigo, where, after a brief decrement of **seg**, we see **ch** updated to `x` only if **seg** is now zero. Afterwards, **n** is set to **line − seg** to determine the actual number of the segment we’re in. Immediately we enter another loop, this time in the fair color of tomato.

Here, we figure out how many times **n** (the current segment number) can be divided by 2. For as long as the modulo gives us zero, we increment **i** and divide **n** by 2. When we are satisfied **n** is no longer thusly divisible, we branch into the slate gray, which contains two loops: first it raises 3 to the power of the **i** we calculated, and then it outputs **ch** that many times. Observe that the first of these loops contains a `[` instruction, which switches control to IP #3 — the one that was only taking baby steps along the bottom edge earlier. The body of the loop (multiplying by 3 and decrementing) is executed by a lonely IP #3, imprisoned in an endless dark olive green cycle along the bottom edge of the code. Similarly, the second of these slate gray loops contains a `]` instruction, which activates IP #5 to output **ch** and decrement, shown here in dark Indian red. In both cases, those Instruction Pointers trapped in servitude obediently execute one iteration at a time and yield control back to IP #4, only to bide the moment for their service to be called upon once again. The slate gray, meanwhile, rejoins its fuchsia and indigo brethren.

As **seg** inevitably reaches zero, the indigo loop exits into the lawn green path, which merely outputs the newline character and promptly merges back into the fuchsia to continue the **line** loop. Beyond the final iteration of the **line** loop lies the short sable ebon path of ultimate program termination.
> 30 votes

# Answer
# Python 2, 78 bytes

```
L=[1]
i=3
exec"L+=[i]+L;i*=3;"*input()
while L:x=L.pop();print' '*sum(L)+'x'*x

```

Starting off with the list `L=[1]`, we duplicate it and insert the next power of 3 in the middle, resulting in `[1, 3, 1]`. This is repeated `n` times to give us the row lengths for the Devil's staircase. Then we print each row padded with spaces.
> 23 votes

# Answer
# APL, 38

```
⊖↑'x'/⍨¨D,⍨¨0,¯1↓-+\D←{1,⍨∊1,⍪3×⍵}⍣⎕,1

```

Example:

```
      ⊖↑'x'/⍨¨D,⍨¨0,¯1↓-+\D←{1,⍨∊1,⍪3×⍵}⍣⎕,1
⎕:
      2
                  x
               xxx
              x
     xxxxxxxxx
    x
 xxx
x

```

Explanation:

```
⊖↑'x'/⍨¨D,⍨¨0,¯1↓-+\D←{1,⍨∊1,⍪3×⍵}⍣⎕,1

                                     ⎕       ⍝ read a number from the keyboard
                       {           }⍣ ,1      ⍝ apply this function N times to [1]
                               3×⍵           ⍝ multiply each value by 3
                           ∊1,⍪               ⍝ add an 1 in front of each value
                        1,⍨                  ⍝ add an 1 to the end
                     D←                      ⍝ store values in D (lengths of rows)
                   +\                        ⍝ get running sum of D
                  -                          ⍝ negate (negative values on / give spaces)
             0,¯1↓                           ⍝ remove last item and add a 0 to the beginning
                                             ⍝ (each row needs offset of total length of preceding rows)
         D,⍨¨                                ⍝ join each offset with each row length
   'x'/⍨¨                                    ⍝ get the right number of x-es and spaces for each row
 ↑                                           ⍝ make a matrix out of the rows
⊖                                            ⍝ mirror horizontally

```
> 20 votes

# Answer
# GNU sed, 142

Not the shortest answer, but its sed!:

```
s/$/:/
:l
s/x/xxx/g
s/:/:x:/g
tb
:b
s/^1//
tl
s/:x/X/g
s/^/:/
:m
s/.*:([Xx]+)Xx*:$/&\1:/
tm
:n
s/([ :])[Xx](x*Xx*)/\1 \2/g
tn
s/:/\n/g
s/X/x/g

```

Because this is sed (no native arithmetic), I'm taking liberties with the rule *"A single integer n \>= 0, indicating the size of the output"*. In this case the input integer must be a string of `1`s, whose length is n. I think this is *"indicating"* the size of the output, even though it is not a direct numerical equivalent to n. Thus for n=2, the input string will be `11`:

```
$ echo 11 | sed -rf devils-staircase.sed

                  x
               xxx
              x
     xxxxxxxxx
    x
 xxx
x

$

```

This appears to complete with exponential time complexity of O(cn), where c is about 17. n=8 took about 45 minutes for me.

---

Alternatively if it is required that n is entered numerically exactly, then we can do this:

### sed, 274 bytes

```
s/[0-9]/<&/g
s/9/8Z/g
s/8/7Z/g
s/7/6Z/g
s/6/5Z/g
s/5/4Z/g
s/4/3Z/g
s/3/2Z/g
s/2/1Z/g
s/1/Z/g
s/0//g
:t
s/Z</<ZZZZZZZZZZ/g
tt
s/<//g
s/$/:/
:l
s/x/xxx/g
s/:/:x:/g
tb
:b
s/^Z//
tl
s/:x/X/g
s/^/:/
:m
s/.*:([Xx]+)Xx*:$/&\1:/
tm
:n
s/([ :])[Xx](x*Xx*)/\1 \2/g
tn
s/:/\n/g
s/X/x/g

```

### Output:

```
$ echo 2 | sed -rf devils-staircase.sed

                  x
               xxx
              x
     xxxxxxxxx
    x
 xxx
x

$

```
> 14 votes

# Answer
# Python 2, 81

```
def f(n,i=1,s=0):
 if i<2<<n:q=3**len(bin(i&-i))/27;f(n,i+1,s+q);print' '*s+'x'*q

```

**Program version (88)**

```
def f(n,s=0):
 if n:q=3**len(bin(n&-n))/27;f(n-1,s+q);print' '*s+'x'*q
f((2<<input())-1)

```

The number of x's in the `n`th 1-indexed row is 3 to the power of (the index of the first set bit in `n`, starting from the lsb).
> 8 votes

# Answer
# Python 2, 74

```
def f(n,s=0):
 if~n:B=3**n;A=s+B-2**n;f(n-1,A+B);print' '*A+'x'*B;f(n-1,s)

```

A recursive approach. The size-$n$ devil's staircase is split into three parts

* The left recursive branch, a staircase of size `n-1`, whose length is `3**n - 2**n`
* The center line of `x`', of length `3**n`
* The right recursive branch, a staircase of size `n-1`, whose length is `3**n - 2**n`

Note that the total length of the three parts is `3*(3**n) - 2*(2**n)` or `3**(n+1) - 2**(n+1)`, which confirms the induction.

The optional variable `s` stores the offset of the current parts we're printing. We first recurse down to the left branch with larger offset, then print the center line, then do the right branch at the current offset.
> 8 votes

# Answer
# CJam, ~~36~~ ~~35~~ 33 bytes

Here is another CJam approach (I haven't looked at Optimizer's code, so I don't know if it's actually much different):

```
L0sl~{{3*0s}%0s\+}*{1$,S*\+}%W%N*

```

This uses `0` for the curve. Alternatively, (using grc's trick)

```
LLl~){3\#a1$++}/{1$,S*\'x*+}%W%N*

```

which uses `x`.

Test it here.

## Explanation

The basic idea is to first form an array with the rows, like

```
["0" "000" "0" "000000000" "0" "000" "0"]

```

And then to go through this list, prepending the right amount of spaces.

```
L0sl~{{3*0s}%0s\+}*{1$,S*\+}%W%N*
L                                 "Push an empty string for later.";
 0s                               "Push the array containing '0. This is the base case.";
   l~                             "Read and evaluate input.";
     {           }*               "Repeat the block that many times.";
      {    }%                     "Map this block onto the array.";
       3*                         "Triple the current string.";
         0s                       "Push a new zero string.";
             0s\+                 "Prepend another zero string.";
                   {       }%     "Map this block onto the result.";
                    1$            "Copy the last line.";
                      ,S*         "Get its length and make a string with that many spaces.";
                         \+       "Prepend the spaces to the current row.";
                             W%   "Reverse the rows.";
                               N* "Join them with newlines.";

```

The other version works similarly, but creates an array of lengths, like

```
[1 3 1 9 1 3 1]

```

And then turns that into strings of `x`s in the final map.
> 6 votes

# Answer
## Dyalog APL, 34 characters

Using the approach by grc. Draws the staircase with  (domino) characters and takes input from stdin. This solution assumes `⎕IO←0`.

```
' ⌹'[(∪∘.=⊖){⍵/⍳≢⍵}⊃(⊢,,)/3*⌽⍳1+⎕]

```
* – take input from stdin.
* `⌽⍳1+⎕` – the sequence of the numbers from  down to 0. (e.g. `3 2 1 0`)
* `3*⌽⍳1+⎕` – three to the power of that (e.g. `27 9 3 1`)
* `(⊢,,)/3*⌽⍳1+⎕` – the previous result folded from the right by the tacit function `⊢,,` which is equal to the dfn `{⍵,⍺,⍵}` yielding the step lengths of the devil's staircase as per grc's approach.
* `{⍵/⍳≢⍵}⊃(⊢,,)/3*⌽⍳1+⎕` the step lengths converted into steps.
* `(∪∘.=⊖){⍵/⍳≢⍵}⊃(⊢,,)/3*⌽⍳1+⎕` that self-classified, as in my J solution. Notice that  already flips the result correctly.
* `' ⌹'[(∪∘.=⊖){⍵/⍳≢⍵}⊃(⊢,,)/3*⌽⍳1+⎕]` the numbers replaced by blanks and dominoes.
> 6 votes

# Answer
# Ruby, 99

A different answer to my other one, inspired by FUZxxl's answer

FUZxxl notes that the numbers of x's correspond to the number of factors of 2 of the index. for example for n=2 we have the following factorization:

```
1 =1
2 =1 * 2
3 =3
4 =1 * 2 * 2
5 =5
6 =3 * 2
7 =7

```

I use a rather more straightforward way of extracting these powers of 2: `i=m&-m` which yields the sequence `1 2 1 4 1 2 1` etc. This works as follows:

`m-1` is the same as `m`in its most significant bits, but the least significant 1's bit becomes a zero, and all the zeros to the right become 1's.

To be able to AND this with the original, we need to flip the bits. There are various ways of doing this. One way is to subtract it from `-1`.

The overall formula is then `m& (-1 -(m-1))` which simplifies to `m&(-m)`

Example:

```
          100   01100100
100-1=     99   01100011
-1-99=   -100   10011100
100&-100=   4   00000100

```

Here's the code: newlines are counted, indents are unnecessary and therefore not counted, as my other answer. It's slightly longer than my other answer due to the clumsy conversion from base 2: `1 2 1 4 1 2 1 etc` to base 3: `1 3 1 9 1 3 1 etc` (is there a way to avoid that `Math::` ?)

```
def s(n)
  a=[]
  t=0
  1.upto(2*2**n-1){|m|i=3**Math::log(m&-m,2)
    a.unshift" "*t+"x"*i
    t+=i}
  puts a
end

```
> 4 votes

# Answer
## Haskell, 99 characters

```
d=q.((iterate((1:).(>>=(:[1]).(*3)))[1])!!)
q[]=[];q(a:r)=sum r&' '++a&'x'++'\n':q r
(&)=replicate

```

The function is `d`:

```
λ: putStr $ d 3
                                                                x
                                                             xxx
                                                            x
                                                   xxxxxxxxx
                                                  x
                                               xxx
                                              x
                   xxxxxxxxxxxxxxxxxxxxxxxxxxx
                  x
               xxx
              x
     xxxxxxxxx
    x
 xxx
x

```
> 4 votes

# Answer
## PHP - 137 bytes

```
function f($n){for($a=[];$i<=$n;array_push($a,3**$i++,...$a))$r=str_repeat;foreach($a as$v){$o=$r(' ',$s).$r(x,$v)."
$o";$s+=$v;}echo$o;}

```

I'm using here the same trick as grc. Here is the ungolfed version:

```
function staircase($n)
{
    $lengthsList = [];
    for ($i = 0; $i <= $n; ++$i) {
        array_push($lengthsList, 3 ** $i, ...$lengthsList);
    }

    $output = '';
    $cumulatedLength = 0;
    foreach ($lengthsList as $length)
    {
        $output = str_repeat(' ', $cumulatedLength) . str_repeat('x', $length) . "\n" . $output;
        $cumulatedLength += $length;
    }

    echo $output;
}

```
> 3 votes

# Answer
# Ruby, ~~140~~ 99

My second ever Ruby code, and my first nontrivial use of the language. Suggestions are most welcome. Byte count excludes leading spaces for indents, but includes newlines (it seems most of the newlines cannot be deleted unless they are replaced by a space at least.)

Input is by function call. Output is an array of strings, which ruby conveniently dumps to stdout as a newline-separated list with a single `puts`.

The algorithm is simply `new iteration` = `previous iteration` \+ `extra row of n**3 x's` \+ `previous iteration`. However there is ~~a lot~~ *a fair amount* of code just to get the leading spaces in the output right.

```
def s(n)
  a=["x"]
  1.upto(n){|m|t=" "*a[0].length
    a=a.map{|i|t+" "*3**m+i}+[t+"x"*3**m]+a}
  puts a
end

```

# Edit: Ruby, 97

This uses the similar but different approach of building a numeric table of all the numbers of x's required in array `a` in the manner described above, but then building a table of strings afterwards. The table of strings is built backwards in array `c` using the rather oddly named `unshift` method to prepend to the existing array.

Currently this approach is looking better - but only by 2 bytes :-)

```
def s(n)
  a=c=[]
  (n+1).times{|m|a=a+[3**m]+a}
  t=0
  a.each{|i|c.unshift" "*t+"x"*i
    t+=i}
  puts c
end

```
> 3 votes

# Answer
## C, 165

```
#define W while
f(n){int i=n+1,j=1<<i,k=1,l,r,s,t;W(i--)k*=3;l=k-j;W(--j){r=j,s=1;W(!(r%2))r/=2,s*=3;l-=s;t=l;W(t--)putchar(32);W(++t<s)putchar(88);putchar('\n');}}

```

Here's the same code unpacked and slightly cleaned up:

```
int f(int n) {
    int i=n+1, j=1<<i, k=1;
    while (i--) k*=3;
    int l=k-j;
    while (--j) {
        int r=j,s=1;
        while (!(r%2))
            r/=2, s*=3;
        l-=s;
        int t=l;
        while (t--) putchar(' ');
        while (++t<s) putchar('X');
        putchar('\n');
    }
}

```

This is based on the same idea as FUZxxl's solution to the problem, of using an explicit rather than implicit form for the rows. The declaration of j sets it to 2^(n+1), and the first while loop computes k=3^(n+1); then l=3^(n+1)-2^(n+1) is the total width of the staircase (this isn't too difficult to prove). We then go through all the numbers r from 1 to 2^(n+1)-1; for each one, if it's divisible by (exactly) 2^n then we plan on printing s=3^n 'X's. l is adjusted to make sure we start from the right spot: we write l spaces and s 'X's, then a newline.
> 3 votes

# Answer
# CJam, ~~46 43 41 39 36~~ 35 bytes

```
L0ri),(a*+_W%(;+{3\#'x*+_,S*}%$1>N*

```

*UPDATE* using a different approach now.

---

Old approach:

```
]ri){3f*_,)"x"a*\]z:+}*_s,f{1$,U+:U-S*\N}

```

Pretty naive and long, but something to get started.

Will add explanation once I golf it.

Try it online here
> 2 votes

# Answer
# Java, ~~271~~ 269 bytes

Uses grc's method.

```
import java.util.*;String a(int a){List<Integer>b=new ArrayList<>();int c=-1,d=1;for(;c++<a;b.add(d),b.addAll(b),b.remove(b.size()-1),d*=3);String f="";for(;b.size()>0;f+="\n"){d=b.remove(b.size()-1);for(int g:b)for(c=0;c<g;c++)f+=' ';for(c=0;c<d;c++)f+='x';}return f;}

```

Indented:

```
import java.util.*;
String a(int a){
    List<Integer>b=new ArrayList<>();
    int c=-1,d=1;
    for(;c++<a;b.add(d),b.addAll(b),b.remove(b.size()-1),d*=3);
    String f="";
    for(;b.size()>0;f+="\n"){
        d=b.remove(b.size()-1);
        for(int g:b)
            for(c=0;c<g;c++)
                f+=' ';
        for(c=0;c<d;c++)
            f+='x';
    }
    return f;
}

```

Any suggestions are welcome.

2 bytes thanks to mbomb007
> 2 votes

# Answer
# Vyxal `j`, 16 bytes

```
Eɽ2Ǒ3$e₌ÞR‡\x*꘍Ṙ

```

Try it Online!

```
Eɽ               # range(1, 2**n-1)
  2Ǒ             # Multiplicity when divided by 2
    3$e          # 3 ** n
       ₌         # Apply both of the following to that:
        ÞR       # Cumulative sums with tail removed and 0 prepended
          ‡\x*   # And that many asterisks
              ꘍Ṙ # Pad with spaces to (cumulative sums) and reverse

```
> 2 votes

# Answer
# JavaScript (ES6) 104 ~~106 118~~

**Edit** Removed the recursive function, the list of '\*' for each line is obtained iteratively, fiddling with bits and powers of 3 (like in many other answers)
Inside the loop, a multiline string is buuilt from bottom up, keeping a running count of leading spaces to add on each line

```
F=n=>{
  for(i=a=s='';++i<2<<n;a=s+'*'.repeat(t)+'\n'+a,s+=' '.repeat(t))
    for(t=u=1;~i&u;u*=2)t*=3;
  return a
}

```

**First Try** removed

The recursive R function build an array with the number of '\*' for each line. For instance R(2) is `[1, 3, 1, 9, 1, 3, 1]`
This array is scanned to build a multiline string from bottom up, keeping a running count of leading spaces to add on each line

```
F=n=>
(R=n=>[1].concat(...n?R(n-1).map(n=>[n*3,1]):[]))(n)
.map(n=>a=' '.repeat(s,s-=-n)+'*'.repeat(n)+'\n'+a,a=s='')
&&a

```

**Test** In Firefox/FireBug console

```
F(3)

```

*Output*

```
                                                                *
                                                             ***
                                                            *
                                                   *********
                                                  *
                                               ***
                                              *
                   ***************************
                  *
               ***
              *
     *********
    *
 ***
*

```
> 1 votes

# Answer
# Perl, 62

```
#!perl -p
eval's/x+/$&$&$&
x/g,s/\d*/x
/;'x++$_;s/x+/$"x$'=~y!x!!.$&/ge

```

First calculates the result iteratively without the leading spaces. Then adds them before each line according to the number of `x` characters in the rest of the string.
> 1 votes

# Answer
## R - 111 characters

Straightforward implementation, building up the array iteratively and destroying it slowly.

```
n=scan()
a=1
if(n)for(x in 1:n)a=c(a,3^x,a)
for(A in a){cat(rep(' ',sum(a)-A),rep('x',A),'\n',sep='');a=a[-1]}

```

Usage:

```
> source('devil.r')
1: 2
2:
Read 1 item
                  x
               xxx
              x
     xxxxxxxxx
    x
 xxx
x

```
> 1 votes

# Answer
# Husk, 41 bytes

```
!→⁰¡(↔§z+ömR' h∫mLtΘ`:"x"ṁȯe"x"Ṙ3f≠' );"x

```

Try it online!

Creates an infinite list of graphs and indexes into them, cause why not.
> 1 votes

# Answer
# Julia 1.0, 64 bytes

```
!n=n<1 ? "x" : [' '^(L=2*3^n-2^n).*(m=!(n-1));lpad('x'^3^n,L);m]

```

Try it online!

output is a list of strings
> 1 votes

# Answer
# Haskell, 81 bytes

```
d=unlines.f
f 0=["x"]
f n|z<-f$n-1=z%[[1..3^n]>>"x"]%z
a%b=map((a!!0>>" ")++)b++a

```

Try it online!

I counted `d=` to compete fairly with the older answer here.
> 1 votes

# Answer
# Jelly, 22 bytes

```
‘2*Ṗọ2 3*µạ+ɼ;¹⁾ xx)ṚY

```

Try it online!

```
‘2*Ṗọ2 3*µạ+ɼ;¹⁾ xx)ṚY Main monadic link
‘                      Increment
 2*                    2 to the power
   Ṗ                   Range from 1 exclusive
    ọ2                 Order of 2
       3*              3 to the power
         µ         )   Map:
          ạ              Absolute difference with
           +ɼ              increment the register by the number
             ;           Join with
              ¹            the number
               ⁾ xx      Repeat " x" that many times
                    Ṛ  Reverse
                     Y Join with newlines

```
> 1 votes

# Answer
# 05AB1E, 20 bytes

```
0$F3*€1Ć}©×®ηO0š¨úR»

```

Outputs with `0` as character instead of `x` (could be any other digit by replacing the leading `0`).

Try it online or verify the first few test cases.

**Explanation:**

```
0            # Push a 0
 $           # Push a 1 and the input-integer
  F          # Pop the input, and loop that many times:
   3*        #  Multiply the values by 3
     €1      #  Push a 1 before each integer in the list
       Ć     #  Enclose to also have a trailing 1
  }©         # After the loop: store the result in variable `®` (without popping)
    ×        # Pop it, and repeat the initial 0 that many times as string(s)
   ®         # Push list `®` again
    η        # Pop and push its prefixes
     O       # Sum each inner prefix
      0š     # Prepend a leading 0
        ¨    # Remove the last item
         ú   # Pad the "x"-string with that many leading spaces
          R  # Reverse the list
           » # Join the lines by newlines
             # (after which the result is output implicitly)

```
> 0 votes

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


title: A nasty little memory leak

text:
# Question
Title: A nasty little memory leak
Below Python code generates memory leak.

**Challenge**: Fix the memory leak with minimal changes to the code as measured by Levenshtein distance to the original code. You may only change the code before `t` is initialised. When the `del t` line is removed the modified program should print `I'm still alive!` every second.

**PS**: I already know the answer (found it after several hours of debugging). This is not the programming help question! Hopefully this would be interesting to folks.

```
import threading, time

# this class takes callback and calls it every 1 sec
class MyTimer:
    def __init__(self, callback):
        self.callback = callback
        self.th = threading.Thread(target=self.run,daemon=True)
        self.th.start()
    def run(self):
        while(True):
            self.callback()
            time.sleep(1)

class TestMyTimer:
    def __init__(self):
        self.timer = MyTimer(self.is_alive)
    def is_alive(self):
        print("I'm still alive")

# test code for MyTimer
t = TestMyTimer()
del t

# just to be sure to collect all dead objects
import gc
gc.collect()

# if you are still seeing messages then we have memory leak!
time.sleep(60)

```

Here's repl.it to play with this code online.

# Answer
Taking inspiration from the comments and from the question, just by adding 3 characters I "fixed" the memory leak.

Granted, I broke everything else at the same time

```
import threading, time

# this class takes callback and calls it every 1 sec
class MyTimer:
    def __init__(self, callback):
        self.callback = callback
        self.th = threading.Thread(target=self.run,daemon=True)
        self.th.start()
    def run(self):
        while(True):
            self.callback()
            time.sleep(1)

class TestMyTimer:
    def __init__(self):
        self.timer = MyTimer(self.is_alive)
    def is_alive(self):
        print("I'm still alive")

# test code for MyTimer
#t = TestMyTimer()
#del t

# just to be sure to collect all dead objects
import gc
#gc.collect()

# if you are still seeing messages then we have memory leak!
time.sleep(60)

```

Edit: The challenge has now been properly updated :)
> 6 votes

# Answer
```
import threading, time

# this class takes callback and calls it every 1 sec
class MyTimer:
    def __init__(self, callback):
        self.a = True
        self.callback = callback
        self.th = threading.Thread(target=self.run,daemon=True)
        self.th.start()
    def run(self):
        while(True):
            self.callback(self.a)
            time.sleep(1)

class TestMyTimer:
    def __init__(self):
        self.timer = MyTimer(self.is_alive)
    def is_alive(self, k):
        print("I'm still alive")
        if not k:
            raise SystemExit()

# test code for MyTimer
t = TestMyTimer()
t.timer.a = 0
del t.timer, t

# just to be sure to collect all dead objects
import gc
gc.collect()

# if you are still seeing messages then we have memory leak!
time.sleep(60)

```
> 0 votes

# Answer
# Python 3, 2 bytes

```
import threading, time

# this class takes callback and calls it every 1 sec
class MyTimer:
    def __init__(self, callback):
        self.callback = callback
        self.th = threading.Thread(target=self.run,daemon=True)
        self.th.start()
    def run(self):
        while(True):
            self.callback()
            time.sleep(1);t

class TestMyTimer:
    def __init__(self):
        self.timer = MyTimer(self.is_alive)
    def is_alive(self):
        print("I'm still alive")

# test code for MyTimer
t = TestMyTimer()
del t

# just to be sure to collect all dead objects
import gc
gc.collect()

# if you are still seeing messages then we have memory leak!
time.sleep(6)

```

Try it online!

Maybe not intended but I don't know a just intended solution
> 0 votes

---
Tags: code-challenge, python, programming-puzzle
---


title: Loading Circle Animation

text:
# Question
Title: Loading Circle Animation
# Loading Circle Animation

## Challenge

Write a full program that takes no input (or has an unused input) that displays exactly the following ASCII animation for as long as possible or only 8 frames.

Frame 1:

```
 #
#
#  #
 ##

```

Frame 2:

```
 ##
#
#
 ##

```

Frame 3:

```
 ##
#  #
#
 #

```

Frame 4:

```
 ##
#  #
#  #

```

(Note that the line at the end is empty.)

Frame 5:

```
 ##
#  #
   #
  #

```

Frame 6:

```
 ##
   #
   #
 ##

```

Frame 7:

```
  #
   #
#  #
 ##

```

Frame 8:

```

#  #
#  #
 ##

```

(Note that the line at the start is empty.)

## Rules

* The program takes no input (or has an unused input).
* The animation can start at any frame, but must animate in sequential order.
* The animation can be in reverse order.
* The program has to run as long as possible or for exactly 8 frames.
* The animation has to be displayed at the same position on screen for every frame.
* Trailing/leading whitespace is okay, as long as the animation looks right.
* `#` and space can be replaced with different (not a newline) distinct characters that are each 1 byte.
* There should be an additional pause of any length but more than 0 ms after an entire frame is drawn.
* This is , so the shortest answer in bytes wins.

# Answer
> 15 votes
# convey, 108 bytes

You never said that the program must have an output, you said in fact "a program that displays exactly the following ASCII animation"

And my program has that animation inside it:

```
    >>,'######'[
    ^<v
     ^<
 >>>v  >>>v
>,<<<  ,<<<
^    >v'######'[
^<< >^,'######'[
>>^ ^<<
'######'[

```

Try it online!

Here is the program runing:

And in the center you can see... THE LOAD ANIMATION :v

Really the programs doesn't start by an state of the animation, it waits 2 cycles before start but... its cool... i supose?

# Answer
> 14 votes
# CP-1610 machine code, 33 DECLEs1 ≈ 42 bytes2

*1. A CP-1610 opcode is encoded with a 10-bit value (0x000 to 0x3FF), known as a 'DECLE'.*
*2. As per the exception described in this meta answer, the exact score is **41.25 bytes** (330 bits)*

Uses `$`'s and spaces. Loops forever. Each frame is displayed during ~650 ms. This is a full program mapped in the memory range $4800-$4820. (The Intellivision bootstrap code will jump at $4800 after a reset if it finds something there.)

```
                      BT    EQU   $200      ; BACKTAB address
                            ROMW  10        ; 10-bit ROM
                            ORG   $4800     ; map the program at $4800

4800   0002                 EIS             ; enable interrupts

4801   02B8 007E            MVII  #$7E, R0  ; load %01111110 in R0
4803   0044                 SWAP  R0,   2   ; expand it to %0111111001111110

4804   00BD           loop: MOVR  R7,   R5  ; \_ R5 = pointer to
4805   02FD 0013            ADDI  #p-$, R5  ; /       BACKTAB positions

4807   0081           draw: MOVR  R0,   R1  ; copy R0 to R1
4808   03B9 0020            ANDI  #32,  R1  ; isolate the 6th bit
480A   02F9 0007            ADDI  #7,   R1  ; add 7 to draw in white
480C   02AA                 MVI@  R5,   R2  ; load the position in R2
480D   0251                 MVO@  R1,   R2  ; write the character
480E   0058                 SLLC  R0        ; \_ rotate the pattern
480F   0028                 ADCR  R0        ; /  to the left
4810   0092                 TSTR  R2        ; is R2 equal to 0?
4811   022C 000B            BNEQ  draw      ; if not, draw again

4813   0012           idle: DECR  R2        ; idle loop: decrement R2
4814   022B 0002            BMI   idle      ; until it looks positive

4816   0220 0013            B     loop      ; restart

                            ; positions
4818   0229 023D ...  p:    DECLE BT+41, BT+61, BT+82, BT+83
481C   0240 022C ...        DECLE BT+64, BT+44, BT+23, BT+22
4820   0000                 DECLE 0

```

## Output

*made with jzIntv*

# Answer
> 9 votes
# HTML5 + CSS3, ~~190 + 98 = 288~~ ~~162 + 102 = 264~~ 86 + ~~170~~ ~~166~~ 165 = ~~256~~ ~~252~~ 251 bytes

```
tt{--c:1}div{--c:2}div tt{--c:3}a+a{--d:calc(7 - var(--c,0))}a{animation:a steps(4,start)1s calc(var(--d,var(--c,0))/8*-1s)infinite}@keyframes a{to{visibility:hidden
```

```
<pre> <a>#</a><a>#</a>
<tt><a>#</a>  <a>#</a><div><a>#</a>  <a>#</a>
<tt> <a>#</a><a>#
```

Explanation: This is based on my Stack Overflow answer to Imitating a blink tag with CSS3 animations, however the number of steps is set to 4 to reduce the duty cycle from 80% to 75% and CSS variables are used to offset the animation of each `#` character. Edit: Saved at least 24 bytes thanks to @IsmaelMiguel. Saved 1 byte by stealing @ccprog's `1s/8` trick.

# Answer
> 7 votes
# Charcoal, ~~21~~ 19 bytes

```
ＲＦχ⁸ＧＨ*²⮌…“⊟4«Ｌ”⁺⁸ι

```

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

```
ＲＦχ⁸

```

Repeats 8 times with a 10ms delay in between each repeat, dumping the canvas to the terminal each time. (Note that this just shows up as control characters in TIO.)

```
ＧＨ*²⮌…“⊟4«Ｌ”⁺⁸ι

```

Draw an octagon using the multidirectional `*`, which means all directions in turn, in the order right, down right, down, down left, left, up left, up, up right. Each side of the octagon is 2 characters long, and the octagon is drawn using a cyclic permutation of the string `# #####` (obtained through reversing the cyclic extension of `##### #` which then gets implicitly truncated to 8 characters) depending on the loop index.

For offline use you may prefer 1 second frames for the same byte count:

```
ＲＦφ⁸ＧＨ*²⮌…“⊟4«Ｌ”⁺⁸ι

```

The animation can be extended to 1000 frames (125 whole cycles) at a cost of two bytes:

```
ＲＦχφＧＨ*²⮌…“⊟4«Ｌ”⁺⁸﹪ι⁸

```

Try it online! Link is to verbose version of code. Or with 1s frames:

```
ＲＦφφＧＨ*²⮌…“⊟4«Ｌ”⁺⁸﹪ι⁸

```

An infinite animation would take ~~27~~ 25 bytes (10ms and 1s frames):

```
ＲＷχ¹«ＧＨ*²⮌…“⊟4«Ｌ”⁺⁸﹪φ⁸≦⊕φ
ＲＷφ¹«ＧＨ*²⮌…“⊟4«Ｌ”⁺⁸﹪φ⁸≦⊕φ

```

# Answer
> 7 votes
# MATL, ~~39~~ 34 bytes

```
`3&Xx0'=<.Ic^w'FO8:@YShZah4eH>ZcDT

```

Try it at MATL online!

### How it works

```
`            % Do..while
  3&Xx       %   Pause for 300 ms and clear screen
  0          %   Push 0
  '=<.Ic^w'  %   Push this string (*)
  F          %   Push false (**)
  O          %   Push 0
  8:         %   Push [1 2 ... 8]
  @          %   Push current iteration index, k
  YS         %   Rotate right by k units. For example, in the 1st iteration
             %   (k=1) this gives [8 1 2 3 4 5 6 7]
  h          %   Concatenate: prepends 0. This gives [0 8 1 2 3 4 5 6 7]
             %   in the 1st iteration
  Za         %   Base conversion. Converts the string (*) from the base
             %   formed by all printable ASCII chars except single quote
             %   (represented by the false input, (**)) to the base (***).
             %   This gives [6 5 0 7 0 0 4 8 0 0 3 0 1 2] in the 1st iteration
  h          %   Concatenate: prepends 0. Gives [0 6 5 0 7 0 0 4 8 0 0 3 0 1 2]
  4e         %   Reshape into 4-row matrix in column-major order. This pads with
             %   a 0 at the end to have a number of entries multiple of 4. Gives
             %   [ 0 7 8 0 ;
             %     6 0 0 1 ;
             %     5 0 0 2 ;
             %     0 4 3 0 ]
             %   in the 1st iteration. For other iterations the nonzero values
             %   will be rotated with respect to the above
  H>         %   Greater than 0? Gives
             %   [ 0 1 1 0 ;
             %     1 0 0 0 ;
             %     1 0 0 0 ;
             %     0 1 1 0 ]
  Zc         %   Convert nonzeros to '#' and zeros to char 0 (shown as space)
             %   [ ' ## ' ;
             %     '#   ' ;
             %     '#   ' ;
             %     ' ## ' ]
  D          %   Display
  T          %   Push true
             % End (implicit). A new iteration is run because the top of the
             % stack is true

```

# Answer
> 6 votes
# APL (Dyalog Unicode), ~~60~~ 55 bytes

Full program. Requires 0-based indexing. Uses `0` and `1` instead of  and `#`. Waits 1 seconds between frames and stops after the 8th.

```
⎕ED&'a'⋄{⎕DL≡a∘←⊃⍤⍕¨4 4⍴'012080037004065'∊⍕1+8|⍵+⍳6}¨⍳8

```

`'a'` the (eventual) variable name "a"
`&` in a background thread:
`⎕ED` open an EDit window on that name

then:

`⍳8` generate the **i**nteger sequence 0…7
`{` on each element of that, apply the following anonymous lambda:
`⍳6` generate the **i**nteger sequence 0…5
`⍵+` add the argument to that
`8|` find the division remainder of that when divided by 8
`1+` increment that
format as space-separated text
`'012080037004065'∊` for each character in this string, check if it is a member (`1`) or not (`0`) of that string
`4 4⍴` reshape those 16 `1`s and `0`s into a 4-by-4 matrix
`⍕¨` format each of those numbers as a 1-character list
`⊃¨` get the first character of each
`a∘←` globally assign that value to the variable `a` (the edit window will update)
get the nesting depth of that matrix (it is 1)
`⎕DL` DeLay that many seconds

Old version in action:

# Answer
> 3 votes
# 05AB1E, 36 bytes

```
[2¾6×2úN._7Ý.Λ,т.W’IEx.Helpers.Š‡’.E

```

If only 05AB1E had a builtin to clear the console.. :/

Starts at frame 6, and rotates indefinitely in reversed order. Uses `0` instead of `#` as character, although could alternatively use `1`/`2` for the same byte-count by replacing the `¾` with `X`/`Y` respectively. Sleeps for 100 ms between each print, but could alternatively sleep any of these times for the same byte-count: `1`/`2`/`3`/`4`/`5`/`6`/`7`/`8`/`9`/`T` (10)/ (26)/ (36)/ (95)/ (255)/ (256)/ (1000), by replacing the `т`.

**Explanation:**

```
[                   # Loop indefinitely:
 2                  #  Push 2
 ¾                  #  Push 0
  6×                #  Repeat it 6 times as string: "000000"
    2ú              #  Pad with 2 leading spaces: "  000000"
      N._           #  Rotate the string the loop-index amount of times towards the left
 7Ý                 #  Push list [0,1,2,3,4,5,6,7]
         .Λ         #  Use the modifiable Canvas builtin with these three options
           ,        #  Pop and print it with trailing newline
 т.W                #  Sleep for 100 ms
 ’IEx.Helpers.Š‡’   #  Push dictionary string "IEx.Helpers.clear"
                 .E #  Evaluate and execute it as Elixir code

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `’IEx.Helpers.Š‡’` is `"IEx.Helpers.clear"`.

The Canvas Builtin uses three arguments to draw a shape:

* Length of the lines we want to draw
* Character/string to draw
* The direction to draw in, where each digit represents a certain direction:

```
7   0   1
  ↖ ↑ ↗
6 ← X → 2
  ↙ ↓ ↘
5   4   3

```

`2¾6×2úN._7Ý` creates the following Canvas arguments:

* Length: `2`
* Characters: `" 000000"` (potentially rotated)
* Directions: `[0,1,2,3,4,5,6,7]`, which translate to \\$\[↑,↗,→,↘,↓,↙,←,↖\]\\$

Try the first two steps online.

Step 1: Draw 2 characters (`" "`) in direction 0/:

```

```

Step 2: Draw 2-1 characters (`"0"`) in direction 1/:

```
 0

```

Step 3: Draw 2-1 character (`"0"`) in direction 2/:

```
 00

```

Step 4: Draw 2-1 character (`"0"`) in direction 3/:

```
 00
   0

```

etc.

Step 7: Draw 2-1 character (`"0"`) in direction 6/:

```
 00
   0
   0
 00

```

Step 8: Draw 2-1 character (`" "`) in direction 7/:

```
 00
   0
   0
 00

```

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

I don't have a gif to see the animation in action, because `IEx.Helpers.clear` (or any clear through Elixir-eval for that matter) doesn't seem to work on Windows machines.. I tried to enable ANSI escape codes in the Windows Console by modifying the Registry on my PC, but wasn't able to get it to work. This should work as intended on a non-Windows machines, though.

As alternative, here the outputs where the clear-command is ignored and the infinite loop `[` is replaced with a loop of eight `8F`: Try it online.

# Answer
> 3 votes
# Stax, 32 bytes

```
éÄû?*&╬_ÅuQ☼Ñï|Σ░♦ë♣∞î,↑&èå#QWÉ╡

```

Run and debug it

Uses JS `requestAnimationFrame` to delay a frame between each step. Here is one which uses a 30-frame delay for better inspection: link

Idea is similar to MATL. Lack of vectorization makes it somewhat bulky.

# Answer
> 3 votes
# Python 2, 158 bytes

```
import time
while 1:
 for w in range(8):
	print'\n'*99
	for x in'48966886698469906912611621960996'[w*4:w*4+4]:print('000'+bin(int(x))[2:])[-4:]
	time.sleep(1)

```

This version does not work on Try it online!

Uses `0` for  and `1` for `#`.

Here is a version **(non competing)** without the clear screens and pauses (one of which blows up TIO) which displays each stage of the animation for each cycle and allows users without a Python 2.7 environment to see the output. For me, this covers the most important and interesting part of the challenge. Clearing the screen and adding delays is really just commentary IMHO.

# Python 2, 118 bytes

```
for w in range(8):
 for x in'48966886698469906912611621960996'[w*4:w*4+4]:print('000'+bin(int(x))[2:])[-4:]
 print ' '

```

Try it online!

# Answer
> 3 votes
# pug \+ CSS, ~~81 + 135 = 216~~ 87 + 123 = 210 bytes

```
-o=54060,i=0
while o>>=1
 if o&1
  a(style=`--i:-${((i&1?7:0)^i++>>1)/8}s`) 0
 else
  b

```

```
body{display:grid;grid:none/repeat(4,1ch)}a{animation:a steps(4,start)1s var(--i)infinite}@keyframes a{to{visibility:hidden

```

Watch it on CodePen. Click on the downward arrow in the HTML area to see the compiled HTML.

The animation is inspired by Neil's answer, but the custom CSS variables are injected by pug.

The characters are ordered with a CSS grid, four items per row with a width of `1ch` each.

`1ch` is defined as the exact advance of the `0` character in that font. That is the reason for displaying it, so the output is exactly aligned as if it was formatted with `<pre>`.

Edit: saved 6 bytes with the help of Ismael Miguel.

# Answer
> 3 votes
# Wolfram Mathematica 89 bytes

```
ListPlot[CirclePoints@8~RotateLeft~u~Drop~2,PlotRange->{{-1,1},{-1,1}}]~Animate~{u,0,7,1}

```

This gif is a bit glitchy, but the above animation does appear correctly, and play automatically and continuously, within a Mathematica notebook.

How it works:

The ASCII characters in the challenge are arranged as vertices on an octagon rather than points on a circle (the left and right pairs are vertically aligned, and the top and bottom pairs are horizontally aligned), so I used `CirclePoints@8` to get the coordinates of the 8 vertices of a regular octagon centered about {0,0}. I rotated this coordinate list successively to the left by `u`, and then dropped the first two points. I used `ListPlot` to plot these, and then animated this, increasing u from 0 to 7 in increments of 1.

The characters are displayed as plot points.

Even though `,PlotRange->{{-1,1},{-1,1}}` costs 27 bytes, an explicit plot range specification was needed to maintain the aspect ratio of the plot as the points were rotated, so that the points would always appear at the same position on the screen.

Alternately, for three less bytes (86), one could use `ListPolarPlot` to put the six points on an actual circle (separated by angles of Pi/4), rather than the vertices of an octagon:

```
ListPolarPlot[1 &~Array~6,DataRange->{u,5*Pi/4+u},PlotRange->Full]~Animate~{u,0,7,Pi/4}

```

This latter code would have been longer than the former, except that here the position and aspect ratio can be fixed using `PlotRange->Full` instead of `PlotRange->{{-1,1},{-1,1}}`.

# Answer
> 2 votes
# C (gcc), ~~162~~ 149 bytes

* -13 thanks to ceilingcat

Loops forever. Each line is encoded in 4-bit segments and shifted to produce the line for the current frame, with increasingly long `sleep()` values. The screen is cleared with a form feed character, which should work in most terminal emulators.

It would be possible to save 3 bytes by not initializing the starting frame, but there is a chance that a negative number could be entered before the function is called, resulting in a frame with a 0-second delay.

```
i,h;f(c){for(c=0;puts("\f");sleep(++c))for(i=4;i--;puts(""))for(h=L"\x66402666\x98891199\x88999119\x46666620"[i]>>c%8*4&15;h;h/=2)printf(L" #"+h%2);}

```

Try it online!

# Answer
> 2 votes
# HTML5 + CSS3 - 78 + 156 = 234 bytes

This answer is entirely based on @Neil's answer.

This was offered as a size reduction of his original answer, which he allowed me to share as an answer.
This answer includes a 1 byte trick as well, taken from the original answer.

```
pre>*{animation:a steps(4,start)1s calc(var(--c,0)*-125ms)infinite}c{--c:7}d{--c:1}e{--c:6}f{--c:2}h{--c:5}j{--c:3}k{--c:4}@keyframes a{to{visibility:hidden
```

```
<pre> <a>#</a><c>#</c>
<d>#</d>  <e>#</e>
<f>#</f>  <h>#</h>
 <j>#</j><k>#</k>
```

This relies entirely on invalid tags, to calculate the CSS animation delays. This allows to shorten the selectors a lot, and is shorter than pre-calculating the delays.

---

If we're allowed to take certain liberties with the presentation of the loading animation, it's possible to reduce the size a few more bytes.

Using `opacity` instead of `visibility`, it's possible to have 2 hidden and all others partially visible.
If the timing can be flexible, it is possible to save some bytes as well.

This also includes a suggestion by @Neil, to use `1s` steps for `8s`, shaving this one down by 2 bytes.

As such, here's a 78 + 145 = **223 bytes** long solution, which might not be valid (but looks prettier, in my opinion):

```
pre>*{animation:a steps(4,start)8s calc(var(--c,0)*-1s)infinite}c{--c:7}d{--c:1}e{--c:6}f{--c:2}h{--c:5}j{--c:3}k{--c:4}@keyframes a{to{opacity:0
```

```
<pre> <a>#</a><c>#</c>
<d>#</d>  <e>#</e>
<f>#</f>  <h>#</h>
 <j>#</j><k>#</k>
```

---

Please remember to upvote @Neil's answer before considering upvoting mine.

# Answer
> 1 votes
# Python 3.8 (pre-release), 91 bytes

Not my favorite because there's no delay...

Also this only works with a terminal that supports moving the cursor with \x1b\[r;cH, and clearing the terminal with \x1b\[2J (... It works for me in termux on Android so far...)

```
[print('\x1b[2J','\x1b[%c;%cH*'*6%(*('2131424334241312'*2)[b*2:b*2+12],))for b in range(8)]

```

Try it online!

# Python 3.8 (pre-release), 119 bytes

Here's a more realistic answer with the most obvious delay.

```
import time;[print('\x1b[2J','\x1b[%c;%cH*'*6%(*('2131424334241312'*2)[b*2:b*2+12],))or time.sleep(1)for b in range(8)]

```

Try it online!

# Answer
> 1 votes
# JavaScript, 93 bytes

```
setInterval(_=>console.log(` 01
7  2
6  3
 54`.replace(/\S/g,n=>(i-n)%8<6?'#':' ',i++)),i=99)
```

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


title: Goto the Nth Page

text:
# Question
Title: Goto the Nth Page
It is common to need to make a page selection interface. It typically looks like this:

```
prev 1 ... 3 4 [5] 6 7 ... 173 next

```

Which means there are totally 173 pages, and you are on the 5th page currently.

This challenge requires you take the total number of pages and the current page number as input, and output a string (or an array) to "display" the page selector.

## Input

2 positive integers

* current page number
* count of pages

It is guaranteed that 1 \<= current \<= total.

## Output

Output a string or an array which represent the ui for page selectors.

* If output as string, a single space (U+0020) should be used between each pages.
* If output as an array, the array should produce same result as the string after convert each item to string and join them with a single space.
    + The three dots (`...`) is not optional for array output.

## Details

* If current == 1, no "prev" will be outputted, otherwise, "prev" comes first.
* If current == total, no "next" will be outputted, otherwise, "next" comes last.
* The first page (1) and the last page (total) should always be outputted.
* The current page, (current - 1) page, (current - 2) page, (current + 1) page, (current + 2) page should be outputted as long as the are in the range of \[1..total\].
* No other pages numbers should be outputted.
* Pages outputted should be sorted in ascending order.
* Output should not contain duplicate page numbers.
* Current page should be highlighted by wrap it in a pair of `[]`.
* If there is a gap between any neighbors, three dots (`...`) should be inserted.

## Test Cases

```
Current Total    Output
1       1        [1]
1       2        [1] 2 next
1       10       [1] 2 3 ... 10 next
3       3        prev 1 2 [3]
3       6        prev 1 2 [3] 4 5 6 next
4       6        prev 1 2 3 [4] 5 6 next
4       7        prev 1 2 3 [4] 5 6 7 next
3       10       prev 1 2 [3] 4 5 ... 10 next
5       10       prev 1 ... 3 4 [5] 6 7 ... 10 next
10      10       prev 1 ... 8 9 [10]
52      173      prev 1 ... 50 51 [52] 53 54 ... 173 next

```

## Rules

* This is code-golf, the shortest code wins!

# Answer
# JavaScript (ES6), ~~130~~ ~~122~~ 121 bytes

Invoke with currying syntax, e.g. `f(3)(10)`.

```
x=>X=>[x>1&&'prev 1',x>4&&'...',x>3&&x-2,x>2&&x-1,`[${x}]`,(X-=x)>1&&x+1,X>2&&x+2,X>3&&'...',X&&X+x+' next'].filter(_=>_)

```

```
f=

x=>X=>[x>1&&'prev 1',x>4&&'...',x>3&&x-2,x>2&&x-1,`[${x}]`,(X-=x)>1&&x+1,X>2&&x+2,X>3&&'...',X&&X+x+' next'].filter(_=>_)

console.log(f(1)(1))
console.log(f(1)(2))
console.log(f(1)(10))
console.log(f(3)(3))
console.log(f(3)(6))
console.log(f(4)(6))
console.log(f(4)(7))
console.log(f(3)(10))
console.log(f(5)(10))
console.log(f(10)(10))
console.log(f(52)(173))
```

Try it online!

*-1 byte (Arnauld): Set `X` to `X-x`.*
> 10 votes

# Answer
# Retina, ~~125~~ ~~113~~ ~~109~~ 107 bytes

```
.+
$*
r`1\G
 1$'
¶

O`1+
\b(1+) \1\b
[$1]
 .* (1+ 1+ \[)|(] 1+ 1+) .*
$2 ... $1
^1
prev 1
1$
1 next
1+
$.&

```

Try it online! Link includes test cases. Saved 12 bytes thanks to @MartinEnder. Explanation:

```
.+
$*

```

Convert to unary.

```
r`1\G
 1$'

```

Generate all the page numbers in reverse order.

Delete the newline separating the input. (There's also a space there from the page number generation anyway.)

```
O`1+

```

Sort the pages back into ascending order. This also sorts the current page, which is now duplicated.

```
\b(1+) \1\b
[$1]

```

Unduplicate and wrap `[]`s around the current page.

```
 .* (1+ 1+ \[)|(] 1+ 1+) .*
$2 ... $1

```

Add an ellipsis if the current page is at least 5, or if there are at least 4 pages after the current page. (Note trailing space, to avoid including the last page in the ellipsis.)

```
^1
prev 1

```

Add the prev if the current page is not 1.

```
1$
1 next

```

Add the next if the current page is not the last page.

```
1+
$.&

```

Convert back to decimal.
> 10 votes

# Answer
# 6502 machine code (C64), 160 bytes

```
00 C0 20 9B B7 86 FB CA F0 01 CA 86 FD 20 9B B7 86 FC A6 FB E8 E4 FC B0 01 E8
86 FE A2 01 E4 FB F0 1A A9 91 A0 C0 20 1E AB A2 02 E4 FD B0 0D A9 2E 20 D2 FF
CA 10 FA 20 3F AB A6 FD 86 9E E4 FB D0 05 A9 5B 20 D2 FF A9 00 20 CD BD A6 9E
E4 FB D0 05 A9 5D 20 D2 FF 20 3F AB A6 9E E4 FC F0 25 E4 FE F0 05 E8 86 9E D0
D5 E8 E4 FC F0 0D A2 02 A9 2E 20 D2 FF CA 10 FA 20 3F AB A6 FC A9 00 20 CD BD
20 3F AB A6 FC E4 FB F0 07 A9 99 A0 C0 20 1E AB 60 50 52 45 56 20 31 20 00 4E
45 58 54 00

```

**Online demo** -- **Usage:** `sys49152,[current],[total]`, e.g. `sys49152,5,173`.

The numbers must be in the range \[1..255\] with current \<= total. As this wasn't specified otherwise, this is the "natural" unsigned integer range on an 8bit processor.

---

Explanation as commented disassembly listing:

```
         00 C0       .WORD $C000        ; load address
.C:c000  20 9B B7    JSR $B79B          ; read 8bit integer
.C:c003  86 FB       STX $FB            ; store current page
.C:c005  CA          DEX                ; calculate lower start for ...
.C:c006  F0 01       BEQ .stl
.C:c008  CA          DEX
.C:c009   .stl:
.C:c009  86 FD       STX $FD            ; ... range and store
.C:c00b  20 9B B7    JSR $B79B          ; read 8bit integer
.C:c00e  86 FC       STX $FC            ; store total pages
.C:c010  A6 FB       LDX $FB            ; load current page
.C:c012  E8          INX                ; calculate upper end for ...
.C:c013  E4 FC       CPX $FC
.C:c015  B0 01       BCS .stu
.C:c017  E8          INX
.C:c018   .stu:
.C:c018  86 FE       STX $FE            ; ... range and store
.C:c01a  A2 01       LDX #$01           ; check whether first page is current
.C:c01c  E4 FB       CPX $FB
.C:c01e  F0 1A       BEQ .sequence      ; then directly to sequence
.C:c020  A9 91       LDA #<.prev        ; output string for ...
.C:c022  A0 C0       LDY #>.prev
.C:c024  20 1E AB    JSR $AB1E          ; ... "prev 1 "
.C:c027  A2 02       LDX #$02           ; check whether page 2 is in range ...
.C:c029  E4 FD       CPX $FD
.C:c02b  B0 0D       BCS .sequence      ; ... then directly to sequence
.C:c02d  A9 2E       LDA #$2E           ; load character '.'
.C:c02f   .ellip1:
.C:c02f  20 D2 FF    JSR $FFD2          ; output ...
.C:c032  CA          DEX
.C:c033  10 FA       BPL .ellip1        ; ... 3 times
.C:c035  20 3F AB    JSR $AB3F          ; output space
.C:c038  A6 FD       LDX $FD            ; load lower start for range
.C:c03a   .sequence:
.C:c03a  86 9E       STX $9E            ; store to temporary
.C:c03c   .seqloop:
.C:c03c  E4 FB       CPX $FB            ; compare with current
.C:c03e  D0 05       BNE .notcurrent1   ; yes -> output '['
.C:c040  A9 5B       LDA #$5B
.C:c042  20 D2 FF    JSR $FFD2
.C:c045   .notcurrent1:
.C:c045  A9 00       LDA #$00
.C:c047  20 CD BD    JSR $BDCD          ; output number
.C:c04a  A6 9E       LDX $9E            ; compare with current
.C:c04c  E4 FB       CPX $FB
.C:c04e  D0 05       BNE .notcurrent2   ; yes -> output ']'
.C:c050  A9 5D       LDA #$5D
.C:c052  20 D2 FF    JSR $FFD2
.C:c055   .notcurrent2:
.C:c055  20 3F AB    JSR $AB3F          ; output space
.C:c058  A6 9E       LDX $9E
.C:c05a  E4 FC       CPX $FC            ; compare position with last page
.C:c05c  F0 25       BEQ .printnext     ; if eq jump to part printing "next"
.C:c05e  E4 FE       CPX $FE            ; compare position to upper end of range
.C:c060  F0 05       BEQ .printellip2   ; if eq jump to part printing "..."
.C:c062  E8          INX
.C:c063  86 9E       STX $9E            ; next number
.C:c065  D0 D5       BNE .seqloop       ; and repeat loop for sequence
.C:c067   .printellip2:
.C:c067  E8          INX
.C:c068  E4 FC       CPX $FC            ; compare next number with last page
.C:c06a  F0 0D       BEQ .printlast     ; if eq jump to part printing page num
.C:c06c  A2 02       LDX #$02
.C:c06e  A9 2E       LDA #$2E           ; load character '.'
.C:c070   .ellip2:
.C:c070  20 D2 FF    JSR $FFD2          ; output ...
.C:c073  CA          DEX
.C:c074  10 FA       BPL .ellip2        ; ... 3 times
.C:c076  20 3F AB    JSR $AB3F          ; output space
.C:c079   .printlast:
.C:c079  A6 FC       LDX $FC            ; output last page number
.C:c07b  A9 00       LDA #$00
.C:c07d  20 CD BD    JSR $BDCD
.C:c080  20 3F AB    JSR $AB3F          ; output space
.C:c083   .printnext:
.C:c083  A6 FC       LDX $FC            ; compare current page with last page
.C:c085  E4 FB       CPX $FB
.C:c087  F0 07       BEQ .done          ; if eq nothing else to do
.C:c089  A9 99       LDA #<.next        ; output string for ...
.C:c08b  A0 C0       LDY #>.next
.C:c08d  20 1E AB    JSR $AB1E          ; "next"
.C:c090   .done:
.C:c090  60          RTS
.C:c091   .prev:
.C:c091  50 52 45 56 .BYTE "prev"
.C:c095  20 31 20 00 .BYTE " 1 ", $00
.C:c099   .next:
.C:c099  4E 45 58 54 .BYTE "next"
.C:c09d  00          .BYTE $00

```
> 8 votes

# Answer
# , ~~214 bytes~~ 168 bytes

```
function(c,m,`~`=function(x,y)if(x)cat(y)){o=-2:2+c
o=o[o>0&o<=m]
o[o==c]=paste0('[',c,']')
c>1~'prev '
c>3~'1 '
c>4~' ... '
T~o
c+3<m~' ...'
c+2<m~c('',m)
c<m~' next'}

```

Try it online!

Thanks to @user2390246 for some great golfing tips
> 6 votes

# Answer
# Wolfram Language (Mathematica), ~~131~~ ~~114~~ 109 bytes

```
Range@#2/.{#->"["<>(t=ToString)@#<>"]",1->"prev 1",#2->t@#2<>" next",#-3|#+3:>"...",x_/;Abs[x-#]>2:>Nothing}&

```

Try it online!

## How it works

Lots of replacing. Starting with a list of all pages, replace, in order:

1. `#->"["<>(t=ToString)@#<>"]"`: the current page with a bracketed string,
2. `1->"prev 1"`: page 1 with the string `prev 1`,
3. `#2->t@#2<>" next"`: the last page with the string `(number) next`, with
4. `#-3|#+3:>"..."`: page `current-3` and page `current+3` with the string `"..."`,
5. `x_/;Abs[x-#]>2:>Nothing`: all other (integer) pages below `current-2` or above `current+2` with nothing. (Yes, `Nothing` is a built-in.)
> 5 votes

# Answer
# APL (Dyalog), ~~83~~ 82 bytes

Anonymous infix function taking current as left argument and total as right argument.

```
{('prev '/⍨⍺>1),('x+'⎕R'...'⍕∊(⊂1⌽'][',⍕)@⍺⊢'x'@(~∊∘(1,⍵,⍺+3-⍳5))⍳⍵),' next'/⍨⍺<⍵}

```

Try it online!

`{``}` explicit lambda where  and  represent the left and right arguments:

`⍺<⍵` is current smaller than total?

`' next'/⍨` if so (lit. use that to replicate) the text

`(``),` prepend the following:

`⍳⍵`**ɩ**ntegers 1 through total

`'x'@(``)` replace with an `x` **at** the positions where the items are…

`~` not

members of

`1` one

`,` followed by

the total

`,` followed by

`⍳5` the first five **ɩ**ntegers (`[1,2,3,4,5]`)

`3-` subtracted from three (`[2,1,0,-1,-2]`)

`⍺+` added to the current (`[⍺+2,⍺+1,⍺,⍺-1,⍺-2]`)

yield that (serves to separate  from `'x'`)

`(``)` apply the following tacit function **at** the current position:

format (stringify)

`'][',` prepend the text\`

`1⌽` rotate one step leftward (moves the `]` to the end)

enclose (so that it is a scalar which will fit in the single indicated position)

**ϵ**nlist (flatten – because we made it nested when we inserted brackets)

format (stringify – 1 space separating numbers from each other and from `x` runs)

`'x+'⎕R'...'` PCRE **R**eplace `x` runs with three periods

`(``),` prepend the following:

`⍺>1` is current larger than 1?

`'prev '/⍨` if so (lit. use that to replicate) the text
> 5 votes

# Answer
# Funky, ~~218~~ 210 bytes

*Saved some bytes, some of which thanks to tsh*

```
p=>m=>{t={}a=t::push b=t::pop fori=p-2i<p+3i++a(i)t[2]="[%i]"%p whilet[0]<1b(0)whilet[n=-1+#t]>m b(n)ifp>4a(0,"...")ifp>3a(0,1)ifp>1a(0,"prev")ifp<m-3a("...")ifp<m-2a(m)ifp<m a("next")t::reduce((a,b)=>a+" "+b)}

```

Try it online!
> 4 votes

# Answer
# Python 2, 135 bytes

```
lambda c,t:re.sub('  +',' ... ','prev '*(c>1)+' '.join(`[x,[x]][x==c]`*(x%t<2or-3<x-c<3)for x in range(1,t+1))+' next'*(c<t))
import re

```

Try it online!

First we create a string like `prev 1 3 4 [5] 6 7 10 next`, which has “gaps” caused by erasing some numbers but not their delimiting spaces. Then we replace any run of 2+ spaces by `...` using a regex.
> 4 votes

# Answer
# Python 2, ~~136~~ 130 bytes

```
lambda p,n:[i for i,j in zip(['prev',1,'...',p-2,p-1,[p],p+1,p+2,'...',n,'next'],[1,3,4,2,1,.1,-n,1-n,3-n,2-n,-n])if p*cmp(j,0)>j]

```

Try it online!

> If output as an array, the array should produce same result as the string after convert each item to string and join them with a single space.

Try it online! in prettified form, where you can see the footer translates quite literally to "convert each to string, join on spaces".

This is an alternative to Lynn's approach.
> 4 votes

# Answer
# Octave, ~~169 196 190 181 175 169~~ 166 bytes

```
@(n,m)(r=[(n>1)*'prev ' (g=n>4)*'1 ... ' (s=@sprintf)(f='%d ',max(n-3+g,1):n-1) s('[%d]',n) 32*(q=n<m) s(f,n+1:min(n+3-(l=n<m-3),m)) l*['... ' s(f,m)] q*'next'])(r>0)

```

Try it online!

I'll add an explanation later on.

Hmm, seems there were some issues with the output format. These have now been resolved - all outputs are correct. But alas it cost 27 bytes. Managed to claw all of those back though with a bit of fat trimming.

---

* Save 6 bytes by using `*` instead of `.*` \- thanks @StewieGriffin
* Save 9 bytes using `sprintf` instead of `num2str` as I already had that handle in `s`.
* Save 6 bytes by pulling `[]` into the `sprint` call.
* Save 6 bytes by finding a way to reduce the number of comparisons.
* Save 3 bytes by removing need for `strtrim()` without causing trailing space.
> 3 votes

# Answer
# Java (OpenJDK 8), ~~218~~ ~~179~~ ~~177~~ ~~167~~ 166 bytes

```
c->t->{String p,e="... ",x="["+c+"] ";int i=c-2;for(p=c>1?"prev 1 "+(c>4?e:""):x;i<c+3;i++)p+=i>1&i<t?i==c?x:i+" ":"";return p+(i<t-1?e:"")+(c<t?t+" next":t>1?x:"");}

```

Try it online!
> 3 votes

# Answer
# Java 8, ~~201~~ ~~200~~ 197 bytes

```
t->n->(n<2?"[1] ":"prev 1 ")+(n>4?"... "+(n-2)+" "+~-n+" ["+n+"] ":n>3?"2 3 [4] ":n>2?"2 [3] ":n>1?"[2] ":"")+(n<t?(n>t-2?"":n>t-3?t-1+" ":n>t-4?(t-2)+" "+~-t+" ":++n+" "+-~n+" ... ")+t+" next":"")

```

**Explanation:**

Try it here.

```
t->n->             // Method with two integer parameters and String return-type
  (n<2?            //  If the current page is 1:
    "[1] "         //   Start with literal "[1] "
   :               //  Else:
    "prev 1 ")     //   Start with literal "prev 1"
  +(n>4?           //  +If the current page is larger than 4:
     "... "        //    Append literal "... "
     +(n-2)+" "    //    + the current page minus 2, and a space
     ~-n           //    + the current page minus 1, and a space
     +" ["+n+"] "  //    + "[current_page]" and a space
    :n>3?          //   Else-if the current page is 4:
     "2 3 [4] "    //    Append literal "2 3 [4] "
    :n>2?          //   Else-if the current page is 3:
     "2 [3] "      //    Append literal "2 [3] "
    :n>1?          //   Else-if the current page is 2:
     "[2] "        //    Append literal "[2] "
    :              //   Else (the current page is 1):
     "")           //    Append nothing
  +(n<t?           //  +If the current page and total amount of pages are not the same:
     (n>t-2?       //    If the current page is larger than the total minus 2:
       ""          //     Append nothing
      :n>t-3?      //    Else-if the current page is larger than the total minus 3:
       t-1+" "     //     Append the total minus 1, and a space
      :n>t-4?      //    Else-if the current page is larger than the total minus 4:
       (t-2)+" "   //     Append the total minus 2, and a space
       +~-t+" "    //     + the total minus 1, and a space
      :            //    Else:
       ++n+" "     //     Append the current page plus 1, and a space
       +-~n+       //     + the current page plus 2, and a space
       " ... ")    //     + literal "... "
     +t            //    + the total itself
     +" next")     //    + literal " next"
    :              //   Else (current page and total amount of pages are the same):
     "")           //    Append nothing
                   // End of method (implicit / single-line return-statement)

```
> 3 votes

# Answer
# Jelly, 59 bytes

```
+2Rṫ-4>Ðḟ⁹1;;QµI’a3R”.ṁ⁸żẎ
Ị¬;n“¢©ỵY“¡&ç»ẋ"W€jçLÐfKṣ⁸j⁸WŒṘ¤

```

A full program\* printing the result to STDOUT. Takes arguments `current` and `total` in that order.

**Try it online!** or see the test-suite.

### How?

```
+2Rṫ-4>Ðḟ⁹1;;QµI’a3R”.ṁ⁸żẎ - Link 1, numbers and ellipses: current, total
                           -                                   e.g. 52, 173
 2                         - literal two                            2
+                          - add to current                         54
  R                        - range                                  [1,2,3,...,53,54]
    -4                     - literal minus four                     -4
   ṫ                       - tail from index (i.e. right five)      [50,51,52,53,54]
         ⁹                 - chain's right argument, total          173
       Ðḟ                  - filter discard if:
      >                    -  greater than?                         [50,51,52,53,54]
          1                - literal one                            1
           ;               - concatenate                            [1,50,51,52,53,54]
            ;              - concatenate (implicit right = total)   [1,50,51,52,53,54,173]
             Q             - unique (remove excess 1 and/or total)  [1,50,51,52,53,54,173]
              µ            - new monadic chain, call that X
               I           - incremental differences                [49,1,1,1,1,119]
                ’          - decrement (vectorises)                 [48,0,0,0,0,118]
                  3        - literal three                          3
                 a         - logical and (vectorises)               [3,0,0,0,0,3]
                   R       - range (vectorises)                     [[1,2,3],[],[],[],[],[1,2,3]]
                    ”.     - literal '.' character                  '.'
                      ṁ    - mould like that                        [['.','.','.'],[],[],[],[],['.','.','.']]
                       ⁸   - chain's left argument, X               [1,50,51,52,53,54,173]
                        ż  - zip with that                          [[1,['.', '.', '.']],[50,[]],[51,[]],[52,[]],[53,[]],[54,['.','.','.']],[173]]
                         Ẏ - tighten                                [1,['.', '.', '.'],50,[],51,[],52,[],53,[],54,['.','.','.'],173]

Ị¬;n“¢©ỵY“¡&ç»ẋ"W€jçLÐfKṣ⁸j⁸WŒṘ¤ - Main link: current, total   e.g. 52, 173
Ị                                - insignificant? (abs(current)<=1)  0
 ¬                               - logical not                       1
   n                             - not equal (current != total)      1
  ;                              - concatenate                       [1,1]
    “¢©ỵY“¡&ç»                   - list of compressed strings        [['p','r','e','v'], ['n','e','x','t']]
               "                 - zip with:
              ẋ                  -   repeat (zeros -> empty lists)   [['p','r','e','v'], ['n','e','x','t']]
                W€               - wrap €ach (prep for the join)     [[['p','r','e','v']], [['n','e','x','t']]]
                   ç             - call last link (1) as a dyad      [1,['.', '.', '.'],50,[],51,[],52,[],53,[],54,['.','.','.'],173]
                  j              - join                              [['p','r','e','v'],1,['.','.','.'],50,[],51,[],52,[],53,[],54,['.','.','.'],173,['n','e','x','t']]
                     Ðf          - filter keep if:
                    L            -   length (removes empty lists)    [['p','r','e','v'],1,['.','.','.'],50,51,52,53,54,['.','.','.'],173,['n','e','x','t']]
                       K         - join with spaces                  ['p','r','e','v',' ',1,' ','.','.','.',' ',50,' ',51,' ',52,' ',53,' ',54,' ','.','.','.',' ',173,' ','n','e','x','t']
                         ⁸       - chain's left argument, current    52
                        ṣ        - split at that                     [['p','r','e','v',' ',1,' ','.','.','.',' ',50,' ',51,' ',],[,' ',53,' ',54,' ','.','.','.',' ',173,' ','n','e','x','t']]
                               ¤ - nilad followed by link(s) as a nilad:
                           ⁸     -   chain's left argument, current  52
                            W    -   wrap                            [52]
                             ŒṘ  -   Python string representation    ['[','5','2',']']
                          j      - join                              ['p','r','e','v',' ',1,' ','.','.','.',' ',50,' ',51,' ','[','5','2',']',' ',53,' ',54,' ','.','.','.',' ',173,' ','n','e','x','t']
                                 - implicit print                    prev 1 ... 50 51 [52] 53 54 ... 173 next

```

* As a dyadic link taking `current` on the left and `total` on the right this returns a list with a mix of characters and integers; this list includes the spaces. The byte `K` cannot simply be removed to adhere to the spec however, since the result would then have the bracketed `current` as separate characters (like `[...'[','5','2',']'...]`) so the "convert each item to string and join them with a single space" would fail to produce the desired result)
> 3 votes

# Answer
**C++ - 247 bytes**

```
#include <iostream>
#define c std::cout<<
#define N (a-i<3?i-a<2?1:b-i:a-i-2)
void s(int a,int b){if(a>1)c"prev ";for(int i=1;i<=b&&N!=0;i+=N)c(i==1?"":" ")<<(a==i?"[":"")<<i<<(a==i?"]":"")<<(N>1?" ...":"");if(a<b-2)c" "<<b;if(a<b)c" next";c"\n";}

```

Try it online!
> 2 votes

# Answer
# Python 2, ~~178~~ 170 bytes

```
x,y=input()
e="... ",""
o=("Prev 1 ","[1] ")[y<2]+e[y<5]
for z in range(2,x):o+=("",(`z`,`[z]`)[z==y]+" ")[y-3<z<y+3]
print o+("",e[x-y<4]+(`x`+" Next",`[x]`)[y==x])[x>1]

```

Try it online!

Second attempt after reading the rules more carefully.

-8 by losing some unneeded brackets.
> 2 votes

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

*-4 bytes thanks to Jonathan Allan!*

```
lambda c,l:["prev"]*(c>1)+[range(1,c),[1,"...",c-2,c-1]][c>4]+[[c]]+[range(c+1,l+1),[c+1,c+2,"...",l]][l-c>4]+["next"]*(c<l)

```

Try it online!

Output as a list, but tio link includes pretty-print.
> 2 votes

# Answer
# C# (.NET Core), ~~195~~ 192 bytes

Saved 3 bytes thanks to Kevin Cruijssen.

```
c=>t=>{var n=c>1?"prev ":"";n+=c>4?"1 ... ":c<2?"[1] ":"1 ";if(t>1){for(int i=c-3;i++<c+2;)if(i>1&i<t)n+=i==c?$"[{i}] ":i+" ";n+=c<t-4?"... "+t:c==t?$"[{t}]":t+"";n+=c<t?" next":"";}return n;}

```

Try it online!
> 2 votes

# Answer
# CJam, 74

```
q~\:A\:B]3e*[1T4A3+1A].>["prev"1'.3*_B"next"]:a.*3/5,A2-f+B,2>&*:+_A#Aa`tp

```

Outputs as array. Try it online

Replace the final `p` with `S*` to output as string.

**Explanation:**

```
q~          read and evaluate the input (pushing 2 numbers on the stack)
\:A\:B      store the numbers in A and B, keeping them in the same order
]3e*        wrap in array, then repeat each number 3 times - [A A A B B B]
[1T4        make an array containing 1, 0 (T=0 by default), 4,
A3+1A]      then A+3, 1, and A
.>          compare the 2 arrays element by element - [A>1 A>0 A>4 B>A+3 B>1 B>A]
             (each result is 1 or 0)
["prev"1    make an array containing "prev", 1,
'.3*_       "..." twice ("..." = '.' repeated 3 times),
B"next"]    then B and "next"
:a          wrap each of its elements in an array - [["prev"][1]["..."]…]
.*          repeat each of these arrays according to the previous array
             e.g. ["prev"] is repeated A>1 times - ["prev"] if A>1, else []
             [1] is repeated A>0 times (always 1), etc.
             obtaining an array of 6 arrays, some of which may be empty
3/          split into 2 arrays of 3 arrays each (between the "..." parts)
5,A2-f+     make an array [0 1 2 3 4] then add A-2 to each element
B,2>&       intersect with the array [2 3 … B-1] (these are the middle numbers)
*           join the 2 previous arrays by adding these numbers between them
:+          concatenate all these arrays and numbers together
             obtaining an array containing only numbers and strings
_A#         duplicate the array then find the position of A in it
Aa`         generate the "[A]" string (with the actual number for A)
             by wrapping A in an array and getting its string representation
t           put it in the array at A's position
p           print the array's string representation

```
> 2 votes

# Answer
# PHP (\<7.2), ~~157~~ 150 bytes

taking the details literally turned out to be the shortest approach:

```
[,$k,$n]=$argv;for($k>1&&print"prev ";$i++<$n;)$g=in_array($i,range($k-2,$k+2)+[5=>1,$n])?!print$i-$k?"$i ":"[$i] ":$g||print"... ";$k<$n&&print next;

```

Run with `php -nr '<code>' <curpage> <numpages>` or try it online.
> 2 votes

# Answer
## Haskell, ~~145~~ 129 bytes

```
s x=show x
a#t=["prev 1"|a>1]++["..."|a>4]++map s[max 4a-2..a-1]++s[a]:map s[a+1..min(a+3)t-1]++["..."|t-a>3]++[s t++" next"|a<t]

```

Try it online!

Edit: @Ørjan Johansen saved 16 bytes. Thanks!
> 2 votes

# Answer
## Golf Script \- 104 characters

```
~\:a;:b;1a<'prev '*3a<'1 ... '*[5,{a 2-+}/]{.0>\b)<&},{.a={'['\']'}*' '}/;b a-:c 2>' ... 'b+*0c<' next'*

```

### Ungolfed

```
~\:a;:b;       # a = 1st arg, b = 2nd arg
1a<'prev '*    # if a > 1: print 'prev '
3a<'1 ... '*   # if a > 3: print '1 ... '
[5,{a 2-+}/]   # creates an array [a-2 a-1 a a+1 a+2]
{.0>\b)<&},    # keeps only elements >0 and <=b
{
  .a={'['\']'}*      # puts '[' ']' around the element equal to a
  ' '}/;             # prints each element with a leading space
b a-:c 2>' ... 'b+*  # if b-a > 2: print ' ... ' + b
0c<' next'*          # if b-a > 0: print ' next'

```
> 1 votes

# Answer
# Perl 5, ~~113+1 (-p)~~ 109 +3(-pal) bytes

```
$_=join$",1..<>;s/\b@F\b/[$&]/;s/^1/prev 1/;s/\d$/$& next/;s/(^|\] )\w+ \w+ \K[\w ]*(?= \w+ \w+( \[|$))/.../g

```

Try it online
> 1 votes

# Answer
# IBM/Lotus Notes Formula, ~~217~~ 211 Bytes

-2 with thanks to @KevinCruijssen

-4 by using variables for the @Text values

```
o:=@If(a=1;"[1]";"Prev 1 ")+@If(a>4;"... ";"");@For(x:=2;x<b;x:=x+1;T:=@Text(x);o:=o+@If(x>a-3&x<a+3;@If(a=x;"["+T+"]";T)+" ";""));Z:=@Text(b);o:=o+@If(b>1;@If(b-a>3;"... ";"")+@If(a=b;"["+Z+"]";Z+" Next");"");o

```

Basically a port of my Python 2 answer just for the fun of trying to remember how to use Formula.

There's no TIO for Formula so here's a screenshot of some of the test cases:
> 1 votes

# Answer
# Ruby, 127 bytes

I'm not particularly happy with this, especially the prev/next logic.

```
->c,t{"prev #{(1..t).chunk{|n|n<2||n==t||n>c-3&&n<c+3}.map{|t,a|t ?a:?.*3}*" "} next".sub(/(prev )?\b(#{c})\b( next)?/,'[\2]')}

```

Try it online!

## Ungolfed

```
->c,t{
  "prev #{
    (1..t)
    .chunk {|n| n < 2 || n == t || n > c - 3 && n < c + 3 }
    .map {|t,a| t ? a : ?. * 3 } * " "
  } next"
  .sub(/(prev )?\b(#{ c })\b( next)?/, '[\2]')
}

```
> 1 votes

# Answer
# Excel VBA, <sub>~~202~~</sub> 201 Bytes

Anonymous VBE immediate window function that takes input from range `A1:A2` and outputs to the VBE immediate window.

```
For i=[Max(A1-2,1)]To[Min(A1+2,A2)]:s=s &IIf([A1]=i,"[" &i &"]",i)&" ":Next:?[If(A1=1,"","prev "&If(A1>3,1&If(A1>4," ... "," "),""))]s[If(A1<A2,If(A1-A2<-3,"... ","")&If(A1-A2<-2,A2&" ","")&"next","")]

```

### Subroutine Version

*Included for readablity*

```
Public Sub PageSelect(Optional ByVal Current As Long = -1, _
                      Optional ByVal Total   As Long = -1)

    Call Sheet1.Activate

    Let [A1] = IIf(Current = -1, [A1], Current)
    Let [A2] = IIf(Total   = -1, [A1], Total)

    Dim s As String
    Let s = ""

    For i = [Max(A1-2,1)] To [Min(A1+2,A2)] Step 1
        Let s = s & IIf([A1] = i, "[" & i & "]", i) & " "
    Next
    Debug.Print [If(A1=1,"","prev "&If(A1>3,1&If(A1>4," ... "," "),""))]; _
                s; _
                [If(A1<A2,If(A1-A2<-3,"... ","")&If(A1-A2<-2,A2&" ","")&"next","")]
End Sub

```
> 1 votes

# Answer
# PHP (Browser), 267 Bytes

```
<?php parse_str($_SERVER['QUERY_STRING']);$c=$a!=1?$a>3?$a>4?'prev 1 . . . ':'prev 1 ':'prev ':'[1] ';$d=$a<$b-2?$a+3:$b;for($i=$a<=2?$a==1?$i=2:$i=$a-1:$i=$a-2;$i<$d;$i++)$c.=$a==$i?"[$i] ":"$i ";if($a<$b-2)$c.=" . . . $b next";else $c.=$a==$b?"[$b]":"$b next";echo $c?>

```

Try it online!

Definitely not as small as it could have been, and as was demonstrated above, using PHP in command line can be much smaller. The input is through GET requests, a is the selected number, b is the limit. This looks like `foo.bar.com/index.php?a=2&b=12`

# Ungolfed

```
<?
    parse_str($_SERVER['QUERY_STRING']);
    $c=$a!=1?$a>3?$a>4?'prev 1 . . . ':'prev 1 ':'prev ':'[1] ';
    $d=$a<$b-2?$a+3:$b;
    for($i=$a<=2?$a==1?$i=2:$i=$a-1:$i=$a-2;$i<$d;$i++)
        $c.=$a==$i?"[$i] ":"$i ";

    if($a<$b-2)$c.=" . . . $b next";else
    $c.=$a==$b?"[$b]":"$b next";
    echo $c
?>

```

I am pretty sure my ternary operators can be improved, feel free to try.
> 1 votes

# Answer
## C - 173 Bytes

```
#define p c&&printf(
c;main(t){scanf("%u%u",&c,&t);c&&t/c?1-p"prev 1"),3<p" ... %d",c-2),2<p" %d",c-1),1|p" [%d] ",c),t>1+p"%d ",c+1),t>2+p"%d ... ",c+2),t-p"%d next",t):0;}

```

Thanks to @ceilingcat for -45 bytes.

**Ungolfed (original version)**

```
#define p printf
c;

main(t)
{
    scanf("%u%u", &c, &t);

    if(1 <= c && c <= t)
    {
        p(c != 1 ?"prev 1" :"");

        p(c - 2 > 1 ?" ... %d" :"", c - 2);
        p(c - 1 > 1 ?" %d" :"", c - 1);

        p(" [%d] ", c);

        p(c + 1 < t ?"%d " :"", c + 1);
        p(c + 2 < t ?"%d ... " :"", c + 2);

        p(c != t ?"%d next" :"", t);
    }
}

```
> 1 votes

# Answer
# PowerShell, 237 bytes

```
param($a,$n)('prev 1','[1]')[$n-lt2]+" ... $($n-2) $($n-1) [$n]"*($n-gt4)+" 2 3 [4]"*($n-eq4)+" 2 [3]"*($n-eq3)+" [2]"*($n-eq2)+" $($n+1) $($n+2) ..."*($n-lt$a-3)+" $($n+1) $($n+2)"*($n-eq$a-3)+" $($n+1)"*($n-eq$a-2)+" $a next"*($n-ne$a)

```

Try it online!

One gigantic string concatenation with way too many dollar signs. ~~Working on golfing further.~~ Nope, I think this is as short as this approach can go.
> 0 votes

# Answer
# Javascript (ES6), ~~265~~ ~~263~~ ~~258~~ ~~240~~ ~~239~~ ~~220~~ ~~194~~ ~~193~~ ~~182~~ 178 bytes

*-2 from removing a debug tool*

*-5 from realizing that I'm using ES6 and can do away with parenthesis sometimes*

*-18 from removing something from an earlier version that is now obsolete*

*-1 from doing some sneaky stuff*

*-19 from removing unnecessary variables*

*-26 bytes from removing the all too complicated remove falsey values. I'm new to ES6*

*-1 from using shorter comparisons*

*-11 from using a recursive function*

\*-4 from replacing `?...:0` with `&&...`, and `... ${t}` with `...+t`

This took way too much of my life, and didn’t give enough upvotes.  ~~but I am so glad the final code is a power of 2 (2^8)~~ I do know there is another JavaScript answer that is about 120 bytes.  ~~but I still love this code~~

**EDIT: i don't know what i was thinking. 265 is not 2^8...**

While making this, I managed to break the ungolfed version. God, do I hate ungolfing code.

**EDIT 2: now it's looking like the better 121 byte solution**

```
y=(e,i,t="")=>i++<e?y(e,i,t+i+' '):t.slice(0,-1);m=(t,p)=>[p-1&&"prev",p<5?y(p-1,0):"1 ... "+y(p-1,p-3),`[${t}]`,t-p<4?y(t,p):y(p+2,p)+` ... `+t,t-p&&"next"].filter(e=>e).join` `

```

Explanation:

to come but basically y is `range(end, start)` and it does some cool stuff like:

1. show prev if `page` is 1
2. show left dots if `page > 4`
3. show right dots if `total - page < 4`
4. show next if `total - page == 0`

and stuff like that and just joins it by ' '. I know you don't have to but I like the fact that is semi-conventional. I don't know. Enjoy.

Try it online!

Validate it online!

Here's a ~~186~~ ~~185~~ ~~174~~ 170 byte solution that I don't like: Try it online!
> 0 votes

# Answer
# PowerShell, 141 bytes

```
param($c,$t)($('prev'*($c-ne1)
1
'...'*($c-gt4)
($c-2)..($c+2)-gt1-lt$t
'...'*($t-$c-gt4)
$t
'next'*($t-ne$c))|?{$_}|gu)-replace"^$c$","[$c]"

```

Try it online!

Less golfed:

```
param($current,$total)
$uiElements=$(
    'prev'*($current-ne1)
    1
    '...'*($current-gt4)
    ($current-2)..($current+2)-gt1-lt$total
    '...'*($total-$current-gt4)
    $total
    'next'*($total-ne$current)
)
($uiElements|where{$_}|Get-Unique)-replace"^$current$","[$current]"

```
> 0 votes

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