title: Find the biggest chunk

text:
# Question
Title: Find the biggest chunk
> *This challenge is **not** code golf. Please read the scoring before you attempt to submit an answer.*

You will be given a multi-line string as input. You should output the *size of the largest contiguous chunk* of non-space characters. Contiguous just means that the chunk is a single piece rather than multiple disconnected pieces.

Characters are adjacent to characters directly before and after then in the same row or column. So this means that chunks cannot be connected via diagonals only.

```
alskdm
askl  so
mmsu  89s
    ks2mks
   3klsl

```

These two chunks are disconnected the bigger one has 16 characters.

You must support all printable ASCII plus space and newline. If your program includes any characters outside of this range you must support those characters too. Nothing else needs to be supported. The input will contain at least 1 non-space character and may have trailing spaces on lines.

## Scoring

Answers will be scored first on the size of their own largest chunk with lower score being better. As a tie breaker they will be scored simply in their total length with lower score being better.

## Test cases

If you want to copy and paste them you can view the source here.

```
a
=> 1
a a
=> 1
a
a
=> 2
5a $
a  @
=> 3
yus
8  2
   3
=> 4
323

ke
=> 3
alskdm
askl  so
mmsu  89s
    ks2mks
   3klsl
=> 16

```

# Answer
# BQN, score 1, ~~125~~ ~~112~~ 108 bytesSBCS

```
 { ⌈ ´ + ˝ ∨ ˝ ∘ × ⎉ 1 ‿ ∞ ˜ ⍟ ≠ 2 > + ´ ∘ | ∘ - ⌜ ˜ '
' ( + ´ ∘ = ∾ ⊐ ˜ ) ¨ ( ' ' < ⊑ ) ¨ ⊸ / ⌽ ¨ 1 ↓ ↑  }

```

Run online!

`1↓↑` Non-empty prefixes of the input.
`⌽¨` Reverse each prefix.
`(' '<⊑)¨⊸/` Keep the prefixes that don't start with whitespace.
`'␤'(+´∘=∾⊐˜)¨` For each prefix, get ⟨*number of newlines*, *index of newline*⟩. These are the 1-based coordinates of non-space characters.
`2>+´∘|∘-⌜˜` Convert the coordinate list to an adjacency matrix.
`∨˝∘×⎉1‿∞˜⍟≠` *OR* matrix power to 2^length.
`⌈´+˝` Maximum number of 1s in a single row.
> 6 votes

# Answer
# JavaScript (Node.js), score 3, ~~628~~ 518 bytes

```
(n, S= 'm' + 'a' + 'p' , T= 'f' + 'l' + 'a' + 't' + 'M' + 'a' + 'p' , L= 'l' + 'e' + 'n' + 'g' + 't' + 'h' , R=n [ 's' + 'p' + 'l' + 'i' + 't' ](' \n '[ 's' + 'l' + 'i' + 'c' + 'e' ]( 1,2 ))[ S ](e =>[ ... e]) )=> R[ S ](( e,i ) => e[S ](( E,I ) =>k =( G= (F= l=> ( M=R [ T ](( a,b ) => a[ T ](( A,B ) => l [ 's' + 'o' + 'm' + 'e' ](j => (j[ 0]- b<0 ?b- j[ 0]: j[ 0]- b)+ (j[ 1]- B<0 ?B- j[ 1]: j[ 1]- B)< 2) &&A !=' '? [[b , B]] : [ ])) )[ L ]== l[ L ]?M [ L ] :F( M)) ([[ i,I ]]) ) > k&& E !=' '?G :k ) , k = 0 ) | k

```

Try it online!

Assuming I've interpreted the rules correctly, this has a score of 3 (the longest contiguous non-space chunk has 3 characters, and there are a lot of 3-char chunks). Pretty long, however, and if it were code-golf the length would be more like 400.

Explanation: we have a counter `k` which holds the max size. It is initially set at 0. We loop through each non-space character and in each case, we capture the chunk that contains that character. If its size is bigger than `k`, we set `k` to its size. Eventually `k` will hold the biggest one and we just return that.

To capture the chunk containing some character, start with the character in question, then we get the adjacent ones and add them to the list. We then get the adjacent ones to the characters in this bigger list, and add them to the list, etc etc, until no more characters are added. The list now represents the chunk which contains the character in question.
> 4 votes

# Answer
# Python 3, score=3, 320 bytes

```
def f(L ,m= 0,i =-1 ):

 for l in L:

  i+= 1;j =0

  for _ in l:

   V=[ 0]; g(L ,i, j,V );m = max (m, V[0 ]); j+= 1

 L [:] =m,

def g(L ,i, j,V ):

 if len (L) >i> -1 <j< len (L[ i]) !=( i,j ) not in V!= ' ' <L[ i][ j]:

  V[0 ]+= 1;V +=( i,j ),

  for x,y in [(0 ,1) ,(0 ,-1 ),( 1,0 ),( -1, 0)] :g( L,i +x, j+y ,V)

```

Try it online!

The function `f` takes in a list of strings `L` as input. Outputs by modifying `L` to becomes `[answer]` (a list containing the answer as the only element).

# Big idea

This is a straightforward DFS implementation. `g(L,i,j,V)` is the recursive DFS part, taking in the lines `L`, the coordinates `i, j` and the list of visited coordinates `V`.

To get a score of 3, the following features become unavailable:

* `eval` and `exec`: we cannot do any string manipulation of the source code
* `import`: no library outside of built in functions and operators
* `input`: we cannot get input from STDIN. Thus we cannot write a full program, and instead must answer with a function
* `lambda`: cannot create lambda function, so we must relies on `def`. Luckily `def` is usable.
* `print`, `return` and `exit`: this leaves modifying function arguments as the only output method.

Fortunately, `for` and `if` are available for flow control.

# More details

`V` is originally the list of visited coordinates, however for convenience I reserve `V[0]` to store the current size of the chunk. Thus `g` returns by incrementing `V[0]` by 1 every time it finds a new valid coordinate.
> 4 votes

# Answer
# Jelly, score 1, 51 bytes

```
Ỵ n ⁶ T € ṭ € " J $ Ẏ W ạ § Ị Ẹ ʋ Ƈ @ Ƭ Ẉ ɗ € ` F Ṁ

```

A monadic Link accepting a list of characters that yields the size of the biggest chunk.

**Try it online!** Or see the test-suite (cases split with `=`).

### How?

We can place spaces between instructions in Jelly without affecting the code (literals being single instructions). Unfortunately, many useful instructions for this challenge are two bytes long - for example: getting truthy multidimensional indices; forming powersets; matrix multiplication, determinants or powers. So, we just have to use the basics here.

```
Ỵn⁶T€ṭ€"J$ẎWạ§ỊẸʋƇ@ƬẈɗ€`FṀ - Link: list of characters, X
Ỵ                          - split X at newline characters
 n⁶                        - not equal space character? (vectorises)
   T€                      - truthy indices of each
         $                 - last two links as a monad:
        J                  -   range of length -> row_numbers
       "                   -   zip with:
     ṭ€                    -     tack each -> coordinates
          Ẏ                - tighten -> list of coordinates
                       `   - use as both arguments of:
                     ɗ€    -   for each, last three links as a dyad:
           W               -     wrap -> our initial list of collected coordinates
                   Ƭ       -     collect inputs up while they're distinct:
                  @        -       with swapped arguments:
                 Ƈ         -         keep those (of all coordinates) for which:
                ʋ          -           last four links as a dyad
            ạ              -             absolute difference
                                           (vectorises across collected coordinates)
             §             -             sums -> Manhatten distances
              Ị            -             -1 <= x <= 1? (vectorises)
               Ẹ           -             any?
                    Ẉ      -     length of each
                        F  - flatten
                         Ṁ - maximum

```
> 3 votes

# Answer
# Charcoal -v, score 6, 305 bytes

```
while Input Push u i Assign []q for Map u Map i[k, m, l] for i if Less " " Pop k Push q k Assign 0 h while q{ Assign [Pop q]z while Filter Minus q z Filter 4 Count z Map l Plus p And Equals r Modulo n 2 Minus Minus n r 1 for k Push z l Assign Minus q z q if Less h Length z Assign Length z h} Print Cast h

```

Try it online! Takes input as a list of newline-terminated strings. Readable version:

```
while (Input()) Push(u, i);
Assign([], q);
for (Map(u, Map(i, [k, m, l]))) for (i) if (Less(" ", Pop(k))) Push(q, k);
Assign(0, h);
while (q) {
    Assign([Pop(q)], z);
    while (Filter(Minus(q, z), Filter(4, Count(z, Map(l, Plus(p, And(Equals(r, Modulo(n, 2)), Minus(Minus(n, r), 1))))))))
        for (k) Push(z, l);
    Assign(Minus(q, z), q);
    if (Less(h, Length(z))) Assign(Length(z), h);
}
Print(Cast(h));

```

Try it online! Explanation:

```
while (Input()) Push(u, i);

```

Input the multiline string as a list of strings.

```
for (Map(u, Map(i, [k, m, l]))) for (i) if (Less(" ", Pop(k))) Push(q, k);

```

Create a list of coordinates of all of the non-blank characters.

```
Assign(0, h);

```

Start tracking the maximum chunk size.

```
while (q) {

```

Loop until all of the coordinates have been assigned to a chunk.

```
    Assign([Pop(q)], z);

```

Start a new chunk.

```
    while (Filter(Minus(q, z), Filter(4, Count(z, Map(l, Plus(p, And(Equals(r, Modulo(n, 2)), Minus(Minus(n, r), 1))))))))

```

While there are coordinates not in the chunk that are adjacent to at least one coordinate in the chunk, ...

```
        for (k) Push(z, l);

```

... add all of the discovered coordinates to the chunk.

```
    Assign(Minus(q, z), q);

```

Remove the chunk from the coordinates.

```
    if (Less(h, Length(z))) Assign(Length(z), h);

```

Update the maximum chunk size if necessary.

```
}
Print(Cast(h));

```

Output the maximum chunk size.
> 2 votes

# Answer
# JavaScript (ES7), score 3, 211 bytes

```
s =>( o=g =(X ,Y) =>m . map ((r ,y) =>r . map ((c ,x) =>c ==' '|| (1/ Y?( X-x )** 2+( Y-y )** 2-1 :k= 0) || g(x ,y, o=o >++ k?o :k, r[x ]=' ')) ))( m=s [ 's' + 'p' + 'l' + 'i' + 't' ]`
`
. map (s =>[ ... s]) )|o

```

Try it online!

### Commented

In the final code, we use `[ 's' + 'p' + 'l' + 'i' + 't' ]` instead of `split` and a literal line feed instead of `\n`. Everything else is just extra spaces all over the place.

```
s => (                   // s = input string
  o =                    // initialize o to a zero'ish value
  g =                    // g is a recursive function taking
  (X, Y) =>              // the current position (X, Y)
  m.map((r, y) =>        // for each row r[] at position y in m[]:
    r.map((c, x) =>      //   for each character c at position x in r[]:
      c == ' ' || (      //     do nothing if c is a space
        1 / Y ?          //     otherwise, if Y is defined:
          (X - x) ** 2 + //       make sure that the quadrance between
          (Y - y) ** 2   //       (X, Y) and (x, y)
          - 1            //       is equal to 1
        :                //     else:
          k = 0          //       reset k to 0
      ) ||               //     if the above is falsy:
      g(                 //       do a recursive call:
        x, y,            //         pass the new position (x, y)
        o =              //         update o to ...
        o > ++k ? o : k, //         max(o, k) where k is pre-incremented
        r[x] = ' '       //         put a space at the new position
      )                  //       end of recursive call
    )                    //   end of inner map()
  )                      // end of outer map()
)(                       // initial call to g:
  m =                    //   initialize m[] to
  s.split`\n`            //   the input string split by new lines
  .map(s => [...s])      //   and each row turned into a list of chars.
) | o                    // end of call: return o

```
> 1 votes

# Answer
# JavaScript (Node.js), score 1, ~~626~~ 613 bytes

```
 [ L = `
` , s = ' s ' [ 1 ] , l = ' l ' [ 1 ] , c = ' c ' [ 1 ] , o = ' o ' [ 1 ] , t = ' t ' [ 1 ] , r = ' r ' [ 1 ] , n = ' n ' [ 1 ] , i = ' i ' [ 1 ] ] [ ' f ' [ 1 ] + i + l + l ] [ c + o + n + ' s ' [ 1 ] + t + r + ' u ' [ 1 ] + c + t + o + r ] ( W = ' o ' , ` g = ( X , Y ) = > s . m a p ( ( r , y ) = > r . m a p ( ( c , x ) = > c > W ? ( x - X ) * * 2 + ( Y - y ) * * 2 - 1 | | g ( x , y , k = 1 / Y ? k + 1 : 1 , r [ x ] = o = o > k ? o : k ) : 0 ) )
 g ( s = o . s p l i t ( L ) . m a p ( t = > [ . . . t ] ) )
r e t u r n + o ` [ s + ' p ' [ 1 ] + l + i + t ] ` ` [ ' j ' [ 1 ] + o + i + n ] ( [ ] ) )

```

Try it online!

That's what I meant "something like jsfuck". Can only define function using "constructor". Other code quite like Arnauld's besides that I forgot that `=>` is 2 char
> 1 votes

# Answer
# Python SciPy, score 8, 167 bytes

```
lambda x:max( bincount (label( ((a:= array([x .split( "\n")]). T.view( "U1"))!= " ")&(a !="\x00" ))[0]. ravel()) [1:])

from scipy. ndimage import*

from numpy import*
```

Attempt This Online!

Leaves the chunking to `scipy.ndimage.label`. The chunk sizes are extracted by `numpy.bincount` which is also the longest function name used at 8 characters
> 0 votes

# Answer
# 05AB1E, score 1, ~~107~~ 101 bytes

```
S ¶ ¡ ζ ζ ð Ê Ð U ˜ ƶ s g ä Δ ε 0 š Ć } ¬ 0 * š Ć 2 F ø € ü 3 } X * ε ε 1 è y ø 1 è « à ] ˜ 0 K D ¢ à

```

Try it online or verify all test cases.

**Explanation:**

Most of it is similar as my 05AB1E answer for the *Is there a stable way to stack these?* challenge, except that `0δ.ø` is `ε0šĆ}` and `Ås` is , since the 2-byte builtins  and `Ås` cannot be separated to minimize the score. (Also, `S¶¡ζζ` could have been `.B€S`, but `.B` is a 2-byte builtin as well.)

Step 1. Convert the input to a matrix of characters:

```
S       # Convert the (implicit) input-string to a list of characters
 ¶¡     # Split it on newlines to a character-matrix

```

Step 2. Right-pad this input-matrix with spaces:

```
ζ       # Zip/transpose the input-matrix; swapping rows/columns,
        # using a space as filler if the rows are of unequal length
 ζ      # Zip/transpose back

```

Step 3. Transform all spaces to `0` and all other characters to `1`:

```
ðÊ      # Check for each character whether it's NOT a space
        # (0 if a space; 1 otherwise)
  Ð     # Triplicate the matrix
   U    # Pop and store a copy in variable `X`

```

Step 4. Create a matrix of the same size with unique positive integers:

```
˜       # Flatten the matrix
 ƶ      # Multiply every 1 by its 1-based index
  s     # Swap so the matrix is at the top
   g    # Pop and push its length (amount of rows)
    ä   # Split the list into that many equal-sized parts

```

Step 5. Flood-fill this matrix based on the matrix of 0s/1s we stored in variable `X`:

```
Δ       # Loop until the matrix no longer changes:

```

Step 5.1: Add a border of 0s around the matrix:

```
 ε      #  Map over each row:
  0š    #   Prepend a 0
    Ć   #   Enclose; append its own head
 }      #  Close the map
  ¬     #  Push the first row (without popping the matrix)
   0*   #  Transform all 0s/1s to 0s by multiplying by 0
     šĆ #  Prepend and enclose this row as well

```

Step 5.2: Create overlapping 3x3 blocks of this matrix:

```
 2F     #  Loop 2 times:
   ø    #   Zip/transpose; swapping rows/columns
    €   #   Map over each row:
     ü3 #    Pop and push its overlapping triplets
  }     #  Close the loop

```

Step 5.3: Transform the `0`s back, based on the matrix of variable `X`:

```
   X*   #  Multiply the values at the same positions by matrix `X`

```

Step 5.4: For each 3x3 block, get the maximum of its center and its horizontal/vertical neighbors:

```
 εε     #  Nested map over the 3x3 blocks:
   1è   #   Get the middle row
   yø1è #   As well as the middle column
   «    #   Merge these triplets together
   à    #   Pop and push the maximum of this list
]       #  Close the nested maps and until_no_changes loop

```

Step 6: Check which island is the largest:

```
˜       # Flatten the matrix to a list
 0K     # Remove all 0s
   D    # Duplicate this list
    ¢   # Count each value
     à  # Pop and push the maximum
        # (after which it is output implicitly as result)

```
> 0 votes

# Answer
# Pip `-r`, score 1, 181 bytes

```
g M : 1 - { _ Q s M a } + $ + : ^ 0 X # _ M g W J % : g { i : # : K 0 ~ J g ( g i / Y # @ g i % y ) : 2 L y + # g g : Z ( J * g ) R K 1 . 2 . K 1 2 X # _ Y 2 N J g I y > x x : y } x

```

Takes input from stdin. Attempt This Online! (Runs all of the test cases easily, but times out if passed its own source code.)

### Explanation

Several operators that would have been useful are two characters (`ZD`, `MM`, `MX`, `@?`), so we have to work around them.

```
gM:1-{_QsMa}+$+:^0X#_Mg
g                        List of lines of stdin (due to -r flag)
 M:                      Map this function to each line in-place:
     {   Ma}              Map this function to each character of the line:
      _Qs                  Is it equal to space? (1 if so, 0 if not)
   1-                     Subtract each result from 1, swapping 1s with 0s
            +             Pad each line to the same length by adding the following:
                     Mg    Map this function to each line of the input:
                   #_       Length of the line
                 0X         String of that many zeros
                ^           Split into a list of digits
             $+:           Sum down the columns of the resulting list of lists

```

Here's a demonstration of how the padding logic works:

```
         g  ["ab"; "cde"; ""; "f"]
      #_M   [2; 3; 0; 1]
    0X      [00; 000; ""; 0]
   ^        [[0; 0]; [0; 0; 0]; []; [0]]
$+:         [0; 0; 0]

```

When two lists of different lengths are added, the part of the longer one that sticks out past the end of the shorter one is included in the result unchanged. Thus, summing the list of lists gives us the longest list-of-zeros in it, and adding that list to each processed row from the input essentially right-pads it with zeros to match the length of the longest row.

```
W J%:g{...}x
W             Loop while
     g         g, which is now a list of lists of integers
   %:          Take each of those numbers mod 2 in-place
  J            Join them together into a single string
              is truthy (i.e. not all 0s):
      {...}    (see below)
           x  After the loop, x holds the max chunk size; output it

```

The initial value of `x` is `""`, which is equivalent to 0 in numeric contexts. Since the maximum chunk is of size at least 1, the value of `x` will always be updated, so we don't have to worry about the possibility of outputting its initial value.

Our flood-fill algorithm finds a chunk of 1s and turns them into 2s. The mod-2 operation at the beginning of the loop then turns these 2s into 0s. Once all chunks have been found, `g` is entirely 0s, at which point the loop halts.

Inside the loop, the first thing we do is find a 1 and change it to 2:

```
i:#:K0~Jg (gi/Y#@gi%y):2
       Jg                 Join g into a single string
      ~                   Find the first regex match of
    K0                    0, zero or more times (equivalent to `0*`)
  #:                      Length of that match
                          This is the row-major flat index of the first nonzero entry in g
i:                        Store it in i
                @g        First row in g
               #          Length
              Y           Yank that value into y
          (g         )    Index into g at
            i/             Row: i/y
                  i%y      Column: i mod y
                      :2  Set the element at that location to 2

```

Then we flood-fill by changing every run of 1s adjacent to a 2 to a run of 2s, swapping rows for columns, and repeating several times:

```
Ly+#g g:Z(J*g)R K1 .2.K1 2X#_
L                              Loop
 y                              Length of first row in g (width of grid)
  +                             Plus
   #g                           Length of g (height of grid)
                               times:
          J*g                   Join each row in g into a single string
         (   )R                 Replace each match of this regex:
                K1               1, zero or more times
                   .2            Followed by 2
                     .K1         Followed by 1, zero or more times
                                with this callback function:
                           #_    Length of match
                         2X      String of that many 2s
        Z                       Zip (transpose) the resulting list of strings
                                (note: it becomes a list of lists of digits again)
      g:                        Assign back to g

```

Finally, we get the size of the chunk we just found and update `x` if the chunk size is bigger:

```
Y2N Jg Iy>xx:y
    Jg          Join g into a single string
 2N             Count the number of 2s
Y               Yank that value into y
       I        If
        y>x     y (chunk size) is greater than x (previous max chunk size):
           x:y   Set x to y

```
> 0 votes

---
Tags: source-layout, self-scoring
---


title: Triangulating Text

text:
# Question
Title: Triangulating Text
Write a program or function that takes in a string guaranteed to only contain printable ASCII characters except for space, and to be a positive triangular number (1, 3, 6, 10, 15, ...) in length.

Print or return the same string, but shaped into a triangle using spaces. Some examples will best show what I mean:

If the input is `R` then the output will be

```
R

```

If the input is `cat` then the output will be

```
 c
a t

```

If the input is `monk3y` then the output will be

```
  m
 o n
k 3 y

```

If the input is `meanIngfu1` then the output will be

```
   m
  e a
 n I n
g f u 1

```

If the input is `^/\/|\/[]\` then the output will be

```
   ^
  / \
 / | \
/ [ ] \

```

If the input is

```
Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork?Youtellme,Ican'tcountverywell,ok?

```

then the output will be

```
              T
             h i
            s r u
           n o f c
          h a r a c
         t e r s i s
        m e a n t t o
       h a v e a l e n
      g t h t h a t c a
     n b e e x p r e s s
    e d a s a t r i a n g
   u l a r n u m b e r . D
  i d i t w o r k ? Y o u t
 e l l m e , I c a n ' t c o
u n t v e r y w e l l , o k ?

```

Basically, newlines are inserted between the substrings of triangular length, spaces are added between all characters, and each line is indented with spaces to fit the triangle shape.

A single trailing newline and lines with trailing spaces are optionally allowed, but otherwise your output should exactly match these examples. The last line of the triangle should not have leading spaces.

**The shortest code in bytes wins.**

# Answer
# Pyth, 22 bytes

```
jua+L\ GjdHfTczsM._UzY

```

Try it online: Demonstration or Test Suite

### Explanation:

```
jua+L\ GjdHfTczsM._UzY   implicit: z = input string
                   Uz    create the list [0, 1, ..., len(z)-1]
                 ._      all prefixes of this list: [[0], [0,1], [0,1,2], ...]
               sM        sum up each sublist: [0, 1, 3, 6, 10, ...]
             cz          split z at these indices
           fT            remove all the unnecessary empty strings
                         this gives us the list of strings of the triangle
 u                   Y   reduce this list, with the initial value G = []
   +L\ G                    prepend a space to each string in G
        jdH                 join the current string with spaces
  a                         and append it to G
j                        print each string on a separate line

```
> 9 votes

# Answer
## Python, 81 bytes

```
def f(s,p=''):
 i=-int(len(2*s)**.5)
 if s:f(s[:i],p+' ');print p+' '.join(s[i:])

```

A recursive function. Goes from the end of `s`, chopping off and printing characters. The number of characters to take is computed from the length of `s`. The function is set up to prints in reverse order of the recursive calls, which terminate when `s` is empty and then resolve back up the line. Each layer, the prefix `p` has an extra space added.

In Python 3, the `if` can be done via short circuiting, though this doesn't seem to save chars:

```
def f(s,p=''):i=-int(len(2*s)**.5);s and[f(s[:i],p+' '),print(p+' '.join(s[i:]))]

```

An equally-long alternative with inequality chaining:

```
def f(s,p=''):i=-int(len(2*s)**.5);''<s!=f(s[:i],p+' ')!=print(p+' '.join(s[i:]))

```

Both `print` and `f` return `None`, which is hard to use.
> 13 votes

# Answer
# Candy, ~~67~~ ~~59~~ 57 bytes

~~`&iZ1-=yZ1+Z*2/>{0g}0=z@1i&{|.}bYR(" ";=)ZR(=a&{;}" ";)"\n";Y1-=ya1j`~~

~~`&1-8*1+r1-2/=y@1i&{|.}bYR(" ";=)ZR(=a&{;}" ";)"\n";Y1-=ya1j`~~

`&8*7-r1-2/=y@1i&{|.}bYR(" ";=)ZR(=a&{;}" ";)"\n";Y1-=ya1j`

or:

```
          &
         8 *
        7 - r
       1 - 2 /
      = y @ 1 i
     & { | . } b
    Y R ( "   " ;
   = ) Z R ( = a &
  { ; } "   " ; ) "
 \ n " ; Y 1 - = y a
1 j

```

long form:

```
stackSz
digit8    # Y = (sqrt((numCh - 1) * 8 + 1) - 1) / 2   using pythagorean
mult      # Y = (sqrt(numCh * 8 - 7) - 1) / 2  equivalent but shorter
digit7
sub
root
digit1
sub
digit2
div
popA
YGetsA
label digit1
incrZ
stackSz   # bail if we're out of letters
if
  else
  retSub
endif
stack2
pushY     # print the leading spaces (" " x Y)
range1
while
  " " printChr
  popA
endwhile
pushZ
range1      # output this row of characters (Z of them)
while
  popA
  stack1
  stackSz
  if
    printChr    # bail on unbalanced tree
  endif
  " " printChr
endwhile
"\n" printChr
pushY
digit1
sub
popA
YGetsA
stack1
digit1 jumpSub   # loop using recursion

```
> 6 votes

# Answer
## Retina, ~~108~~ ~~102~~ ~~94~~ ~~87~~ ~~82~~ ~~64~~ 63 bytes

Thanks to Sp3000 for making me pursue my original approach, which brought the byte count from 108 down to 82.

*Massive thanks to Kobi who found a much more elegant solution, which allowed me to save another 19 bytes on top of that.*

```
S_`(?<=^(?<-1>.)*(?:(?<=\G(.)*).)+)
.
$0
m+`^(?=( *)\S.*\n\1)
<space>

```

Where `<space>` represents a single space character (which would otherwise be stripped by SE). For counting purposes, each line goes in a separate file and `\n` should be replaced with an actual linefeed character. For convenience, you can run the code as is from a single file with the `-s` flag.

Try it online.

### Explanation

Well... as usual I can't give a full introduction to balancing groups here. For a primer see my Stack Overflow answer.

```
S_`(?<=^(?<-1>.)*(?:(?<=\G(.)*).)+)

```

The first stage is a `S`plit stage, which splits the input into lines of increasing length. The `_` indicates that empty chunks should be omitted from the splitting (which only affects the end, because there will be a match in the last position). The regex itself is entirely contained in a look-around so it won't match any characters, but only positions.

This part is based on Kobi's solution with some additional golfitude I found myself. Note that lookbehinds are matched right-to-left in .NET, so the following explanation should best be read bottom to top. I've also inserted another `\G` in the explanation for clarity, although that isn't necessary for the pattern to work.

```
(?<=
  ^         # And we ensure that we can reach the beginning of the stack by doing so.
            # The first time this is possible will be exactly when tri(m-1) == tri(n-1),
            # i.e. when m == n. Exactly what we want!
  (?<-1>.)* # Now we keep matching individual characters while popping from group <1>.
  \G        # We've now matched m characters, while pushing i-1 captures for each i
            # between 1 and m, inclusive. That is, group <1> contains tri(m-1) captures.
  (?:
    (?<=
      \G    # The \G anchor matches at the position of the last match.
      (.)*  # ...push one capture onto group <1> for each character between here
            # here and the last match.
    )       # Then we use a lookahead to...
    .       # In each iteration we match a single character.
  )+        # This group matches all the characters up to the last match (or the beginning
            # of the string). Call that number m.
)           # If the previous match was at position tri(n-1) then we want this match
            # to happen exactly n characters later.

```

I'm still admiring Kobi's work here. This is even more elegant than the prime testing regex. :)

Let's move on to the next stage:

```
.
$0

```

Simple: insert a space after every non-linefeed character.

```
m+`^(?=( *)\S.*\n\1)
<space>

```

This last stage indents all the lines correctly to form the triangle. The `m` is just the usual multiline mode to make `^` match the beginning of a line. The `+` tells Retina to repeat this stage until the string stops changing (which, in this case means that the regex no longer matches).

```
^      # Match the beginning of a line.
(?=    # A lookahead which checks if the matched line needs another space.
  ( *) # Capture the indent on the current line.
  \S   # Match a non-space character to ensure we've got the entire indent.
  .*\n # Match the remainder of the line, as well as the linefeed.
  \1   # Check that the next line has at least the same indent as this one.
)

```

So this matches the beginning of any line which doesn't have a bigger indent than the next. In any such position we insert a space. This process terminates, once the lines are arranged in a neat triangle, because that's the minimal layout where each line has a bigger indent than the next.
> 6 votes

# Answer
## CJam, ~~27~~ 26 bytes

*Thanks to Sp3000 for saving 1 byte.*

```
Lq{' @f+_,)@/(S*N+a@\+\s}h

```

~~Surprisingly close to Pyth, let's see if this can be golfed...~~

Test it here.

### Explanation

```
L        e# Push an empty array to build up the lines in.
q        e# Read input.
{        e# While the top of the stack is truthy (non-empty)...
  ' @f+  e#   Prepend a space to each line we already have.
  _,)    e#   Get the number of lines we already have and increment.
  @/     e#   Split the input into chunks of that size.
  (S*    e#   Pull off the first chunk (the next line) and join with spaces.
  N+     e#   Append a linefeed.
  a@\+   e#   Append it to our list of lines.
  \s     e#   Pull up the other chunks of the input and join them back into one string.
}h

```
> 5 votes

# Answer
# Ruby, ~~84~~ ~~77~~ 73 bytes

```
->v{1.upto(n=v.size**0.5*1.4){|i|puts" "*(n-i)+v[i*(i-1)/2,i].chars*" "}}

```

**77 bytes**

```
->v{0.upto(n=(v.size*2)**0.5-1){|i|puts" "*(n-i)+v[i*(i+1)/2,i+1].chars*" "}}

```

Reduced few more bytes by removing variable `r` as suggested by steveverrill.

**84 bytes**

```
->v{n=(v.size*2)**0.5-1;0.upto(n){|i|puts" "*(n-i)+v[(r=i*(i+1)/2)..r+i].chars*" "}}

```

**Ungolfed:**

```
->v {
  1.upto(n=v.size**0.5*1.4) { |i|
    puts" "*(n-i)+v[i*(i-1)/2,i].chars*" "
  }
}

```

First calculating triangular number from the input string

```
n=v.size**0.5*1.4

```

i.e. for example input string size is 120 and our triangular number n, will be 15.

```
puts" "*(n-i)+v[i*(i-1)/2,i].chars*" "

```

In the above line, it prints spaces followed by series of string which are fetched from the input string using following pattern

`[[0,0],[1,2],[3,5],[6,9]]`

**Usage:**

```
f=->v{1.upto(n=v.size**0.5*1.4){|i|puts" "*(n-i)+v[i*(i-1)/2,i].chars*" "}}
f["Thisrunofcharactersismeanttohavealengththatcanbeexpressesasatriangularnumber.Diditwork?Youtellme,Ican'tcountverywell,ok?"]
              T
             h i
            s r u
           n o f c
          h a r a c
         t e r s i s
        m e a n t t o
       h a v e a l e n
      g t h t h a t c a
     n b e e x p r e s s
    e s a s a t r i a n g
   u l a r n u m b e r . D
  i d i t w o r k ? Y o u t
 e l l m e , I c a n ' t c o
u n t v e r y w e l l , o k ?

```
> 5 votes

# Answer
# Pyth, 27 bytes

```
Js.IsSGlzWz+*-J=hZdjd<~>zZZ

                               z = input()
                               Z = 0
                               d = ' '
    sSG                        G -> tri(G)
  .I   lz                      Find the (float) input whose output is len(z).
 s                             Convert to int.
J                              Save as J.
         Wz                    while z:
               =hZ             Z += 1
            *-J  Zd            Generate J-Z spaces.
                      ~>zZ     Remove the first Z characters from z.
                     <    Z    Generate those first Z characters.
                   jd          Join on spaces.
           +                   Add the two together and print.

```

Test Suite

An interesting approach - imperative, and uses `.I`. Probably golfable.
> 4 votes

# Answer
# Ruby approach 2 rev 1, 76 bytes

```
->s{s=s.chars*' '
0.upto(w=s.size**0.5-1){|i|puts' '*(w-i)+s[i*i+i,i*2+2]}}

```

Optimized using syntax ideas from Vasu Adari's answer, plus a few twists of my own.

# Ruby approach 2 rev 0, 93 bytes

```
->s{s=s.chars.to_a.join(' ')
w=(s.size**0.5).to_i
w.times{|i|puts' '*(w-i-1)+s[i*i+i,i*2+2]}}

```

Completely different approach. First we add spaces in between the characters of the input. Then we print out the rows line by line.

# Ruby approach 1, 94 bytes

```
->s{n=-1;w=((s.size*2)**0.5).to_i
(w*w).times{|i|print i/w+i%w<w-1?'':s[n+=1],-i%w==1?$/:' '}}

```

this ended up far longer than anticipated.

`w` contains the number of printable characters in the bottom row, or equivalently, the number of lines.

Every line contains `w` whitespace characters (the last of which is the newline) so the idea is to print these whitespace characters and insert the printable characters where necessary.
> 4 votes

# Answer
# C, ~~138~~ ~~136~~ 134 bytes

Takes a string as an input :

```
j,r,k,a;f(char*s){j=strlen(s);r=k=sqrt(1+8*j)/2;for(;r--;printf("\n")){for(j=r;j--;)printf(" ");for(j=k-r;j--;)printf("%c ",s[a++]);}}

```
> 4 votes

# Answer
## Minkolang 0.14, 42 bytes

```
(xid2;$I2*`,)1-[i1+[" "o]lrx" "$ii-1-D$O].

```

Try it here.

### Explanation

```
(                Open while loop
 x               Dump top of stack
  i              Loop counter (i)
   d2;           Duplicate and square
      $I2*       Length of input times two
          `,     Push (i^2) <= (length of input)
            )    Close for loop; pop top of stack and exit when it's 0

1-[                              Open for loop that repeats sqrt(len(input))-1 times
   i1+[                          Open for loop that repeats (loop counter + 1) times
       " "o                      Push a space then read in character from input
           ]                     Close for loop
            l                    Push 10 (newline)
             r                   Reverse stack
              x                  Dump top of stack
               " "               Push a space
                  $i             Push the max iterations of for loop
                    i-           Subtract loop counter
                      1-         Subtract 1
                        D        Pop n and duplicate top of stack n times
                         $O      Output whole stack as characters
                           ].    Close for loop and stop.

```
> 3 votes

# Answer
# CJam, 50 Bytes

```
q:QQ,1>{,{),:+}%:RQ,#:IR2ew<{~Q<>:LS*L,I+(Se[N}%}&

```

Try it here.

Explanation

```
q:QQ,1>{  e# Only proceed if string length > 1, otherwise just print.
,{),:}%:R e# Generates a list of sums from 0 to k, where k goes from 0 to the length of the string [0,1,3,6,10,15,21,...]
Q,#:I     e# Find the index of the length of the string in the list
R2ew<     e# Make a list that looks like [[0,1],[1,3],[3,6],...,[?,n] ]where n is the length of the string
{~Q<>:L   e# Use that list to get substrings of the string using the pairs as start and end indices
S*        e# Put spaces between the substrings
L,I+(Se[N e# (Length of the substring + Index of string length in sum array -1) is the length the line should be padded with spaces to. Add a new line at the end.
%}&

```
> 3 votes

# Answer
# Python 2, ~~88~~ 85 bytes

```
s=t=raw_input()
i=1
while s:print' '*int(len(t*2)**.5-i)+' '.join(s[:i]);s=s[i:];i+=1

```

Thanks xnor for saving 3 bytes.
> 3 votes

# Answer
# JavaScript (ES6), 135 bytes

```
w=>{r='';for(s=j=0;j<w.length;j+=s++);for(i=j=0;w[j+i];j+=++i)r+=Array(s-i-1).join` `+w.slice(j,i+j+1).split``.join` `+'<br>';return r}

```

De-golf + demo:

```
function t(w) {
    r = '';
    for (s = j = 0; j < w.length; j += s++);
    for (i = j = 0; w[j + i]; j += ++i) r += Array(s - i - 1).join` ` + w.slice(j, i + j + 1).split``.join` ` + '<br>';
    return r;
}

document.write('<pre>' + t(prompt()));
```
> 2 votes

# Answer
# Java, 258 194

Golfed:

```
String f(String a){String r="";int t=(((int)Math.sqrt(8*a.length()+1))-1)/2-1;int i=0,n=0;while(n++<=t){for(int s=-1;s<t-n;++s)r+=" ";for(int j=0;j<n;++j)r+=a.charAt(i++)+" ";r+="\n";}return r;}

```

Ungolfed:

```
public class TriangulatingText {

  public static void main(String[] a) {
    // @formatter:off
    String[] testData = new String[] {
      "R",
      "cat",
      "monk3y",
      "meanIngfu1",
      "^/\\/|\\/[]\\",
      "Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork?Youtellme,Ican'tcountverywell,ok?",
    };
    // @formatter:on

    for (String data : testData) {
      System.out.println("f(\"" + data + "\")");
      System.out.println(new TriangulatingText().f(data));
    }
  }

  // Begin golf
  String f(String a) {
    String r = "";
    int t = (((int) Math.sqrt(8 * a.length() + 1)) - 1) / 2 - 1;
    int i = 0, n = 0;
    while (n++ <= t) {
      for (int s = -1; s < t - n; ++s)
        r += " ";
      for (int j = 0; j < n; ++j)
        r += a.charAt(i++) + " ";
      r += "\n";
    }
    return r;
  }
  // End golf
}

```

Program output:

```
f("R")
R

f("cat")
 c
a t

f("monk3y")
  m
 o n
k 3 y

f("meanIngfu1")
   m
  e a
 n I n
g f u 1

f("^/\/|\/[]\")
   ^
  / \
 / | \
/ [ ] \

f("Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork?Youtellme,Ican'tcountverywell,ok?")
              T
             h i
            s r u
           n o f c
          h a r a c
         t e r s i s
        m e a n t t o
       h a v e a l e n
      g t h t h a t c a
     n b e e x p r e s s
    e d a s a t r i a n g
   u l a r n u m b e r . D
  i d i t w o r k ? Y o u t
 e l l m e , I c a n ' t c o
u n t v e r y w e l l , o k ?

```
> 2 votes

# Answer
# JavaScript (ES6), 106 bytes

```
a=>(y=z=0,(f=p=>p?" ".repeat(--p)+a.split``.slice(y,y+=++z).join` `+`
`+f(p):"")(Math.sqrt(2*a.length)|0))

```

Uses recursion instead of a for loop to build the string.

To find the length of the longest row, use the formula for the nth triangular number `T_n` is `T_n = (n^2 + n)/2`. Given `n` and solving for `T_n` using the quadratic formula, we have:

```
1/2 * n^2 + 1/2 * n - T_n = 0

a = 1/2, b = 1/2, c = -T_n

-1/2 + sqrt(1/2^2 - 4*1/2*-T_n)
------------------------------- = sqrt(1/4 + 2*T_n) - 1/2
             2*1/2

```

It turns out that after flooring, adding 1/4 inside the square root doesn't change the result, hence the formula for the longest row is `Math.sqrt(2*a.length)|0`.
> 1 votes

# Answer
# TeaScript, 44 Bytes

```
r(m=$s(2*xn)|0)ßp.R(m-i)+x·.S(v,v+=Æw)jø+§)µ

```

This uses the same method as my JavaScript answer, but is a lot shorter.

### Ungolfed

```
r(m=$s(2*xn)|0)m(#p.R(m-i)+xs``.S(v,v+=++w)j` `+`
`)j``

```
> 1 votes

# Answer
# Powershell, 69 bytes

```
($args|% t*y|?{$r+="$_ ";++$p-gt$l}|%{$r;rv r,p;$l++})|%{' '*--$l+$_}

```

Less golfed test script:

```
$f = {

(
    $args|% t*y|?{  # test predicate for each char in a argument string
        $r+="$_ "   # add current char to the result string
        ++$p-gt$l   # return predicate value: current char posision is greater then line num
    }|%{            # if predicate is True
        $r          # push the result string to a pipe
        rv r,p      # Remove-Variable r,p. This variables will be undefined after it.
        $l++        # increment line number
    }

)|%{                # new loop after processing all characters and calculating $l
    ' '*--$l+$_     # add spaces to the start of lines
}                   # and push a result to a pipe

}

@(
    ,("R",
    "R ")

    ,("cat",
    " c ",
    "a t ")

    ,("monk3y",
    "  m ",
    " o n ",
    "k 3 y ")

    ,("meanIngfu1",
    "   m ",
    "  e a ",
    " n I n ",
    "g f u 1 ")

    ,("^/\/|\/[]\",
    "   ^ ",
    "  / \ ",
    " / | \ ",
    "/ [ ] \ ")

    ,("Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork?Youtellme,Ican'tcountverywell,ok?",
    "              T ",
    "             h i ",
    "            s r u ",
    "           n o f c ",
    "          h a r a c ",
    "         t e r s i s ",
    "        m e a n t t o ",
    "       h a v e a l e n ",
    "      g t h t h a t c a ",
    "     n b e e x p r e s s ",
    "    e d a s a t r i a n g ",
    "   u l a r n u m b e r . D ",
    "  i d i t w o r k ? Y o u t ",
    " e l l m e , I c a n ' t c o ",
    "u n t v e r y w e l l , o k ? ")

    ,("*/\/|\/|o\/|o|\/o|o|\/||o|o\/o|||o|\/o||o|||\/||o|||o|\/|o|||o||o\",
    "          * ",
    "         / \ ",
    "        / | \ ",
    "       / | o \ ",
    "      / | o | \ ",
    "     / o | o | \ ",
    "    / | | o | o \ ",
    "   / o | | | o | \ ",
    "  / o | | o | | | \ ",
    " / | | o | | | o | \ ",
    "/ | o | | | o | | o \ ")

) | % {
    $s,$expected = $_
    $result = &$f $s
    "$result"-eq"$expected"
    $result
}

```

Output:

```
True
R
True
 c
a t
True
  m
 o n
k 3 y
True
   m
  e a
 n I n
g f u 1
True
   ^
  / \
 / | \
/ [ ] \
True
              T
             h i
            s r u
           n o f c
          h a r a c
         t e r s i s
        m e a n t t o
       h a v e a l e n
      g t h t h a t c a
     n b e e x p r e s s
    e d a s a t r i a n g
   u l a r n u m b e r . D
  i d i t w o r k ? Y o u t
 e l l m e , I c a n ' t c o
u n t v e r y w e l l , o k ?
True
          *
         / \
        / | \
       / | o \
      / | o | \
     / o | o | \
    / | | o | o \
   / o | | | o | \
  / o | | o | | | \
 / | | o | | | o | \
/ | o | | | o | | o \

```
> 1 votes

# Answer
# 05AB1E, 11 bytes

```
ā£õKεSðý}.c

```

Try it online!
> 1 votes

# Answer
# Vyxal `C`, 5 bytes

```
KÞṁvṄ

```

Try it Online!

```
 Þṁ   # Mold (without repeating elements) to...
K     # Prefixes
   vṄ # Join each on spaces
      # (C flag) center the result

```
> 1 votes

# Answer
# Bash + sed, 87

```
for((;i<${#1};i+=j));{
a+=(${1:i:++j})
}
printf %${j}s\\n ${a[@]}|sed 's/\S/ &/g;s/.//'

```
> 0 votes

# Answer
## C#, 202

```
string r(string s,List<string> o,int i=1){o=o.Select(p=>" "+p).ToList();o.Add(String.Join(" ",s.Substring(0,i).ToCharArray()));return s.Length==i?String.Join("\n",o):r(s.Substring(i,s.Length-i),o,i+1);}

```

I don't know if this is legal in code-golf but, does passing a list in the function count? I can't find a way to recurse this without a List\< string \> declared outside the function so I put it as a parameter.

Usage:

```
 r("1",new List<string>());
 r("123", new List<string>());
 r("123456", new List<string>());
 r("Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork?Youtellme,Icanstcountverywell,ok?",new List<string>());

```
> 0 votes

# Answer
# C, 102 bytes

```
i,j;main(n,s){for(n=sqrt(strlen(gets(s))*2);j<n;printf("%*.1s",i>1?2:i*(n-j),i++>j?i=!++j,"\n":s++));}

```
> 0 votes

# Answer
# R, 142 bytes

Pretty sure I can get this down more. Still working on that though. I feel like I'm missing an easy recursion -- but I haven't been able to shorten it right.

```
f=function(a){n=nchar(a);l=which(cumsum(1:n)==n);w=strsplit(a,c())[[1]];for(i in 1:l){cat(rep(" ",l-i),sep="");cat(w[1:i],"\n");w=w[-(1:i)]}}

```

ungolfed

```
f=function(a){
    n = nchar(a)                 #number of characters
    l= which(cumsum(1:n)==n)     #which triangle number
    w= strsplit(a,c())[[1]]      #Splits string into vector of characters
    for (i in 1:l) {
        cat(rep(" ",l-i),sep="") #preceeding spaces
        cat(w[1:i],"\n")         #Letters
        w=w[-(1:i)]              #Shifts removes letters (simplifies indexing)
    }
}

```
> 0 votes

# Answer
# Vyxal `j`, 24 bytes

```
{:|&›:¥Ẏ⅛¥ȯ}¾ƛfṄ¾LnL-ð*p

```

Try it Online!
> 0 votes

---
Tags: code-golf, string, ascii-art, arithmetic, sequence
---


title: Page Selector

text:
# Question
Title: Page Selector
I'm making a page selector for my super cool terminal-based blog program. In order for it to fit correctly into the design, it has to have some constraints.

The page selector can only display a certain number of numbers at a time due to the constraints of the UI system. If there are more characters then can fit, they must be removed and replaced with an ellipsis (which itself counts as a number). The system will try to display up to three numbers around the selected one (which is displayed surrounded by square brackets) and distribute the rest of the numbers evenly at the ends.

Your task is to, given a number of pages, selector width (always more than or equal to 3, and always odd), and currently selected number, all of which are both required and positive, print to STDOUT the resulting page selector.

## Examples

```
In: 5 5 1
Out: < [1] 2 3 4 5 >

In: 5 3 1
Out: < [1] ... 5 >

In: 7 5 3
Out: < 1 ... [3] ... 7 >

In: 11 7 4
Out: < 1 ... 3 [4] 5 ... 11 >

In: 11 7 7
Out: < 1 ... 6 [7] 8 ... 11 >

In: 11 9 7
Out: < 1 2 ... 6 [7] 8 ... 10 11 >

In: 7 3 3
Out: < ... [3] ... >

```

# Answer
# Python3, 380 bytes:

```
lambda r,w,c:'< '+' '.join(map(str,Q([*R(1,c)],J:=(min((w-1)//2+(w-1)%2,c-1)),w+~J,len(V:=[*R(c+1,r+1)]))+[f'[{c}]']+W(V,w+~J)))+' >'
R,*E=range,'...'
W=lambda r,l:E if l<2and len(r)>1else(r if l==len(r)else r[:l-2]+E+[r[-1]])
Q=lambda r,l,L,V:r[:l-1]+E if L==1and V>1else(E if l<2and len(r)>1else(r if L-2or r==[]else r[:-1]+E)if l==len(r)else[r[0],*E,r[-1]]if L-2else r[:l-1]+E)

```

Try it online!

Output:

```
< [1] 2 3 4 5 >
< [1] ... 5 >
< 1 ... [3] ... 7 >
< 1 2 3 [4] 5 ... 11 >
< 1 ... 6 [7] 8 ... 11 >
< 1 2 ... [7] ... 11 >
< 1 2 ... [6] ... 11 >
< ... [3] ... >
< 1 ... [3] ... >

```
> 3 votes

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


# Question
Title: Print an arch of ascending / descending numbers
I figured an "arch" was the best way to describe this pattern of numbers:

```
1234567887654321
1234567  7654321
123456    654321
12345      54321
1234        4321
123          321
12            21
1              1

```

Formally defined, each line consists of the numbers 1 through `9-n`, `(n-1)*2` spaces, and the numbers `9-n` through 1 (where `n` is the current line).

Your task is to write, using the shortest code possible, a small script/program that prints the above pattern subject to the following restrictions:

1. You may not hardcode the entire pattern. You may only hardcode a single line of the pattern at most.
2. Your program must print a newline (any combination of `\n` or `\r`) at the end of each line.

Ready... set.... go!

# Answer
## Python 2, ~~65~~ ~~55~~ ~~53~~ 51

```
s=12345678
while s:r='%-8d'%s;print r+r[::-1];s/=10

```

Shortened using some of ugoren's ideas.
> 22 votes

# Answer
## GolfScript (25 chars)

```
8,{.~10,<1>\' '*.2$-1%n}/

```
> 10 votes

# Answer
## APL (18)

```
k,⌽k←↑↑∘(1↓⎕D)¨⌽⍳8

```

Explanation:

* `1↓⎕D`: the string of digits ("0123456789") minus its first element
* `↑∘(1↓⎕D)¨⌽⍳8`: select the first \[8..1\] characters ('12345678', '1234567'...)
* : format as matrix (filling the unused characters with blanks)
* `k,⌽k←`: store in `k`, and display `k` followed by the vertical mirroring of `k`
> 9 votes

# Answer
# Ruby: ~~61~~ 50 characters

```
s="87654321";s.chars{|c|puts s.reverse+s;s[c]=" "}

```

Sample run:

```
bash-4.2$ ruby -e 's="87654321";s.chars{|c|puts s.reverse+s;s[c]=" "}'
1234567887654321
1234567  7654321
123456    654321
12345      54321
1234        4321
123          321
12            21
1              1

```
> 4 votes

# Answer
## Befunge - 3 x 18 = 54

I felt I had to do something with befunge, it's been too long since I last used it. This problem felt the most appropriate for the language.

It is horrendously slow due to the print loop that takes about 8 actions per character (counting styles differ).

```
80v >#v"12345678"<
>5 *^ >,#$:_$:1-:v
^2< 0p0+7\*48\_@#<

```
> 4 votes

# Answer
# JavaScript, 71

```
s='1234567887654321',i=10;while(--i)console.log(s=s.split(i).join(' '))

```
> 4 votes

# Answer
## C, 83 chars

```
main(a,b,n){
    for(a=12345678,n=1e8,b=n-a-1;a;a/=10)
        printf("%-8d%8d\n",a,b),
        b%=n/=10;
}

```
> 3 votes

# Answer
# Python 2, 75 62

It won't beat Volatility's answer, but here's another approach using python's mutable strings (`bytearray`):

```
s=bytearray('1234567887654321')
for i in range(8):s[8-i:8+i]=i*'  ';print s

```

**Edit**

I found a shorter version, using `str.replace`:

```
s='1234567887654321'
for c in s[8:]:print s;s=s.replace(c,' ')

```
> 3 votes

# Answer
# Mathematica 92 85 67 54 51

**Method #1**: (54 chars) Makes array using row#, col#, and distance from left-right edge.

```
Grid@Array[If[#2<9,#2,17-#2]/.x_/;x+#>9:>" "&,{8,16}]

```

---

**Method #2**: (67 chars) Pad ever-shortening ranges.

```
Print@@@Table[Join[k = PadRight[Range@i, 8, " "], Reverse@k], {i, 8, 1, -1}];

```

---

**Method #3**: (85 chars) Selectively fill each row of an array.

Start with list of 8 space characters. Replace positions 1 and 16 with "1"; replace "2" at positions 2 and 15, etc.

```
p = 0; q = 16;
Print @@@Reverse@Rest@NestList[ReplacePart[#, {++p -> p, q-- -> p}]&,Array[" "&,q], 8];

```

---

**Method #4**: (86 chars) Selectively empty each row of an array.

```
p=8;q=9;
Print@@@NestList[ReplacePart[#,{p---> " ",q++-> " "}]&,Join[k=Range@8,Reverse@k],7];

```

---

**Method #5**: Using strings (92 chars)

```
p=8;s="12345678";
Print[#,StringReverse@#]&/@NestList[StringReplace[#,ToString@p-- ->  " "]&,s,7];

```
> 3 votes

# Answer
# Perl, 41

plus `-E` switch. Total characters on the command line: **50**

requires at least perl5, version 10.

```
perl -E'say@!=1..8-$_,$"x(2*$_),reverse@!for-0..7'

```
> 3 votes

# Answer
## PHP, 68

(Inspired by HamZa's answer)

`for($n=8;$n;$r[]=$n--)echo str_replace($r," ","1234567887654321\n");`

Plays on the fact that PHP's str\_replace can accept an array for search and a string for replace, it'll replace every item in the array with the given string. After each iteration, the current number is added to the search array, removing it from the next loop.

Example of the code in action: http://ideone.com/9wVr0X
> 3 votes

# Answer
# Marbelous 165

```
@0
08
>0
LN
--
@0
:LN
}0}0}0}0
..SAPSSD0A
{0
:PS
}0
~~09
..//
<<@0
\\>0
&0//
--@1
@020
&0/\&0
@1
:SA
@0
}0
>0!!
--00@1
@0++//
+O/\@1
+O
:SD
}0@0
\\>0\/
--/\+O
@0..+O

```

Pseudocode:

```
MB():
    for x in 8..1:
        LN(x)
LN(x):
    SA(x)
    PS(x)
    SD(x)
    print "\n"
PS(x):
    print " "*(8-x)*2
SA(x):
    for n in 1..x:
        print n
SD(x):
    for n in x..1:
        print n

```
> 3 votes

# Answer
## Python 2.x - ~~73~~ ~~65~~ ~~63~~ 61 chars

```
c=1;s='87654321'
while c<9:print s[::-1]+s;s=' '*c+s[c:];c+=1

```
> 2 votes

# Answer
## PHP, 76

```
for($i=9;$i>1;){$r[]=$i--;echo str_replace($r,' ','1234567887654321')."\r";}

```
> 2 votes

# Answer
# K, 28

```
-1_a,'|:'a:8$'{-1_x}\,/$1+!8

```

.

```
k)-1_a,'|:'a:8$'{-1_x}\,/$1+!8
"1234567887654321"
"1234567  7654321"
"123456    654321"
"12345      54321"
"1234        4321"
"123          321"
"12            21"
"1              1"

```

You could generalise it for 36: `{-1_a,'|:'a:(#*m)$'m:{-1_x}\,/$1+!x}`

```
k){-1_a,'|:'a:(#*m)$'m:{-1_x}\,/$1+!x} 5
"1234554321"
"1234  4321"
"123    321"
"12      21"
"1        1"
q)k){-1_a,'|:'a:(#*m)$'m:{-1_x}\,/$1+!x} 15
"123456789101112131415514131211101987654321"
"12345678910111213141  14131211101987654321"
"1234567891011121314    4131211101987654321"
"123456789101112131      131211101987654321"
"12345678910111213        31211101987654321"
"1234567891011121          1211101987654321"
"123456789101112            211101987654321"
"12345678910111              11101987654321"
"1234567891011                1101987654321"
"123456789101                  101987654321"
"12345678910                    01987654321"
"1234567891                      1987654321"
"123456789                        987654321"
"12345678                          87654321"
"1234567                            7654321"
"123456                              654321"
"12345                                54321"
"1234                                  4321"
"123                                    321"
"12                                      21"
"1                                        1"

```
> 2 votes

# Answer
# GoRuby 2.1

### 36 chars

```
8.w(1){|x|a=[*1..x].j.lj 8;s a+a.rv}

```

### Ungolfed

```
8.downto(1) do |x|
  a = [*1..x].join.ljust(8)
  puts a + a.reverse
end

```
> 2 votes

# Answer
**K 20**

```
{x,'|:'x:|x$,\$1+!x}

q)k){x,'|:'x:|x$,\$1+!x}8
"1234567887654321"
"1234567  7654321"
"123456    654321"
"12345      54321"
"1234        4321"
"123          321"
"12            21"
"1              1"

```
> 2 votes

# Answer
# Javascript, 67 chars

Insipired by steveworley's answer (I would comment if I could):

### Code snippet

```
a='1234567887654321\n',b='',c=10;while(--c)b+=a=a.split(c).join(' ')
```

```
<a href="#" onclick="javascript:document.getElementById('output').innerHTML = b;">Display</a>
<pre id="output">...</pre>
```

The presence of the last newline does follow the rules.

update: cut 2 chars by removing parentheses (operator precedence) and 1 by removing an unneeded space

It seemed like it's trolling me, because no matter how many different ways I tried to shorten or simplify by un-hardcoding a segment of code, the length stayed the same until I let the "I think this counts" rule written below apply.

*(If printing counts as what comes back when this is executed in the chrome console)*
> 2 votes

# Answer
# Brainfuck: 542 Bytes

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

```
> 2 votes

# Answer
## Haskell, 84

A starting point for someone to improve:

```
mapM_ putStrLn[let l=take(8-i)"12345678"++replicate i ' 'in l++reverse l|i<-[0..7]]

```

Most likely part would be to make the `l++reverse l` point free, letting us get rid of the `let`-statement, but I'll I could find was `ap`, which requires imports.
> 1 votes

# Answer
## *Mathematica*, 59

61 using my own ideas:

```
Grid[Clip[#~Join~Reverse@#&@Range@8,{1,9-#},{," "}]&~Array~8]

```

Or 59, borrowing from David's answer:

```
Grid@Array[Join[k=PadRight[Range[9-#],8," "],Reverse@k]&,8]

```
> 1 votes

# Answer
## R: 52

```
for(i in 8:1)cat(1:i,rep(" ",16-2*i),i:1,"\n",sep="")

```
> 1 votes

# Answer
## Tcl: 91 characters

```
set i 10
set n 1234567887654321
while {[incr i -1]} {puts [set n [string map "$i { }" $n]]}

```
> 1 votes

# Answer
# PostScript: 105 characters

String handling is not easy in PS but can make for relatively simple code:

```
0 1 7{(1234567887654321)dup
8 3 index sub(              )0 6 -1 roll 2 mul getinterval putinterval =}for

```

A slightly longer version at 120 chars but can generate different number arches by replacing the 8 at the start of the second line with any number in the range 1 to 9:

```
/D{dup}def/R{repeat}def/P{=print}def
8 D -1 1{1 1 index{D P 1 add}R pop 2 copy sub{(  )P}R D{D P 1 sub}R pop()=}for pop

```
> 1 votes

# Answer
## TSQL, 148

Edit: down to 148 with manatwork's suggestion and tweak to ORDER BY.

Readable:

```
WITH t AS(
    SELECT 1n, CAST(1 AS VARCHAR(MAX)) o
 UNION ALL
    SELECT n+1,o+CHAR(n+49)
    FROM t
    WHERE n<8
)
SELECT o  + SPACE(16-2*n) + REVERSE(o)
FROM t
ORDER BY 1 DESC

```

Golfed:

```
WITH t AS(SELECT 1n,CAST(1AS VARCHAR(MAX))o UNION ALL SELECT 1+n,o+CHAR(n+49)FROM t WHERE n<8)SELECT o+SPACE(16-2*n)+REVERSE(o)FROM t ORDER BY 1DESC

```

Output:

```
1234567887654321
1234567  7654321
123456    654321
12345      54321
1234        4321
123          321
12            21
1              1

```
> 1 votes

# Answer
## Haskell, 79

```
r n x|x>n=' '|True=x
t="87654321"
main=mapM(putStrLn.(`map`("12345678"++t)).r)t

```

This works by replacing characters \> n with `' '`, where characters n are sourced from "87654321" (which happens to be the tail of the string to perform substitution on).
> 1 votes

# Answer
# k, 33 chars

```
{|:{x,'|:'x}a$,/'$:{1+'!x}'1+!a:x}9

```
> 1 votes

# Answer
# PHP: 61 chars (or 60 chars if you replace the \n by a real ASCII newline)

(Inspired by GigaWatt's and HamZa's answer)

```
for($n=9;$n;$r[$n--]=" ")echo strtr("1234567887654321\n",$r);

```

http://ideone.com/FV1NXu
> 1 votes

# Answer
# PowerShell: 38

**Golfed code**

```
8..1|%{-join(1..$_+"  "*(8-$_)+$_..1)}

```

**Walkthrough**

`8..1|%{`...`}` pipe integers from 8 to 1 into a ForEach-Object loop.
`-join(`...`)` joins output of the nested code into a single string with no delimiters.
`1..$_` outputs integers ascending from 1 to the current integer in the loop.
`+" "*(8-$_)` adds a double-space, multiplied by the difference between 8 and the current integer, to the output.
`+$_..1` adds integers, descending from the current integer to 1, to the output.
> 1 votes

# Answer
## Javascript with lambdas, 147

```
(s="12345678")[r="replace"](/./g,i=>s[r](RegExp(".{"+(i-1)+"}$"),Array(i*2-1).join(" ")))[r](/\d{1,8} */g,m=>m+(Array(m%10+1).join(m%10+1)-m)+"\n")

```

Can be checked in Firefox.
> 1 votes

# Answer
## CJam, 22 characters

Not a valid answer (as language was developed after the question), and not the shortest either, but here goes:

```
8,{S*_,9-~,:)\_2$W%N}%

```

Try it online here
> 1 votes

# Answer
# Jelly, 11 bytes

```
RURz⁶Zm0$€Y

```

Try it online!

```
RURz⁶Zm0$€Y  Main Link
RU           Inverse Range
  R          Range ([1...x], [1..x-1], [1..x-2], ..., [1])
   z⁶Z       Zips, filling by spaces, and then zips back (pads)
         €   Map...
      m0$    ...appending the reverse of each element to itself
          Y  Newline-delimited

```
> 1 votes

# Answer
# Vyxal `j`, 9 bytes

```
8ɾɾṘƛṅ8↲m

```

Try it Online!

```
8ɾ        # 1...8
  ɾ       # 1...{1...8}
   Ṙ      # {1...8}...1
    ƛ     # For each
     ṅ    # Join
      8↲  # Pad to length 8 with spaces
        m # Mirror
          # (j flag) join by newlines

```
> 1 votes

# Answer
# Pip `-l`, 13 bytes

```
RF\,8X8-,8ZDs

```

Try it online!

### Explanation

```
        ,8     Numbers 0 through 7
      8-       Subtract each from 8, giving numbers 8 through 1
     X         Repeat that many times
  \,8          the corresponding number from 1 through 8
               We now have the list [11111111 2222222 ... 77 8]
RF             Reflect, appending a reversed copy of the list
          ZDs  Transpose, padding shorter elements with a default value of space
               Autoprint with each row on its own line (-l flag)

```
> 1 votes

# Answer
# Stax, 9 bytes

```
éúß8╕t±╫k

```

Run and debug it gaming
> 1 votes

# Answer
# APL, 15 Chars, 29 Bytes

```
a,⌽a←⊃⌽,\⍕10⊥⍳8

```

`⍕10⊥⍳8` produces string '12345678' and `,\` gives all prefixes.

```
 1 12 123 1234 12345 123456 1234567 12345678

```

reverses the array and  builds a matrix:

```
12345678
1234567
123456
12345
1234
123
12
1

```

`a,⌽a` concatenates each row with its reverse and gives the results.

Works on GNU APL and APLX. For Dyalog APL, change  to , or set migration level to 2 `⎕ML←2`.
> 1 votes

# Answer
## Lua, 62

```
s='1234567887654321'for i=8,1,-1 do print(s)s=s:gsub(i,' ')end

```
> 0 votes

# Answer
**K 27**

```
q)k)f:{{x,'|:'x}x$,/'$1+!:'|1+!x}
q)f 8
"1234567887654321"
"1234567  7654321"
"123456    654321"
"12345      54321"
"1234        4321"
"123          321"
"12            21"
"1              1"

```
> 0 votes

# Answer
# J: 34 31 characters

```
(,.|."1)|.(>:i.8){."0 1(49}.a.)

```

Been a while since I've coded in J. I'm sure I can shave off some characters somewhere.
> 0 votes

# Answer
# Java, 127

```
void a(){for(int y=0;y<8;System.out.println(y++==9?"":""))for(int c=0,x=1;c<16;System.out.print(y+(x=++c<=8?c:8-c+9)>8?"":x));}

```
> 0 votes

# Answer
# Haskell, 71 bytes

```
d="87654321"
main=mapM putStrLn[do x<-reverse d++d;max" "[x|x<=y]|y<-d]

```

Try it online!
> 0 votes

# Answer
# Canvas, ~~7~~ 6 bytes

```
８｛Ｒ］⇵║

```

Try it here!
> 0 votes

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


title: Draw an ASCII Volume

text:
# Question
Title: Draw an ASCII Volume
Given a volume level `V` in the range `1-10`. Your program should draw the following ASCII art.

When `V=1`:

```
\
 |
/

```

When `V=2`:

```
  \
\  |
 | |
/  |
  /

```

When `V=3`:

```
    \
  \  |
\  | |
 | | |
/  | |
  /  |
    /

```

And etc. Trailing spaces are allowed.

This is a code-golf challenge so the shortest solution wins.

# Answer
> 8 votes
# Python 3.8 (pre-release), ~~169~~ ~~157~~ ~~144~~ ~~131~~ ~~98~~ ~~92~~ ~~90~~ 87 bytes

*Thanks @ophact for helping me save ~~some~~ a lot of bytes*

*Thanks @alephalpha for helping me golf it down to under 100 bytes with a completely new strategy*

*Thanks @ emanresu A for another -8 bytes*

```
lambda n:[print(*" "*~-abs(i)+(i!=0)*"\\/"[i>0],(n-abs(i))*" |")for i in range(-n,n+1)]

```

Try it online!

~~First time trying to golf in Python. There's probably tons of stuff to golf here :D~~

My answer has literally been golfed to death entirely by the efforts of other people (not me).

# Answer
> 8 votes
# Vyxal, 17 bytes

```
ɾ\|*\\?ɾ꘍$YvøMøĊ§

```

Try it Online!

This was quite a nice approach that may have ended up a bit clunky due to lack of overloads.

The idea is simple: Create the rotated form:

```
  \ /
   |
 \   /
  |||
\     /
 |||||

```

And rotate it 90° with the `§` builtin.

We can create the above by interleaving the following:

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

  \ /
 \   /
\     /

```

And that's basically what this does, with a few convenient Vyxal builtins. So close to beating Charcoal...

```
   *              # Repeat...
 \|               # "|"
ɾ                 # By 1...n
      ?ɾ          # 1...n
        ꘍         # Spaces appended to...
    \\            # "\"
         $Y       # Interleave them
           vøM    # Mirror each line, leaving the middle alone and flipping slashes
              øĊ  # Align each line to the center
                § # Rotate the whole thing 90°

```

# Answer
> 7 votes
# Python 2, 78 bytes

```
n=i=input()
while~n-i:x=abs(i);print('  '*x+'\/'[i<0]+' ')[2:],'| '*(n-x);i-=1

```

Try it online!

# Answer
> 7 votes
# JavaScript (ES6), 92 bytes

This builds the output character per character. (So it may be longer than generating the strings explicitly, but it's a little more fun. ^^)

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

```

Try it online!

### How?

For each position \\$(x,y)\\$ with \\$0\le x\<2n\\$ and \\$-n\le y \le n\\$, we compute:

$$d=y^2-x^2/4$$

For \\$n=3\\$, this gives:

$$\begin{array} {|c|c|} \hline & 0 & 1 & 2 & 3 & 4 & 5 \\ \hline 3 & 9 & 8.75 & 8 & 6.75 & \color{red}{5} & 2.75 \\ \hline 2 & 4 & 3.75 & \color{red}{3} & 1.75 & 0 & \color{blue}{-2.25} \\ \hline 1 & \color{red}{1} & 0.75 & 0 & \color{blue}{-1.25} & -3 & \color{blue}{-5.25} \\ \hline 0 & 0 & \color{blue}{-0.25} & -1 & \color{blue}{-2.25} & -4 & \color{blue}{-6.25} \\ \hline -1 & \color{red}{1} & 0.75 & 0 & \color{blue}{-1.25} & -3 & \color{blue}{-5.25} \\ \hline -2 & 4 & 3.75 & \color{red}{3} & 1.75 & 0 & \color{blue}{-2.25} \\ \hline -3 & 9 & 8.75 & 8 & 6.75 & \color{red}{5} & 2.75 \\ \hline \end{array}$$

We then apply the following rules:

* If \\$x\\$ is even:
    + If \\$x=d-1\\$, we insert either a `\` or a `/` according to the sign of \\$y\\$ (red cells)
    + Otherwise, we insert a space
* If \\$x\\$ is odd:
    + If \\$d\<0\\$, we insert a `|` (blue cells)
    + Otherwise, we insert a space

# Answer
> 6 votes
# Pari/GP, 85 bytes

```
n->for(i=-n,n,print(concat([if(j>l=abs(i)," |",j<l,"  ",i<0,"\\ ","/ ")|j<-[1..n]])))

```

Try it online!

# Answer
> 4 votes
# Ruby, 69 bytes

```
->n{(-n..n).map{|c|((" "*2*z=c.abs)+(c>0?"/ ":"\\ ")+" |"*n)[2,2*n]}}

```

Try it online!

# Answer
> 2 votes
# Charcoal, 16 bytes

```
ＦＮ«Ｐ↖²Ｐ↓⊕ι→↗»‖Ｂ↓

```

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

```
ＦＮ«

```

Loop `V` times.

```
Ｐ↖²

```

Draw each of the `\`s along the top as a line of two without moving the cursor, so that the second one gets overwritten by the vertical line below.

```
Ｐ↓⊕ι

```

Draw the top half of each vertical line without moving the cursor.

```
→↗

```

Move to the top of the next vertical line.

```
»‖Ｂ↓

```

Reflect to complete the art.

# Answer
> 2 votes
# 05AB1E, 18 bytes

```
Ýx¨R'\ús„ |×ζ`θ».∊

```

Try it online or verify all test cases.

**Explanation:**

```
          #  e.g. input=3
Ý         # Push a list in the range [0, (implicit) input]
          #  STACK: [0,1,2,3]
 x        # Double each value (without popping)
          #  STACK: [0,1,2,3],[0,2,4,6]
  ¨       # Remove the last item
          #  STACK: [0,1,2,3],[0,2,4]
   R      # Reverse it
          #  STACK: [0,1,2,3],[4,2,0]
    '\   '# Push string "\"
          #  STACK: [0,1,2,3],[4,2,0],"\"
      ú   # Pad it with leading spaces based on the integer-list
          #  STACK: [0,1,2,3],["    \","  \","\"]
 s        # Swap so the earlier list is at the top
          #  STACK: ["    \","  \","\"],[0,1,2,3]
  „ |     # Push string " |"
          #  STACK: ["    \","  \","\"],[0,1,2,3]," |"
     ×    # Repeat it the integers amount of times
          #  STACK: ["    \","  \","\"],[""," |"," | |"," | | |"]
       ζ  # Create pairs of the two lists, which uses a space as implicit filler
          # since they're of unequal lengths
          #  STACK: [["    \",""],["  \"," |"],["\"," | |"],[" "," | | |"]]
`         # Pop and push the pairs separated to the stack
          #  STACK: ["    \",""],["  \"," |"],["\"," | |"],[" "," | | |"]
 θ        # Leave just the last/second item of the top pair
          #  STACK: ["    \",""],["  \"," |"],["\"," | |"]," | | |"
  »       # Join the stack with newline delimiter, which will implicitly join
          # lists by spaces first
          #  STACK: "    \ \n  \  |\n\  | |\n | | |"
   .∊     # Vertically mirror with overlap
          #  STACK: "    \ \n  \  |\n\  | |\n | | |\n\  | |\n  \  |\n    \ "
          # (which is output implicitly as result)

```

# Answer
> 2 votes
# Java, 241, 238 bytes

```
public class V{public static void main(String[]a){int V=new java.util.Scanner(System.in).nextInt(),d=-1,i=V;var s="";while(i<=V){if(i==0)d=1;else s+=("  ".repeat(i-1)+(d<0?"\\ ":"/ "));s+=" |".repeat(V-i)+'\n';i+=d;}System.out.print(s);}}

```

Obviously Java is a rather verbose language for code golf, but I like to see how well I can do with it anyway. It isn't clear if "Given a value V" means to read it as an input, or if the value for V is allowed to be hard coded, so long as values in the range (1-10) work. If the value for V can be set in the code, the answer can be reduced to 198 bytes.

If we go so far as to allow a line of code that can be entered into jshell, then we can get it to 145 or 146 bytes (depending on V being one or two digits):

```
int V=3,d=-1,i=V;var s="";while(i<=V){if(i==0)d=1;else s+=("  ".repeat(i-1)+(d<0?"\\ ":"/ "));s+=" |".repeat(V-i)+'\n';i+=d;}System.out.print(s);

```

In this case the input value for V is entered directly in the program. I suspect this violates Default for Code Golf: Program, Function or Snippet? though.

# Answer
> 2 votes
# GNU APL, ~~43~~ 42 Chars, ~~67~~ 66 Bytes

```
{⍉(2/-⍵-⍳⍵)⌽⊃⊃,/{1(¯1+2×⍵)1/¨"\ /"" | "}¨⍳⍵}

```

`⊃⊃,/{1(¯1+2×⍵)1/¨'\ /' ' | '}¨⍳⍵` replicates characters according to the input and builds the matrix, for example V=3:

```
\ /
 |
\   /
 |||
\     /
 |||||

```

`(2/-⍵-⍳⍵)⌽` rotates rows to their position, and finally  does a transpose:

```
    \
  \  |
\  | |
 | | |
/  | |
  /  |
    /

```

Update:

Since GNU APL support double quote string, `'\ /' ' | '` can be rewritten as `"\ /"" | "`, with one space removed.

# Answer
> 1 votes
# Retina 0.8.2, 65 bytes

```
.+
$*:¶$&$*:¶$&$*:
:
 |
\G \|
¶$.%'$* \ $%`
r` \|\G
$.%`$* / $%'¶

```

Try it online! Explanation:

```
.+
$*:¶$&$*:¶$&$*:

```

Convert the input into three rows of `V` `:`s as placeholders for the `|`s (which cost an extra byte to match).

```
:
 |

```

Replace the `:`s with  `|`, so that the `|`s have the correct spacing.

```
\G \|
¶$.%'$* \ $%`

```

Turn the first row of  `|`s into a "triangle", preceded with `\`s.

```
r` \|\G
$.%`$* / $%'¶

```

Turn the last row of  `|`s into a "triangle", preceded with `/`s.

# Answer
> 1 votes
# APL+WIN, 59 bytes

Prompts for n. Index origin = 0

```
(∊2/¨⌽-i)⊖⍉⊃,('\',¨(-1+n)↑¨'/'),[0.1]' ',¨(n←1+2×i←⍳⎕)⍴¨'|'

```

Try it online! Thanks to Dyalog Classic

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


title: Prime a*b+c of N

text:
# Question
Title: Prime a*b+c of N
Given an integer \\$N\\$, print or return integers \\$a\\$, \\$b\\$, and \\$c\\$ that satisfy all of the following conditions, if such integers exist:

* \\$a \times b + c = N\\$
* \\$a\\$, \\$b\\$, and \\$c\\$ are all prime
* \\$a \> b \> c\\$

If no valid combination of integers exist, you should return nothing, 0, None, an empty list, or raise an error.

If multiple valid combinations of integers exists, you can print or return any of them or all of them in a data type of your choosing.

A list of multiple solutions does not need to be sorted, and since we know that \\$a \> b \> c\\$, you can return them in any order.

```
Examples:

Input: 17
Output: 5 3 2

Input: 20
Output: None

Input: 37
Output: 7 5 2

Input: 48
Output: None

Input: 208
Output: [(41, 5, 3), (29, 7, 5)]

```

This is code golf, so the code with the lowest byte count wins.

Inspired by this Redditor's neat dream.

# Answer
> 11 votes
# Wolfram Mathematica, 29 bytes

```
 Solve[a*b+c==#>a>b>c,Primes]&

```

Test cases:

```
Solve[a*b+c==#>a>b>c,Primes]&@17
Solve[a*b+c==#>a>b>c,Primes]&@20
Solve[a*b+c==#>a>b>c,Primes]&@37
Solve[a*b+c==#>a>b>c,Primes]&@48
Solve[a*b+c==#>a>b>c,Primes]&@208

```

> {{a -\> 5, b -\> 3, c -\> 2}}
>
> {}
>
> {{a -\> 7, b -\> 5, c -\> 2}}
>
> {}
>
> {{a -\> 29, b -\> 7, c -\> 5}, {a -\> 41, b -\> 5, c -\> 3}}

# Answer
> 6 votes
# tinylisp, 210 bytes

```
(load library
(d p prime?
(d f(q((n k)(i(e n k)0(i(g n k 2)(g n k 2)(f n(+ k 1
(d g(q((n k j)(i(l(/ n k)j)0(i(*(l(- n(* k j))j)(l j k)(p(- n(* k j)))(p k)(p j))(list k(- n(* k j))j)(g n k(+ j 1
(d F(q((n)(f n 2

```

Try it online!

Gotta love golfing in tinylisp...

Thanks to DLosc for saving some bytes... 32 to be exact.

# Answer
> 4 votes
# Factor \+ `math.combinatorics math.primes`, 64 bytes

```
[ dup nprimes swap 3 [ first3 * + = ] with filter-combinations ]

```

Try it online!

## Explanation

Get all the combinations of three primes that satisfy `a * b + c = N`. `a > b > c` is inherent by virtue of the fact we're filtering combinations without repetition.

# Answer
> 3 votes
# Pyth, 37 bytes

```
FGQIP_GFHGIP_HFNHIP_NIq+*GHNQ
G
H
N.q

```

hacky, but works

Try it online!

explanation:

```
                              Q = eval(input())
F                             for
 G                            G
  Q                           in range(Q):
   I                            if
    P_                          prime(
      G                          G
                                ):
       F                          for
        H                         H
         G                        in range(G):
          I                         if
           P_                       prime(
             H                       H
                                    ):
               F                      for
                N                     H
                 H                    in range(H):
                  I                     if
                   P_                   prime(
                     N                   N
                                        ):
                      I                   if
                          G               G
                         *                *
                           H              H
                        +                 +
                            N             N
                       q                  ==
                             Q            Q:
                              (newline)     print(
G                                             G
                                            )
 (newline)                                  print(
H                                             H
                                            )
 (newline)                                  print(
N                                             N
                                            )
 .q                                         exit()

```

# Answer
> 3 votes
# APL(Dyalog Unicode) \+ dfns, ~~63~~43 bytes SBCS

```
{⍵⌿⍨(∧/1pco¨⍵)∧⍺=(0∘⌷+1∘⌷×2∘⌷)⍉⍵}∘(3cmat⊢)⍨

```

Hats off to @ovs for a 2+18 bytes shave!

Tacit function with an anonymous function baked in. Returns a 3-col matrix, with as many rows as possible results.

`dfns` is like a library of useful functions:

* the `pco` function I'm using, which checks for primality, can be found there; and
* the `cmat` function generates the combinations of possible `a`, `b`, and `c` values.

Try it on online! The TIO link has 2 more bytes because of `f←`, which I'm using to make it easier to test the function. It also takes a long time because I'm being wasteful with my primality checks; here is the output on my machine:

```
      f¨ 17 20 37 48 208
┌─────┬┬─────┬┬──────┐
│5 3 2││7 5 2││29 7 5│
│     ││     ││41 5 3│
└─────┴┴─────┴┴──────┘

```

Explanation:

`(3cmat⊢)` builds a 3-column matrix with all possible values of `a`, `b`, and `c`, already satisfying the restriction that `a > b > c`:

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

```

Then, `{⍵⌿⍨(∧/1pco¨⍵)∧⍺=(0∘⌷+1∘⌷×2∘⌷)⍉⍵}` takes the original number on the left and that 3-col matrix on the right, and takes all rows that satisfy two criteria simultaneously:

* the rows only have prime numbers (checked with `(∧/1pco¨⍵)`); and
* `a×b+c` equals the original input (checked with `⍺=(0∘⌷+1∘⌷×2∘⌷)⍉⍵`).

# Answer
> 3 votes
# Excel, 164 bytes

```
=TEXTJOIN(",",,LET(q,SEQUENCE(A4),a,FILTER(q,MMULT((MOD(q,TRANSPOSE(q))=0)*1,q^0)=2),b,TRANSPOSE(a),c,(a>b)*(A4-a*b),IF(XLOOKUP(c,a,a^0,0)*(b>c),a&" "&b&" "&c,"")))

```

Link to Spreadsheet

## Explantion

```
=TEXTJOIN(",",, ~ )                 # Separates multiple answers with a comma
  LET(q,SEQUENCE(A4),               # q = (1..A4) listed vertically
  a,FILTER(q, ~ ),                  # a = primes in q
    MMULT( ~,q^0)=2                 # a number is prime if the sum of the row is 2
      MOD(q,TRANSPOSE(q))=0)*1      # creates a qxq array where if row# mod column = 0 then 1 else 0
  b,TRANSPOSE(a),                   # b primes listed horizontally
  c,(a>b)*(A4-a*b),                 # 2-dim array where if a>b then c = A4 - a*b
  IF(XLOOKUP(c,a,a^0,0)*(b>c),~,"") # if c is prime and b>c then return value else ""
    a&" "&b&" "&c                   # a b c

```

## Insider Beta Version using LAMBDA, 157 bytes

```
=TEXTJOIN(",",,MAKEARRAY(A1,A1,LAMBDA(a,b,LET(c,MAX(A1-a*b,1),p,LAMBDA(x,SUM((MOD(x,SEQUENCE(x))=0)*1)=2),IF((a>b)*(b>c)*p(a)*p(b)*p(c),a&" "&b&" "&c,"")))))

```

# Answer
> 2 votes
# Vyxal, 10 bytes

```
~æ3ḋ'÷*+?=

```

Try it Online!

```
~          # Filter (implicit) range 1...n by...
 æ         # Is prime?
  3ḋ       # Combinations of length 3
    '      # Filtered by...
     ÷*+   # a*b+c
        ?= # Equals input?

```

Outputs a list of all valid lists.

# Answer
> 2 votes
# JavaScript (Node.js), 89 bytes

```
f=(n,b)=>p(b)&p(a=n/b|0)&p(c=n%b)&a>b?[a,b,c]:b!=n&&f(n,-~b);p=(n,i=n)=>n%--i?p(n,i):i==1

```

Try it online!

If stackoverflow allowed as an error, then

# JavaScript (Node.js), 83 bytes

```
f=(n,b)=>p(b)&p(a=n/b|0)&p(c=n%b)&a>b?[a,b,c]:f(n,-~b);p=(n,i=n)=>n%--i?p(n,i):i==1

```

Try it online!

# Answer
> 2 votes
# MATL, ~~28~~ ~~25~~ ~~24~~ 23 bytes

```
Zq"@tG-YfhXHd0>AHn3=*?H

```

Try it online!

```
Zq"   % for each prime less than (or equal to) the input
@t    % duplicate it on the stack
G-    % subtract it from the input
Yf    % get the prime factors of the result
h     % concatenate that with the current iterating prime
XH    % save that in the H clipboard
d0>A  % check that it's strictly increasing
Hn3=  % and has 3 elements
*?    % if both conditions are true
H     % push that result list back on the stack

```

Prints all valid results.

# Answer
> 2 votes
# Python 3, 137 bytes

```
lambda n:[(a,b,c)for a in R(n)for b in R(n)for c in R(n)if all([a>b>c,a*b+c==n,all(all(n%m for m in R(2,n))for n in (a,b,c)),c])]
R=range

```

Try it online!

Thanks to @attiP for `R=range` -8 bytes

# Python 3, 139 bytes

```
eval("lambda n:[(a,b,c)for aRfor bRfor cRif all([a>b>c,a*b+c==n,all(all(n%m for mR[2:])for n in (a,b,c)),c])]".replace("R"," in range(n)"))

```

Try it online!

# Answer
> 1 votes
# Ruby, ~~83~~ 78 bytes

```
->n{(2..n).select{|x|/^(!!+)\1+$/!~?!*x}.combination(3).find{|c,b,a|a*b+c==n}}

```

Try it online!

# Answer
> 1 votes
# Python 2, 112 bytes

```
P=k=1
p=r=[]
n=input()
while k<n:
 if P%k:r=r+[(k,b,n-k*b)for b in p if b>n-k*b in p];p+=k,
 P*=k*k;k+=1
print r

```

Try it online!

---

A port of l4m2's Javascript answer with a bit of their help comes in at ~~101~~ 99 bytes:

```
f=lambda n,b=1:all(p%k for p in(n/b,b,n%b)for k in range((n%b>1)+(n/b>b),p))*(n/b,b,n%b)or f(n,b+1)

```

Try it online!

# Answer
> 1 votes
# Jelly (fork), 10 bytes

```
ÆRUŒƈ×+ƭ/Ƙ

```

Try it online! (the Jelly equivalent)

Outputs all possible solutions, or `[]` if there are none. And, the equivalent vanilla Jelly answer:

# Jelly, 13 bytes

```
ÆRUœc3×+ƭ/=¥Ƈ

```

Try it online!

## How they work

```
ÆRUŒƈ×+ƭ/Ƙ - Main link. Takes an integer N on the left
ÆR         - Primes from 2 to N
  U        - Reverse
   Œƈ      - Combinations of 3, no replacement
         Ƙ - Keep those that equal N under:
        /  -   Reduce [a, b, c] by:
       ƭ   -     Tie two dyads f, g:
     ×     -       Product
      +    -       Addition
                This maps [a, b, c] -> [a×b, c] -> a×b+c

```

The normal Jelly one is identical, except that `œc3` is special-cased as `Œƈ` and `=¥Ƈ` is equivalent to `Ƙ`

# Answer
> 1 votes
# PowerShell Core, 176 bytes

```
param($n)for($c=1;++$c-lt$n){for($b=$c;++$b-lt$n){for($a=$b;++$a-lt$n){if($a*$b+$c-eq$n-and(&($p={param($t)!($t-2)-!(2..($t-1)|?{!($t%$_)})})$a)*(&$p $b)*(&$p $c)){$a,$b,$c}}}}

```

Try it online!

I tried using ranges, but it gets really slow, probably because it is allocating too many of them, so `for` for now :)

Slow draft with ranges, 175 bytes

# Answer
> 1 votes
# Husk, 14 bytes

```
ḟo=⁰§+←oΠtṖ3İp

```

Try it online!

Outputs c\<b\<a if a solution exists, otherwise quits after 1 minute with a 'the request exceeded the 60 second time limit and was terminated' warning from the 'try it online' interpreter.
Arguably this isn't a real 'error' (and Husk itself would happily run forever looking for a solution among higher and higher entries in the infinite list of primes), so for 1 more byte we can have:
`ḟo=¹§+←oΠtṖ3fṗḣ` (which only searches among primes less than the input).

```
ḟo              # return the first...
          Ṗ3    # ...list of 3 items selected from
            İp  # ...the infinite list of primes
                # that satisfies:
    §+          #   the sum of...
      ←         #   ...the first item
       oΠ       #   ...and the product of
         t      #   ...the tail (all except first item)
  =⁰            #   is equal to the input

```

# Answer
> 1 votes
# C (gcc), ~~139 130 122 118~~ 115 bytes

```
a,b,c,z,y;p(x){for(y=z=1;++z<x;)y&=x%z>0;y=!y;}f(n){for(a=n;a&&p(c=(c<3?b<3?b=--a-1:--b:c)-1)|p(b)|p(a)|a*b+c-n;);}

```

Try it online!

Slightly golfed less.

```
a,b,c,z,y;
p(x){
  y=z=1;
  for(;++z<x;)
    y&=x%z>0;
  y=!y;
}
f(n){
  a=n;
  while(a&&p(c=(c<3?b<3?b=--a-1:--b:c)-1)|p(b)|p(a)|a*b+c-n);
}

```

# Answer
> 1 votes
# 80386 Machine Code, ~~110~~ ~~107~~ 99 bytes

Try it online!

When there is no valid answer, the program crashes, and I hope this belongs to "raise an error" category.

---

Thanks for the wonderful tip for skipping instructions. I'm still trying to get rid of the `call`s which take 5 bytes each, but it's not clear for now.

`ecx` is the input number, and `edx` is the pointer to the output array

```
00000000 <f>:
0:  89 cf                   mov    edi,ecx
2:  31 db                   xor    ebx,ebx
4:  89 d8                   mov    eax,ebx
00000006 <L0>:
6:  e3 40                   jecxz  48 <err>
8:  83 f8 02                cmp    eax,0x2
b:  7f 0b                   jg     18 <_1>
d:  83 fb 02                cmp    ebx,0x2
10: 7f 03                   jg     15 <_0>
12: 49                      dec    ecx
13: 89 cb                   mov    ebx,ecx
00000015 <_0>:
15: 4b                      dec    ebx
16: 89 d8                   mov    eax,ebx
00000018 <_1>:
18: 48                      dec    eax
19: 89 c5                   mov    ebp,eax
1b: e8 29 00 00 00          call   49 <p>
20: 73 e4                   jae    6 <L0>
22: 89 dd                   mov    ebp,ebx
24: e8 20 00 00 00          call   49 <p>
29: 73 db                   jae    6 <L0>
2b: 89 cd                   mov    ebp,ecx
2d: e8 17 00 00 00          call   49 <p>
32: 73 d2                   jae    6 <L0>
34: 89 ce                   mov    esi,ecx
36: 0f af f3                imul   esi,ebx
39: 01 c6                   add    esi,eax
3b: 39 fe                   cmp    esi,edi
3d: 75 c7                   jne    6 <L0>
3f: 89 0a                   mov    DWORD PTR [edx],ecx
41: 89 5a 04                mov    DWORD PTR [edx+0x4],ebx
44: 89 42 08                mov    DWORD PTR [edx+0x8],eax
47: c3                      ret
00000048 <err>:
48: f4                      hlt
00000049 <p>:
49: 50                      push   eax
4a: 51                      push   ecx
4b: 52                      push   edx
4c: 89 e9                   mov    ecx,ebp
0000004e <L1>:
4e: 49                      dec    ecx
4f: 83 f9 02                cmp    ecx,0x2
52: 7c 0a                   jl     5e <end>
54: 89 e8                   mov    eax,ebp
56: 99                      cdq
57: f7 f1                   div    ecx
59: 85 d2                   test   edx,edx
5b: 75 f1                   jne    4e <L1>
5d: a8                      .byte 0xa8
0000005e <end>:
5e: f9                      stc
5f: 5a                      pop    edx
60: 59                      pop    ecx
61: 58                      pop    eax
62: c3                      ret

```

**output**

```
5 3 2
7 5 2
41 5 3
47 7 5

```

the original assembly code

# Answer
> 0 votes
# Python 3, 174 bytes

```
from itertools import*
f=lambda n:[i for i in [(a,b,c)for a,b,c in combinations([*range(n-1,-1,-1)],3)if a*b+c==n]if all(map(lambda n:all(n%i for i in range(2,n))==(n>1),i))]

```

Try it online!

# Answer
> 0 votes
# Python 3.8 (pre-release), 138 bytes

```
lambda i,F=lambda n:all(n%a for a in range(2,n)):[[j,k,l]for j in range(3,i)for k in range(3,i//j+1)if F(j)+F(k)+F(l:=i-j*k)>2<=l<k<j][:1]

```

Try it online!

Semi-brute-force method. Thanks AnttiP for spotting an obvious superfluous 5-byte segment.

# Answer
> 0 votes
# Retina 0.8.2, 120 bytes

```
.+
$*
^(11(1)+)(?<!^\3+(11+))((?<9-2>\1))+(?!1?$|(11+)\5+$)((?<-4>1)+)$(?<=(?!(11+)\7+$)((?>1(?<-9>1)+)))|.+
$.1 $.8 $.6

```

Try it online! Link includes test cases. Explanation:

```
.+
$*

```

Convert to unary.

```
^(11(1)+)(?<!^\3+(11+))

```

Search for a prime number `a` (`$.1` or `2+$#2`)...

```
((?<9-2>\1))+

```

... that when repeated `b` (`1+$#4` or `1+$#9`) times (`$#4`/`$#9` is less than or equal to `$#2` so `b` is less than `a`)...

```
(?!1?$|(11+)\5+$)((?<-4>1)+)$

```

... leaves a remainder `c` (`$.6`) that is prime (`$.6` is less than or equal to `$#4` so `c` is less than `b`)...

```
(?<=(?!(11+)\7+$)((?>1(?<-9>1)+)))

```

... and `b` (`$.8`) is prime.

```
|.+

```

But if a match couldn't be found, replace the input anyway.

```
$.1 $.8 $.6

```

Replace the input with the desired values.

# Answer
> 0 votes
# 05AB1E, 10 bytes

```
ÅP3.Æʒ`*+Q

```

Outputs the triplets in the order \\$\[c,b,a\]\\$.

Try it online or verify all test cases.

**Explanation:**

```
ÅP          # Push a list of prime numbers ≤ the (implicit) input-integer
  3.Æ       # Get all unique 3-element combinations of this list
     ʒ      # Filter these [c,b,a]-triplets by:
      `     #  Pop and push c,b,a separated to the stack
       *    #  Multiply the top two: b*a
        +   #  Add it to the third: c+b*a
         Q  #  Check if it's equal to the (implicit) input-integer
            # (after which the filtered list of triplets is output implicitly)

```

# Answer
> 0 votes
# Charcoal, 39 bytes

```
ＮθＩΦＥ…²θ⟦ι÷θι﹪θι⟧∧⬤⊞ＯΦιμ¹‹λ§ιμ⬤ι⬤…²λ﹪λν

```

Try it online! Link is to verbose version of code. Outputs all solutions. Explanation: Test all values `a` from `2` up to `n` and checks that the list `[a, n/a, n%a, 1]` is descending and that the first three elements are prime. Conveniently this optimised version turns out to be golfier than a naïve brute force algorithm.

```
Ｎθ                                      Input as an integer
     …                                  Range from
      ²                                 Literal integer `2`
       θ                                To input integer
    Ｅ                                   Map over values
         ι                              Current value
           θ                            Input integer
          ÷                             Integer divided by
            ι                           Current value
              θ                         Input integer
             ﹪                          Modulo
               ι                        Current value
        ⟦       ⟧                       Make into a list
   Φ                                    Filtered where
                       ι                Current list
                      Φ                 Filtered where
                        μ               Inner index
                   ⊞Ｏ                  Concatenated with
                        ¹               Literal integer `1`
                  ⬤                     All values satisfy
                          λ             Current value
                         ‹              Is less than
                            ι           Current list
                           §            Indexed by
                             μ          Inner index
                 ∧                      Logical And
                               ι        Current list
                              ⬤         All elements satisfy
                                 …      Range from
                                  ²     Literal integer `2`
                                   λ    To current element
                                ⬤       All values satisfy
                                     λ  Current element
                                    ﹪   Is not divisible by
                                      ν Innermost value
  Ｉ                                         Cast to string
                                            Implicitly print

```

# Answer
> 0 votes
# Japt, 16 bytes

... So *very* out of practice. Returns all possible solutions, each in reverse order.

```
o ðj à f@¶XÎ+XÅ×

```

Try it

# Answer
> 0 votes
# BQN, 37 bytesSBCS

Main idea taken from l4m2's answer.

```
(∨⊸≡∧´(1=·+´0=↕⊸|)¨)¨⊸/⊢(⌊÷∾⊢∾|˜)¨1↓↕

```

Run online!

# Answer
> 0 votes
# APL (Dyalog Unicode) \+ dfns, 29 bytes

I spent a bit too much time trying to golf RGS's answer, so I decided to post this on its own now.

```
{m⌿⍨⍵=2(⌷+0⌷×⌿)⍉m←pco⌽3cmat⍵}

```

Try it online!

There are two significant differences compared to the original answer:

* When `pco` is applied to a single argument, it returns the ⍵-th prime number. This can be used to construct triples of primes directly, avoiding a more complicated primality test.
* The implementation for \\$a\times b+c\\$ is a bit shorter using dyadic `/` to get the product.

# Answer
> 0 votes
# Julia 0.4, 62 bytes

```
N->for a=P=primes(N),b=P,c=P a>b>c&&a*b+c==N&&return a,b,c end

```

Try it online!

Julia 0.4 for the `primes` function (later moved in the `Primes` package). Returns `nothing` is there is no solution

# Answer
> 0 votes
# Haskell, 91 bytes

```
f n=[[a,b,c]|a<-q$n+1,b<-q a,c<-q b,a*b+c==n,and[0<mod y x|y<-[a,b,c],x<-q y]];q z=[2..z-1]

```

Try it online!

---
Tags: code-golf, math, integer, primes
---


# Question
Title: Convert 256-wrap brainfuck into 257-wrap brainfuck
Usually each cell in brainfuck has 256 states, which is not enough to tell whether input is EOF or a character (usually `\xFF`). To fix it we can add one more state to it, and EOF (256) isn't mistake from a byte.

Since outputting EOF is also not defined, `.` on 256 works as reading, and therefore `,` is removed from the modified version.

Given a program in the 256-wrap brainfuck, provide a 257-wrap brainfuck program with same behavior when an infinite stream is provided as input. Memory needn't remain same though.

Sample:

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

```

This is , shortest code (converter) in each language wins.

# Answer
# Python 3.8 (pre-release), 87 86 bytes

```
lambda s:"".join([3*c,p:="++[->>+<]>[-<]<","[-]-.",p*255,c][ord(c)%31%11%7]for c in s)

```

Try it online!

Basically the idea is that we only use every third cell to store the memory that the input program uses. The other cells are simply zero. This gives space to implement the addition code. The addition code is as follows:

`++[->>+<]>[-<]<`

Let's see how this works. There are two possibilities, either the cell has value of `255` or it has a lower value.

If the cell has value `255` then, after the first additions the value of the cell is now `0` (since it's mod 257). This means that the next loop won't execute at all. So we skip the first loop and move right. This square is 0, so we won't execute the next loop and we finally move left, back to the starting square, which has now value 0, meaning that we succeeded in doing `255->0`.

If the cell has some other value `x`, the first two additions will make the value of the cell `x+2` which is not zero. This means that the next loop will execute. We decrement this cell (value now is `x+1`) and move twice to the right. We increment that cell (now has value `1`) and move left. The cell we are on right now has also value 0, so the loop stops. We then move right, to find our cell which has value 1. We decrement it to leave it in a clean state and move left. Again, this cell has value 0, so the loop stops. Finally we move left once to get back to where we started, with the cell having value `x+1`

Decrementation is just addition 255 times. `[`, `.` and `]` don't need to be changed. We triplicate `>` and `<` since every third cell stores the "original" program values. Actually, we also triplicate `[` and `]`, but this doesn't have any effect on the execution of the program. For `,` we just zero the cell with `[-]` and then decrement once more to get value 256 and then use the dot.
> 5 votes

---
Tags: code-golf, code-generation, brainfuck
---


title: Print Every Code Golf tag

text:
# Question
Title: Print Every Code Golf tag
*Huge omega thanks to @wasif for emailing me this challenge idea in its basic form*

Everyone knows that questions on StackExchange require tags - labels that allow posts to be grouped together by category. However, most of the time, I barely know which tags exist, because there's just *so many* of them. Henceforth, today's task is to tell me every single tag that exists on the Code Golf and Coding Challenges Stack Exchange.

## The Challenge

Write a program or function that prints/returns a list of all available tags on https://codegolf.stackexchange.com As tags can be created/deleted at any time, simply hard-coding a list of tags is not a valid solution - the list must be correct at run-time regardless of when the program/function is executed. The tags avaliable can be seen here

## Rules

* As this is an challenge, internet connections are allowed. However, web requests can only be made to codegolf.stackexchange.com and api.stackexchange.com domains.
* Output can be given in any convenient and reasonable format.
* The tags can be in any order, so long as all current tags are returned.
* The exact name of the tags must be used (e.g. `code-golf` is valid, `code GOLF` is not valid.)
* And as usual, standard loopholes apply, shortest code wins

## Example Program

```
import urllib.request
import regex

pobj = regex.compile('rel="tag">(.*)</a>')
page_number = 2
req = urllib.request.urlopen(f"https://codegolf.stackexchange.com/tags?page=1&tab=name")
data = req.read().decode('utf-8')
tags = []
while data.count("tag") != 43:
    tags += pobj.findall(data)
    req = urllib.request.urlopen(f"https://codegolf.stackexchange.com/tags?page={page_number}&tab=name")
    data = req.read().decode('utf-8')
    page_number += 1

print(tags)

```

# Answer
> 10 votes
# 05AB1E, ~~60~~ ~~57~~ 56 bytes

```
[N>’¸¸.Â‚‹º.ŒŒ/›´?€¼=ƒËŠˆ&€®=ÿ’.wD2è'eQ#“e":"“¡¦ε'"¡н]\)

```

Outputs as a list of pages, where each page is a list of tags.

```
[N>’...’.wD2è'eQ#“e":"“¡¦ε'"¡н]\)  # trimmed program
[               #                  # while...
            è                      # character in...
        .wD                        # data of response from URL...
                                   # (implicit) "http://" concatenated with...
   ’...’                           # "api.stackexchange.com/tags?site=codegolf&page=ÿ"...
                                   # (implicit) with ÿ replaced by...
 N                                 # current index in loop...
  >                                # plus 1...
            è                      # at index...
           2                       # literal...
                #                  # is not...
               Q                   # equal to...
             'e                    # literal...
        .w                         # push data of response from URL...
                                   # (implicit) "http://" concatenated with...
   ’...’                           # "api.stackexchange.com/tags?site=codegolf&page=ÿ"...
                                   # (implicit) with ÿ replaced by...
 N                                 # current index in loop...
  >                                # plus 1...
                       ¡           # split by...
                 “e":"“            # literal...
                        ¦          # excluding the first...
                         ε         # with each element replaced by...
                             н     # first element of...
                                   # (implicit) current element in map...
                            ¡      # split by...
                          '"       # literal
                              ]    # exit map
                              ]    # exit infinite loop
                               \   # delete top element of stack
                                )  # push stack
                                   # implicit output

```

# Answer
> 8 votes
# Jyxal 0.2.0, 44 bytes

```
0{›:`ȯø.⟩β•∵.•⅛/ɾƈ?λ→=%&λẋ=¬⋎»₅`%¨UøJht(ntt,

```

Jyxal-is-not-hosted-anywhere-so-read-the-readme-to-see-how-to-try-this

Fixed thanks to @emanresu A

Absolutely crushes 05AB1E. On my machine, it goes through the first 25 pages before getting a 403 and printing `4` forever. Unfortunately, Vyxal cannot decompress zipped responses so I kinda had to use Jyxal in place. This is heavily dependent on the ordering of the values in the JSON response.

```
0{›:`ȯø.⟩β•∵.•⅛/ɾƈ?λ→=%&λẋ=¬⋎»₅`%¨UøJht(ntt, # I don't need the 2 closing parens at the end.
0                                            # Push 0 (Jyxal does not have implicit input yet)
 {                                           # Loop forever
  ›                                          # And increment the number
                                %            # Replace all "%" in the string...
    `ȯø.⟩β•∵.•⅛/ɾƈ?λ→=%&λẋ=¬⋎»₅`             # "api.stackexchange.com/tags?page=%&site=codegolf"
   :                                         # With the current loop index
                                 ¨U          # Make a GET request to that URL...
                                   øJ        # And decode the JSON response
                                     h       # Get the first key-value pair...
                                      t      # And the second item; that is, the "items" array
                                       (n    # For each item in that array...
                                         t   # Get the last key-value pair and then...
                                          t  # Get the value
                                           , # Print that value

```

# Answer
> 7 votes
# Python 3 + `requests`, 143 bytes

```
from requests import*
p=1
while[print(x["name"])for x in get(f"http://api.stackexchange.com/tags?page={p}&site=codegolf").json()["items"]]:p+=1

```

-19 bytes thanks to Jonathan Allan
-5 bytes thanks to dingledooper

# Answer
> 5 votes
# JavaScript (Firefox chrome), 135 bytes

```
f=async(i=1)=>(await((await fetch('http://codegolf.stackexchange.com/tags?page='+i)).text())).match(/[\w-]+(?=&#3)/g).map(alert)|f(i+1)

```
1. ~~Open Browser Console of Firefox;~~ You may however open console on this page instead;
2. Paste codes there;
3. Invoke it by running `f()`;
4. Click to close many many `alert`'s

---

Source codes for tags page contains line

```
<a href="/questions/tagged/code-golf" class="post-tag" title="show questions tagged 'code-golf'" rel="tag">code-golf</a>

```

We match the text `code-golf` between `'` by `/[\w-]+(?=&#3)/g`.

The recursion terminate when ith page contains no tags. While the match result is null, and `.map` on `null` cause an error.

# Answer
> 4 votes
# JavaScript, 176 bytes

```
async _=>{t=[];i=1;do t.push(...(j=await (await fetch("http://api.stackexchange.com/2.2/tags?site=codegolf&page="+i++)).json()).items);while(j.has_more)return t.map(d=>d.name)}

```

Must be run on `api.stackexchange.com` subdomain; I use `/docs` for testing.

# Answer
> 3 votes
# Bash \+ wget + jq, 86

Assumes there are no more than 99 pages of results (currently 10 pages).

```
wget -qO- api.stackexchange.com/tags?site=codegolf\&page={1..99}|zcat|jq .items[].name

```

Testing this blew through my daily API requests limit pretty quick.

---
Tags: code-golf, internet
---