# Question
Title: Output integers in negative order, increase the maximum integer everytime
# Main task

Your task is to print out integers in descending order, starting from 1, and increasing as you keep hitting 1 again, up until the given input is reached, then, print out the rest until you hit 1 again. Example with input `6`:

```
1
21
321
4321
54321
654321
Without newlines (valid output):
121321432154321654321

```
*Side note: this is A004736 in the OEIS. Also, the first example (with newlines) is an invalid output, as specified in the rules.*

# Input

Your code may take any kind of input (graphical, STDIN) in the form of an integer or number.

# Output

Your code should output the above described sequence, up until the input number is reached, then finish to output until it reaches 1 again. The output may be anything, therefore numbers, strings, integers, or graphical output. It is required to print out a single number (no newlines if it's a string). Your output can be in- and outroduced with as many characters as you need (e.g. `[]`).

Since there was some misunderstanding, here's a regex pattern you can try your outputs on.

```
^(\D*(\d)+\D*)$

```

# Rules

* The output must be a full number, not split up by anything, not even newlines.
* The algorithm shouldn't check for the first instance of N appearing in any way (e.g. the `21` in `121321`), but rather for the first instance of N as the actual number.
* A single trailing newline is allowed.
* The handling for negative input is fully your choice, negative numbers aren't cases you should test.

## Test cases

```
Input: 6
Output: 121321432154321654321

Input: 1
Output: 1

Input: 26
Output: 121321432154321654321765432187654321987654321109876543211110987654321121110987654321131211109876543211413121110987654321151413121110987654321161514131211109876543211716151413121110987654321181716151413121110987654321191817161514131211109876543212019181716151413121110987654321212019181716151413121110987654321222120191817161514131211109876543212322212019181716151413121110987654321242322212019181716151413121110987654321252423222120191817161514131211109876543212625242322212019181716151413121110987654321

Input: 0
Output: 0, Empty, or Error

Input: 21
Output: 121321432154321654321765432187654321987654321109876543211110987654321121110987654321131211109876543211413121110987654321151413121110987654321161514131211109876543211716151413121110987654321181716151413121110987654321191817161514131211109876543212019181716151413121110987654321212019181716151413121110987654321

```
Thanks @Emigna, I used his algorithm to calculate these test cases.

## Winner

The winner has been chosen! It was ErikGolfer's answer with an impressive **5** bytes! Congratulations!

# Answer
# Jelly, 5 bytes

```
RRUVV

```

Try it online!

Formula not mine.

I suspect there is too much going on here...

\[ANSWER ACCEPTED\] I'd have given some 5 rep to Dennis, but this is not Reputation Exchange. Dennis showed me the `VV` behavior. To my surprise, this is shorter than 05AB1E.
> 13 votes

# Answer
# 05AB1E, 6 bytes

```
L€LíJJ

```

Try it online!

**Explanation**

Example input 4

```
L       # range [1 ... input]
        # STACK: [1,2,3,4]
 €L     # map: range
        # STACK: [[1],[1,2],[1,2,3],[1,2,3,4]]
   í    # reverse each
        # STACK: [[1],[2,1],[3,2,1],[4,3,2,1]]
    J   # join inner lists
        # STACK: ['1','21','321','4321']
     J  # join list
        # OUTPUT: 1213214321

```
> 19 votes

# Answer
## JavaScript (ES6), 37 bytes

```
f=(n,k=1)=>k>n?n--?f(n):'':f(n,k+1)+k

```

### Demo

```
f=(n,k=1)=>k>n?n--?f(n):'':f(n,k+1)+k

console.log(f(6))
```

### Alternate method for n \< 10, 34 bytes (non-competing)

```
f=(n,s='1')=>--n?s+f(n,++s[0]+s):s

```

In JavaScript, strings are immutable. Therefore, it's impossible to alter the content of the Nth character of a string `s` by assigning a new value to `s[N]`.

However, the expression `++s[N]` is valid and does evaluate as one would expect, even if the string remains unchanged. For instance:

```
++"1"[0] // equals 2

```

And by extension:

```
s = "21"
++s[0] + s // equals "321"

```
> 13 votes

# Answer
# V, ~~29~~ ~~28~~ ~~27~~ ~~23~~ ~~19~~ ~~17~~ 16 bytes

***8*** *bytes saved thanks to @DJMcMayhem*

***3*** *bytes saved thanks to @nmjcman101*

```
"apÀñÄòy$jpkgJ

```

Hidden characters:

```
"apÀ<C-x>ñÄ<C-x>òy$jpkgJ

```

`C-x` is Ctrl+x.

Try it online! takes input via command-line arguments

Hexdump:

```
0000000: 2261 70c0 adf1 c418 f279 246a 706b 674a  "ap......y$jpkgJ

```

### Explanation

```
"ap            Paste the argument
À<C-x>         Argument minus 1 times (so that we exclude the 0)
ñ ... ò        Loop (for some weird reason the ò closes the ñ)
Ä<C-x>         paste current line above and decrement it

```

Now it looks like:

```
1
2
...
n

```

*continued...*

```
ò             recursively do (until a breaking error)
y$             yank this line
  jp           paste it down
    kgJ        go up and join
              implicit ò end

```

### GIF (outdated)

(for arg `6`)
> 12 votes

# Answer
# C#, ~~72~~ ~~69~~ 65 bytes

```
n=>{for(int i=0,j;i<n;)for(j=++i;j>0;)System.Console.Write(j--);}

```

If the output can just be returned as opposed to being Written to the console

# C#, ~~71~~ ~~68~~ 64 bytes

```
n=>{var s="";for(int i=0,j;i<n;)for(j=++i;j>0;)s+=j--;return s;}

```

Thanks to @VisualMelon for saving a lot of bytes

Test it here (Humourously the online compiler breaks at any number above 420)
> 11 votes

# Answer
## Perl, 21 bytes

**Uses `-E` at no extra cost.**

```
say map$}=$_.$},1..<>

```

### Usage

```
perl -E 'say map$}=$_.$},1..<>' <<< 6
121321432154321654321

```
> 8 votes

# Answer
# Pure bash, 34

```
eval eval printf %s \\{{1..$1}..1}

```

Two levels of brace expansion. With input `6`, the first level expands to `{1..1} {2..1} {3..1} {4..1} {5..1} {6..1}`. This then expands to `1 2 1 3 2 1 4 3 2 1 5 4 3 2 1 6 5 4 3 2 1`, which is smushed together to one string with `printf %s`. `eval`'s are required at both levels of expansion - for the first level so that the `$1` parameter is expanded first, and for the second level so that it expands after the first level.

Try it online
> 8 votes

# Answer
# Pyth, 7 bytes

```
jks}R1S

```

A program that takes input of an integer and prints the result.

Try it Online!

**How it works**

```
jks}R1S   Program. Input: Q
jks}R1SQ  Implicit input fill
    R     Map
      SQ  over [1, 2, 3, 4, ..., Q] with i:
   } 1     Yield [i, i-1, i-2, i-3, ..., 1]
  s       Merge
jk        Join
          Implicitly print

```
> 7 votes

# Answer
# GeoGebra, 67 bytes

```
1
InputBox[a]
Sum[Join[Sequence[Sequence[Text[j],j,i,1,-1],i,1,a]]]

```

Each line is entered separately into the input bar. Input is taken from an input box.

Here is a gif of the execution:

**How it works**

Entering `1` implicitly assigns `a` to `1`, and the `InputBox` command associates an input box with `a`. Then, for each `i` in `{1, 2, 3, ..., a}`, the list `{i, i-1, i-2, ..., 1}` is created using the `Sequence` command, and each `j` in that list is converted to a string using `Text`. Finally, `Join` merges all the lists, and `Sum` concatenates all the elements to one text object, which is displayed.
> 7 votes

# Answer
## Retina, ~~26~~ 22 bytes

Byte count assumes ISO 8859-1 encoding.

```
.+
$*

$`¶
1
$.%'
0?¶

```

Try it online!

### Explanation

```
.+
$*

```

Convert input to unary.

```

$`¶

```

At each position, insert the prefix up to that point, as well as a linefeed. This creates a unary range from `2` to `n+1`, one value per line.

```
1
$.%'

```

Replace each `1` with the number of characters after it on the same line. This turns something like `11111` into `43210`.

```
0?¶

```

Remove all linefeeds and the zeros preceding them.
> 7 votes

# Answer
## Python 2, 51 bytes

```
r=s=''
n=0
exec'n+=1;s=`n`+s;r+=s;'*input()
print r

```
> 7 votes

# Answer
# GameMaker Language, 65 bytes

```
b=""for(i=1;i<=argument0;i++){c=i while(j)b+=string(c--)}return b

```
> 5 votes

# Answer
# Actually 8 bytes

```
RR♂RΣRεj

```

First time posting an answer in Actually so it probably can be golfed.

**How it works**

```
Program takes implicit input, implicit print at EOF
R           Takes the input and creates a range (1, input)
                STACK = [1,2,..,n]
 R          Reverse the top stack item (our range)
                STACK = [n,..,2,1]
  ♂R        For each item in our range, create a range (1, rangeitem)
                STACK = [[1,2,..,n], .., [1,2], [1]]
    Σ       Stitch the items of the list together
                STACK = [n,..,1,2,3,1,2,1]
     R      Reverse the top stack item again (our answer)
                STACK = [1,2,1,3,2,1,..n]
      εj    Create an empty string and append each item from the list to it.
            (turns non string items into strings)

```

Try it online!
> 5 votes

# Answer
# APL, 10 bytes

```
∊⍕¨∘⌽∘⍳¨∘⍳

```

E.g.:

```
      (∊⍕¨∘⌽∘⍳¨∘⍳)6
121321432154321654321

```

Explanation:

* : get the numbers from 1 to N.
* `⍳¨∘`: for each of those, get the numbers from 1 to N.
* `⌽∘`: reverse that list
* `⍕¨∘`: get the character representation of each item (so it does not output the numbers with spaces in between)
* : flatten the resulting array
> 5 votes

# Answer
# Python 2, ~~71~~ 68 bytes

I bet a recursive solution could be shorter, but I'm having a hard time formulating this into one.

```
n=input()
i=0
o=""
while i<n:
    i+=1;j=i
    while j:o+=`j`;j-=1
print o

```

**Try it online**
> 5 votes

# Answer
# Python 3, 87 92 83 74 bytes

```
lambda n:"".join(["".join([str(i)for i in range(1,k)][::-1])for k in range(1,n+2)])

```

Shorter answer using recursion :

```
f=lambda n:f(n-1)+"".join([str(i)for i in range(1,n+1)][::-1])if n>0else""

```

Maybe not the shortest one but it's only made with Python's list comprehension !

*(Edited to add the print function and remove the \n)*

*(Edited to remove the print function, and change n+1, k+1 to n,k+2)*
> 4 votes

# Answer
# Brachylog v1, 8 bytes

```
yb@[rcw\

```

Try it online!

### Explanation

```
yb         The list [1, ..., Input]
  @[       Take a prefix of that list
    rc     Reverse it and concatenate into an integer
      w    Write to STDOUT
       \   Backtrack: try another prefix

```
> 4 votes

# Answer
# C89, 54 bytes

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

```

56 -2 = 54 thanks to ErikGolfer!
> 4 votes

# Answer
# Perl 6, 22 bytes

```
{[~] flat [\R,] 1..$_}

```

A lambda that returns a string.

(Try it online.)

### Explanation:

* `1..$_`: Range of integers... `(1 2 3 4)`
* `[,] 1..$_`: Reduce ("fold") over comma operator... `(1 2 3 4)`
* `[\,] 1..$_`: With intermediate results (triangular reduce)... `((1) (1 2) (1 2 3) (1 2 3 4))`
* `[\R,] 1..$_`: Apply reversing meta-operator to the comma... `((1) (2 1) (3 2 1) (4 3 2 1))`
* `[~] flat ...`: Remove list nesting, and fold over string concat operator... `1213214321`
> 4 votes

# Answer
## Haskell, 35 bytes

```
f x=[1..x]>>= \y->[y,y-1..1]>>=show

```

Usage example: `f 6` -\> `"121321432154321654321"`.

For all numbers `x` in `1 ... x` make a list `x,x-1, ... ,1`, turn the numbers into a string and concatenate them into a single string. Again, concatenate those strings into a single string.
> 4 votes

# Answer
# Pyth, 8 bytes

```
jks_M._S

```

### Explanation

```
jks_M._SQ   Implicit input
       SQ   Get the range [1, 2, ..., N]
     ._     Get each prefix
   _M       Reverse each prefix
jks         Join everything as a string

```
> 3 votes

# Answer
# 05AB1E, 6 bytes

```
LR.sJJ

```

Try it online!
> 3 votes

# Answer
# R, ~~38~~ ~~33~~ 44 bytes

```
if((n=scan())>0)for(i in 1:n)cat(i:1,sep="")

```

Takes input to STDIN, and loops from 1 to n, creating the sequence i to 1 for each step and printing it.

Edit: replaced `seq(i,1)` by `i:1` saving 5 bytes and showing why I shouldn't golf during meetings.
> 3 votes

# Answer
## Mathematica, 36 bytes

```
ToString/@(""<>Range[Range@#,1,-1])&

```

Throws a bunch of warnings which can be safely ignored.

### Explanation

Using input `5` as an example:

```
Range@#

```

Creates a range `{1, 2, 3, 4, 5}`.

```
Range[...,1,-1]

```

`Range` is listable so we can give it a list for any of its arguments and it will automatically thread over that argument. So this gives us a bunch of reversed lists:

```
{{1}, {2, 1}, {3, 2, 1}, {4, 3, 2, 1}, {5, 4, 3, 2, 1}}

```

Next:

```
(""<>...)

```

This joins the nested list with the empty string. Since the nested list doesn't actually contain any strings, it can't really join the values (which is where the warnings are generated), but `""<>` has the side-effect of flattening the list. So this gives us

```
1 <> 2 <> 1 <> 3 <> 2 <> 1 <> 4 <> 3 <> 2 <> 1 <> 5 <> 4 <> 3 <> 2 <> 1

```

Now comes Mathematica's beautiful feature that `Map` doesn't care about the structure it's mapping over. You normally apply it to a list, but it works with any head. `f /@ h[a, b, c]` simply gives you `h[f[a], f[b], f[c]]`. In our case, the head is `StringJoin` and the values are the integers.

```
ToString/@...

```

So this simply turns the integers into strings. At that point `StringJoin[...]` knows what to do with them and joins them all into a single string:

```
"121321432154321"

```
> 3 votes

# Answer
# GolfScript, 14 bytes

```
~,{),{)}%-1%}%

```

Try it online!

Usual method of course, but this is GolfScript.

Explanation for this **VAST** piece of code:

```
~,{),{)}%-1%}% # Code
               # Initial stack.      ["n"]
~              # Eval ToS.           [n]
 ,             # ToS' lowered range. [[0..n)]
  {),{)}%-1%}  # Block. 1 argument.  [a]
   )           # Increment.          [a+1]
    ,          # Range.              [[0..a)]
     {)}       # Block. 1 argument.  [b]
      )        # Increment.          [b+1]
        %      # Map.                [[1..a]]
         -1    # Integer. -1         [[1..a] -1]
           %   # Each nth element.   [[a..1]]
             % # Map.                [[[1],[2,1],...,[n..1]]]
               # Implicit output.    121...n..1

```

Note that output is as a single number. Trailing `\n`.
> 3 votes

# Answer
# MATL, ~~14~~ 11 bytes

```
:"@:P]v!VXz

```

Try it online!

### Explanation

```
:      % Input N implicitly. Push range [1 2 ...N]
"      % For each k in [1 2 ...N]
  @:   %   Push range [1 2 ... k]
  P    %   Reverse
]      % End
v!     % Concatenate all arrays horizontally
V      % Convert to string
Xz     % Remove spaces. Display implicitly

```
> 3 votes

# Answer
# Python, ~~63~~ ~~57~~ 59 bytes

A recursive solution that works in both Python 2 and 3. This can probably be golfed further. Golfing suggestions welcome! Try it online!

**Edit:** -6 bytes thanks to Jonathan Allan. +2 bytes with thanks to mbomb007 for pointing out a problem with my answer.

```
f=lambda n:n and f(n-1)+"".join(map(str,range(n,0,-1)))or""

```

**Ungolfing**

```
def f(n):
    s = ""
    for i in range(n+1):
        m = map(str, range(n, 0, -1))
        s += "".join(m)
    return s

```
> 3 votes

# Answer
# brainfuck, 17 bytes

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

```

## Explanation

```
>           keep the first cell at 0
 ,          input of the decimal number into the cell
  [>        start a conditionnal loop and go to the next cell
   [+.>]    while it don't find 0, increment each cells and output the value
    +.      increment the new cell and output
     [<]    go to the first cell
      >-]   decrement the second cell and restart

```

Try it online!
> 3 votes

# Answer
# PHP, ~~35~~ ~~34~~ 33 bytes

*Saved a byte because I miscounted, thanks Titus! And another!*

```
while($i++<$argv[1])echo$s=$i.$s;

```

Run from command line with `-r`.

Pretty simple answer, loops from 1 through our input `n`, tacking the number onto the beginning of the string and printing it out.
> 2 votes

# Answer
# CJam, 13 bytes

```
ri,:){,:)W%}%

```

interpreter
> 2 votes

# Answer
# Brachylog (v2), 7 bytes

```
⟦₁⟧₁ᵐcc

```

Try it online!

Function submission. (The TIO link contains a command-line argument to run a function as though it were a full program.)

This would be just five bytes if the sequences went down to 0 rather than 1 – so it seems that this is one of those questions that's decided by the choice of 0- versus 1-indexing.

## Explanation

```
⟦₁⟧₁ᵐcc
⟦₁       Range from 1 to {the function input}
    ᵐ    On each element of that range,
  ⟧₁       take a descending range from that value to 1
     c   Concatenate the ranges
      c  Concatenate the digits of the resulting numbers

```
> 2 votes

# Answer
# C#, 67 65 bytes

```
f=n=>{int x=n;var r="";while(n>0)r+=n--;return x>0?f(x-1)+r:"";};

```

Anonymous recursive function which returns the required string.

Full program with ungolfed method and test cases:

```
using System;

public class Program
{
    public static void Main()
    {
        Func<int, string> f = null;
        f = n =>
        {
            int x = n;
            var r = "";
            while (n > 0)
                r += n--;
            return x > 0 ? f(x - 1) + r : "";
        };

        Console.WriteLine(f(6));    // 121321432154321654321
        Console.WriteLine(f(1));    // 1
        Console.WriteLine(f(26));   // 121321432154321654321765432187654321987654321109876543211110987654321121110987654321131211109876543211413121110987654321151413121110987654321161514131211109876543211716151413121110987654321181716151413121110987654321191817161514131211109876543212019181716151413121110987654321212019181716151413121110987654321222120191817161514131211109876543212322212019181716151413121110987654321242322212019181716151413121110987654321252423222120191817161514131211109876543212625242322212019181716151413121110987654321
        Console.WriteLine(f(0));    // "" (empty string)
    }
}

```
> 1 votes

# Answer
# Octave, ~~47~~ 48 bytes

```
@(n)num2str((g=meshgrid(n:-1:1)')(g<=1:n)','%d')

```

Try it online!

Explanation:

`meshgrid(n:-1:1)'` :create a grid of repeated `n:1`

```
   6   6   6   6   6   6
   5   5   5   5   5   5
   4   4   4   4   4   4
   3   3   3   3   3   3
   2   2   2   2   2   2
   1   1   1   1   1   1

```

`(g<=(1:n))` :only select those elements that are under anti-diagonal

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

```
> 1 votes

# Answer
## JavaScript, 53 bytes

`f=(n,s='',x=n)=>{while(n)s+=n--;return x?f(--x)+s:''}`

Thanks Titus for saving me bytes!
> 1 votes

# Answer
# PowerShell, 41 bytes

```
1..$args[0]|%{$a+=-join($_..1)};,$a-ne101

```

Try it online!

(*7 bytes to handle the special case of `0` for input*)

Loops from `1` up to the input `$args[0]`, each iteration concatenates onto `$a` the result of a `-join` operation operating on the range from the current number `$_` down to `1`. Then, we turn `$a` into an array `,` and select those elements of the array that are `-n`ot`e`qual to `101` (this filters out the `0` input). That's left on the pipeline and output is implicit.

NB -- Since strings in PowerShell (and .NET) are based on the StringBuilder class which is a `char` array, the maximum length we can get to is `2^31-1`. But, PowerShell on your desktop will likely run out of memory before then, and TIO has an output limit of `256 KiB`, so the actual maximum value supported is quite a bit smaller than that.
> 1 votes

# Answer
## QBIC, 25 bytes

```
:[a|[b,1,-1|A=A+_t!c$|}?A

```

Sample run:

```
Command line: 10
12132143215432165432176543218765432198765432110987654321

```

Explanation:

```
:           Get 'a' from the command line
[a|         FOR b=1; b<=a; b++
[b,1,-1|      FOR c=b; c>=1; c--
A=A+_t!c$|      Append c to the 'output buffer' A$
}           Close the FOR loops
?A          Print 'a'

```

Non-competing: five minutes ago, I taught QBIC to do implicit printing on exit of anything stored in `Z$`. That brings the code for this challenge down to ~~22 bytes~~ 19 bytes since I've made the cast-to-string autotrim!

```
:[a|[b,1,-1|Z=Z+!c$

```
> 1 votes

# Answer
# Scala, 22 bytes

```
1 to _ map(_ to(1,-1))

```

Returns a sequence of sequences of ints.

Usage:

```
val f:(Int=>Seq[Seq[Int]])=1 to _ map(_ to(1,-1))
println(f(6))

```

Ungolfed:

```
n=>1 to n map(i=>i to 1 by -1)

```

Explanation:

```
1 to _      //create a Range from 1 to the argument of this function
map(        //map each element to...
  _ to(1,-1)  //a range from the number to 1, in steps of -1
)

```
> 1 votes

# Answer
# bash, 69 bytes

```
f()([ $1 = 0 ]||(echo -n $1;f $[$1-1]));[ $1 = 0 ]||($0 $[$1-1];f $1)

```

f is a recursive function, and the entire script is recursive too.

*Edit:* @DigitalTrauma posted an improved version of this, which you can see in his comment on this answer. I'm not going to take the time to modify the answer, since he also posted a completely different bash solution, using brace expansion, that blows this answer away!
> 1 votes

# Answer
# Mathematica, ~~38~~ 54 bytes

```
FromDigits@*Flatten@IntegerDigits@Range[Range@#,1,-1]&

```

I stole `Range[Range@#,1,-1]` from Martin Ender's (still shorter) answer to save three bytes (dammit, I gotta start remembering that some functions are Listable). `IntegerDigits` converts the multi-digit numbers in the result to lists of single digits, `Flatten` removes all the list nesting, and `FromDigits` reassembles them into an integer. Oh well.
> 1 votes

# Answer
# PHP, ~~52~~ 49 bytes

```
<?for(;$k++<$argv[1]+2;$j=$k)while(--$j>0)echo$j;

```
> 1 votes

# Answer
# Ruby, 37 34 bytes

```
->n{a=p;(1..n).map{|i|p a=[i,a]}*''}

```

Saved 3 bytes thanks to G B.
> 1 votes

# Answer
## `j` `f`, 3 bytes

It's actually pretty trivial in W ...

```
M_M

```

## Explanation

a      % Take an input, say 3
     M % Identity map every item in numeric value 3
       % Since it is prohibited, a range is generated,
       % namely [1 2 3]
 a M   % For every item in [1 2 3]:
       % Note that single items are 1, 2, and 3, *not* the whole list
  a    % Generate a range from 1 to that number: [[1] [1 2] [1 2 3]]
    _  % Reverse for lists: [[1] [2 1] [3 2 1]]

Flag:f % Flatten the list: [1 2 1 3 2 1]
Flag:j % Join the list: 121321
```
</code></pre>
> 1 votes

# Answer
# Keg, 11 bytes (SBCS)

Now I realized that Keg is pretty hard to use...

```
¿Ï_^'(Ï_')"

```

Try it online!
> 1 votes

# Answer
# Vyxal, 5 bytes

```
ɾɾRṅṅ

```

Try it Online!

Tied with first :(

### Explained

```
ɾɾRṅṅ
ɾɾ    # range of range of [1...input]
  R   # reduce (reverse each of list)
   ṅṅ # join by nothing twice

```
> 1 votes

# Answer
# Python 2, 58 Bytes

```
print[[a for a in range(b+1,0,-1)]for b in range(input())]

```

Or, if the output of the above is not allowed, then the following code for 59 Bytes:

```
for i in range(input()+1):
 for j in range(i,0,-1):print j,

```
> 0 votes

# Answer
# 05AB1E, 6 bytes

```
LR.sJJ

```

Uses the **CP-1252** encoding. Try it online!

```
         # Implicit input
 L       # Push [1, 2, ..., n]
  R      # Reverse
   .s    # Get suffixes
     JJ  # Join twice
         # Implicit output

```
> 0 votes

# Answer
## Batch, 68 bytes

```
@for /l %%i in (1,1,%1)do @for /l %%j in (%%i,-1,1)do @cmd/cset/a%%j

```

Fortunately not printing newlines only costs 5 bytes.
> 0 votes

# Answer
# Python, 80 bytes

```
r=''.join;lambda b:r([r([`i`for i in range(1,a+1)][::-1])for a in range(1,b+1)])

```

You can easily test this by pasting the above code into a repl and hitting enter, then typing `_(6)` or whatever input you want to give.
> 0 votes

# Answer
# C, 52 bytes

Based on cat's existing answer:

```
i,j;f(n){j=++i;while(j)printf("%d",j--);i-n?f(n):0;}

```

Call with:

```
int main()
{
    f(6);
}

```
> 0 votes

# Answer
## Java: 141 chars

```
void c(int in,StringBuilder s){for(int i=1;i<=in;i++){for(int j=i;j>0;j--){s.append(Integer.toString(j));}}System.out.println(s.toString());}

```

Using `c(6,new StringBuilder());`:

> 121321432154321654321
> 0 votes

# Answer
## Clojure, ~~94~~ ~~84~~ 74 bytes

-10 bytes by eliminating the redundant `for`.

-10 bytes by eliminating the `let`.

Still long, but -20 bytes is nice.

```
#(loop[r 1 a""](if(> r %)a(recur(inc r)(str a(apply str(range r 0 -1))))))

```

Generates the reversed range, and concats it to the accumulator, then loops again while necessary.

Ungolfed:

```
(defn negative-order [n]
  (loop [r 1
         a ""]
    (let [s (apply str (range r 0 -1))]
      (if (> r n)
        a
        (recur (inc r) (str a s))))))

```
> 0 votes

# Answer
## Clojure, 57 bytes

```
#(apply str(reductions(fn[s i](str(inc i)s))""(range %)))

```

`reductions` is perfect for incrementally producing outputs like this.
> 0 votes

# Answer
# Stacked, noncompeting, 20 bytes

```
~>~>reveach flat''#`

```

Try it online!

I think a few of the features used in this answer were made after this challenge.

## Explanation

```
~>~>reveach flat''#`
~>                    range from [1, n]
  ~>                  vectorized range [[1,1], [1,2], ..., [1, n]]
    reveach           reverses each segment
            flat      flatten
                ''#`  join by nothing

```
> 0 votes

# Answer
# Java, 99 bytes

```
void f(int a){int[]f=new int[2];while(++f[0]<=a){f[1]=f[0];while(f[1]>0)System.out.print(f[1]--);}}

```

EDIT 1: Saved few bytes by changing it from a full program to a function.

Ungolfed:

```
void f(int a) {
    int[] f = new int[2];
    while (++f[0] <= a) {
        f[1] = f[0];
        while (f[1] > 0) System.out.print(f[1]--);
    }
}

```
> 0 votes

# Answer
# GolfScript, 12 bytes

```
~),(;{),(;}%

```

Try it online!
> 0 votes

# Answer
# Japt `-P`, 5 bytes

```
õõ cÔ

```

Try it

```
õõ cÔ     :Implicit input of integer
õ         :Range [1,input]
 õ        :Range [1,each], giving a 2D-array
   c      :Flatten after
    Ô     :Reversing each
          :Implicitly join & output

```
> 0 votes

# Answer
# Thunno 2 `N`, 3 bytes

```
RRṃ

```

Attempt This Online!

Same as Reversed Iota's, but with the `N` flag which joins the nested list.
> 0 votes

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


title: Catalan Numbers

text:
# Question
Title: Catalan Numbers
The ***Catalan numbers*** (OEIS) are a sequence of natural numbers often appearing in combinatorics.

The nth Catalan number is the number of Dyck words (balanced strings of parenthesis or brackets such as `[[][]]`; formally defined as a string using two characters `a` and `b` such that any substring starting from the beginning has number of `a` characters greater than or equal to number of `b` characters, and the entire string has the same number of `a` and `b` characters) with length `2n`. The nth Catalan number (for \\$n\ge0\\$) is also explicitly defined as: $$C\_n=\frac1{n+1}\binom{2n}n$$ Starting from \\$n=0\\$, the first 20 Catalan numbers are:

```
1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190...

```

# Challenge

Write a full program or function that takes a non-negative integer `n` via STDIN or an acceptable alternative, and outputs the nth Catalan number. Your program must work at minimum for inputs `0-19`.

## I/O

### Input

Your program must take input from STDIN, function arguments or any of the acceptable alternatives per this meta post. You can read the inputted number as its standard decimal represention, unary representation, or bytes.

* If (and only if) your language cannot take input from STDIN or any acceptable alternative, it may take input from a hardcoded variable or suitable equivalent in the program.

### Output

Your program must output the nth Catalan number to STDOUT, function result or any of the acceptable alternatives per this meta post. You can output the Catalan number in its standard decimal representation, unary representation or bytes.

The output should consist of the approriate Catalan number, optionally followed by one or more newlines. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation).

---

This is not about finding the language that is the shortest. This is about finding the shortest program in every language. Therefore, I will not accept an answer.

In this challenge, languages newer than the challenge are acceptable **as long as they have an implementation.** It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8). Note also that built-ins for calculating the nth Catalan number are allowed.

# Catalog

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the snippet:

```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 66127; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
## C, ~~78~~ ~~52~~ ~~39~~ ~~34~~ 33 bytes

Even more C magic (thanks xsot):

```
c(n){return!n?:(4+6./~n)*c(n-1);}

```

`?:` is a GNU extension.

---

This time by expanding the recurrence below (thanks xnor and Thomas Kwa):

$$ \begin{equation} \begin{split} C\_0 & = 1 \\ C\_n & = \frac{2 (2n - 1)}{n + 1} C\_{n - 1} \\ & = \frac{2 (2n+2-3)}{n+1} C\_{n - 1} \\ & = 2 \left(2\frac{n+1}{n+1} - \frac{3}{n+1}\right) C\_{n - 1} \\ & = \left(4 - \frac{6}{n+1}\right) C\_{n - 1} \end{split} \end{equation} $$

```
c(n){return n?(4+6./~n)*c(n-1):1;}

```

`-(n+1)` is replaced by `~n`, which is equivalent in two's complement and saves 4 bytes.

---

Again as a function, but this time exploiting the following recurrence:

$$ \begin{equation} \begin{split} C\_0 & = 1 \\ C\_n & = \frac{2 (2n - 1)}{n + 1} \cdot C\_{n - 1} \end{split} \end{equation} $$

```
c(n){return n?2.*(2*n++-1)/n*c(n-2):1;}

```

`c(n)` enters an infinite recursion for negative `n`, although it's not relevant for this challenge.

---

Since calling a function seems an acceptable alternative to console I/O:

```
c(n){double c=1,k=2;while(k<=n)c*=1+n/k++;return c;}

```

`c(n)` takes an `int` and returns an `int`.

---

Original entry:

```
main(n){scanf("%d",&n);double c=1,k=2;while(k<=n)c*=1+n/k++;printf("%.0f",c);}

```

Instead of directly calculating the definition, the formula is rewritten as:

$$ \begin{equation} \begin{split} \frac{1}{n + 1} {2n \choose n} &= \frac{(2n)!}{(n!)^2 \cdot (n + 1)} \\ & = \frac{2n \cdot \ldots \cdot (n + 1)}{n! \cdot (n + 1)} \\ & = \frac{1}{n + 1} \cdot \frac{\prod\_{k = 1}^n (n + k)}{\prod\_{k = 1}^n k} \\ & = \frac{1}{n + 1} \cdot \prod\_{k = 1}^n \frac{n + k}{k} \\ & = \frac{1}{n + 1} \cdot \prod\_{k = 1}^n \left(1 + \frac{n}{k}\right) \\ & = \frac{1}{n + 1} (n + 1) \prod\_{k = 2}^n \left(1 + \frac{n}{k}\right) \\ & = \prod\_{k = 2}^n \left(1 + \frac{n}{k}\right) \end{split} \end{equation} $$

The formula assumes `n >= 2`, but the code accounts for `n = 0` and `n = 1` too.

In the C mess above, `n` and `k` have the same role as in the formula, while `c` accumulates the product. All calculations are performed in floating point using `double`, which is almost always a bad idea, but in this case the results are correct up to `n = 19` at least, so it's ok.

`float` would have saved 1 byte, unfortunately it's not precise enough.
> 28 votes

# Answer
# Jelly, 4 bytes

```
Ḥc÷‘

```

Try it online!

### How it works

```
Ḥc÷‘    Left argument: z

Ḥ       Compute 2z.
 c      Hook; apply combinations to 2z and z.
  ÷‘    Divide the result by z+1.

```
> 25 votes

# Answer
## CJam, 12 bytes

```
ri_2,*e!,\)/

```

Try it online.

Beyond input 11, you'll need to tell your Java VM to use more memory. And I wouldn't actually recommend going much beyond 11. In theory, it works for any N though, since CJam uses arbitrary-precision integers.

### Explanation

CJam doesn't have a built-in for binomial coefficients, and computing them from three factorials takes a lot of bytes... so we'll have to do something better than that. :)

```
ri  e# Read input and convert it to integer N.
_   e# Duplicate.
2,  e# Push [0 1].
*   e# Repeat this N times, giving [0 1 0 1 ... 0 1] with N zeros and N ones.
e!  e# Compute the _distinct_ permutations of this array.
,   e# Get the number of permutations - the binomial. There happen to be 2n-over-n of
    e# of them. (Since 2n-over-n is the number of ways to choose n elements out of 2n, and
    e# and here we're choosing n positions in a 2n-element array to place the zeros in.)
\   e# Swap with N.
)/  e# Increment and divide the binomial coefficient by N+1.

```
> 11 votes

# Answer
## TI-BASIC, 11 bytes

```
(2Ans) nCr Ans/(Ans+1

```

Strangely, nCr has higher precedence than multiplication.
> 11 votes

# Answer
## Python 3, 33 bytes

```
f=lambda n:0**n or(4+6/~n)*f(n-1)

```

Uses the recurrence

```
f(0) = 1
f(n) = (4-6/(n+1)) * f(n-1)

```

The base case of 0 is handled as `0**n or`, which stops as `1` when `n==0` and otherwise evaluates the recursive expression on the right. The bitwise operator `~n==-n-1` shortens the denominator and saves on parens.

Python 3 is used for its float division. Python 2 could do the same with one more byte to write `6.`.
> 11 votes

# Answer
# Mathematica, ~~16~~ 13 bytes

```
CatalanNumber

```

Built-ins, amirite fellas :/

Non-builtin version (21 bytes):

```
Binomial[2#,#]/(#+1)&

```

A binomial-less version (25 bytes):

```
Product[(#+k)/k,{k,2,#}]&

```
> 10 votes

# Answer
## J, 8 bytes

```
>:%~]!+:

```

This is a monadic train; it uses the (2x nCr x)/(x+1) formula. Try it here.
> 7 votes

# Answer
# pl, 4 bytes

```
☼ç▲÷

```

Try it online.

## Explanation

In pl, functions take their arguments off the stack and push the result back onto the stack. Normally when there are not enough arguments on the stack, the function simply fails silently. However, something special happens when the amount of arguments on the stack is one off from the arity of the function -- the input variable `_` is added to the argument list:

```
☼ç▲÷

☼      double: takes _ as the argument since there is nothing on the stack
 ç     combinations: since there is only one item on the stack (and arity is 2), it adds _ to the argument list (combinations(2_,_))
  ▲    increment last used var (_)
   ÷   divide: adds _ to the argument list again

```

In effect, this is the pseudocode:

```
divide(combinations(double(_),_),_+1);

```
> 7 votes

# Answer
# Sesos, ~~94~~ ~~86~~ 68 bytes

8 bytes by changing the factorial-er from version 1 to version 2.

18 bytes by computing `n!(n+1)!` in one step. **Largely inspired by Dennis' primality test algorithm.**

Hexdump:

```
0000000: 16f8de a59f17 a0ebba 7f4cd3 e05f3f cf0fd0 a0ebde  ..........L.._?......
0000015: b1c1bb 76fe18 8cc1bb 76fe1c e0fbda 390fda bde3d8  ...v.....v.....9.....
000002a: 000fbe af9d1b b47bc7 cfc11c b47bc7 cff1fa e07bda  .......{.....{.....{.
000003f: 39e83e cf07                                       9.>..

```

Try it online!

Uses the formula `a(n) = (2n)! / (n!(n+1)!)`.

* The factorial-er: version 1 (in-place, constant memory), version 2 (in-place, linear memory)
* The multiplier: here (in place, constant memory)
* The divider: here (does not halt if not divisible)

## Assembler

```
set numin
set numout
get
jmp,sub 1,fwd 1,add 1,fwd 2,add 2,rwd 3,jnz
fwd 1,add 1
jmp
  jmp,sub 1,rwd 1,add 1,rwd 1,add 1,rwd 1,add 1,fwd 3,jnz
  rwd 1,sub 1,rwd 1,sub 1,rwd 1
  jmp,sub 1,fwd 3,add 1,rwd 3,jnz
  fwd 1
jnz
fwd 3
jmp
  jmp
    sub 1,rwd 1
    jmp,sub 1,rwd 1,add 1,rwd 1,add 1,fwd 2,jnz
    rwd 2
    jmp,sub 1,fwd 2,add 1,rwd 2,jnz
    fwd 3
  jnz
  rwd 1
  jmp,sub 1,jnz
  rwd 1
  jmp,sub 1,fwd 2,add 1,rwd 2,jnz
  fwd 3
jnz
fwd 1
jmp
  jmp,sub 1,fwd 1,add 1,fwd 1,add 1,rwd 2,jnz
  fwd 1,sub 1,fwd 1
  jmp,sub 1,rwd 2,add 1,fwd 2,jnz
  rwd 1
jnz
rwd 2
jmp
  jmp
    sub 1,fwd 1
    jmp,sub 1,fwd 1,add 1,fwd 1,add 1,rwd 2,jnz
    fwd 2
    jmp,sub 1,rwd 2,add 1,fwd 2,jnz
    rwd 3
  jnz
  fwd 1
  jmp,sub 1,jnz
  fwd 1
  jmp,sub 1,rwd 2,add 1,fwd 2,jnz
  rwd 3
jnz
fwd 1
jmp
  fwd 1,add 1,rwd 3
  jmp,sub 1,fwd 1,add 1,fwd 1,sub 1,rwd 2,jnz
  fwd 1
  jmp,sub 1,rwd 1,add 1,fwd 1,jnz
  fwd 1
jnz
fwd 1
put

```

## Brainfuck equivalent

This Retina script is used to generate the brainfuck equivalent. Note that it only accepts one digit as command argument, and does not check if a command is in the comments.

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

```
> 6 votes

# Answer
# Pyth, 8

```
/.cyQQhQ

```

Try it online or run the Test Suite

### Explanation

```
/.cyQQhQ   ## implicit: Q = eval(input())
/     hQ   ## integer division by (Q + 1)
 .c        ## nCr
   yQ      ## use Q * 2 as n
     Q     ## use Q as r

```
> 5 votes

# Answer
# Julia, 23 bytes

```
n->binomial(2n,n)/(n+1)

```

This is an anonymous function that accepts an integer and returns a float. It uses the basic binomial formula. To call it, give it a name, e.g. `f=n->...`.
> 5 votes

# Answer
## Seriously, 9 bytes

```
,;;u)τ╣E\

```

Hex Dump:

```
2c3b3b7529e7b9455c

```

Try it online

Explanation:

```
,                   Read in evaluated input n
 ;;                 Duplicate it twice
   u)               Increment n and rotate it to bottom of stack
     τ╣             Double n, then push 2n-th row of Pascal's triangle
       E            Look-up nth element of the row, and so push 2nCn
        \           Divide it by the n+1 below it.

```
> 5 votes

# Answer
## Matlab, ~~35~~ 25 bytes

```
@(n)nchoosek(2*n,n)/(n+1)

```

## Octave, 23 bytes

```
@(n)nchoosek(2*n,n++)/n

```
> 4 votes

# Answer
# JavaScript (ES6), 24 bytes

Based on the Python answer.

```
c=x=>x?(4+6/~x)*c(x-1):1

```

### How it works

```
c=x=>x?(4+6/~x)*c(x-1):1
c=x=>                     // Define a function c that takes a parameter x and returns:
     x?               :1  //  If x == 0, 1.
       (4+6/~x)           //  Otherwise, (4 + (6 / (-x - 1)))
               *c(x-1)    //  times the previous item in the sequence.

```

I think this is the shortest it can get, but suggestions are welcome!
> 4 votes

# Answer
# , 3 chars / 6 bytes

```
Мƅï

```

`Try it here (Firefox only).`

Builtins ftw! So glad I implemented math.js early on.

# Bonus solution, 12 chars / 19 bytes

```
Мơ 2*ï,ï)/⧺ï

```

`Try it here (Firefox only).`

Ay! 19th byte!

Evaluates to pseudo-ES6 as:

```
nchoosek(2*input,input)/(input+1)

```
> 4 votes

# Answer
## Dyalog APL, 9 bytes

```
+∘1÷⍨⊢!+⍨

```

This is a monadic train; it uses the (2x nCr x)/(x+1) formula. Try it online here.
> 3 votes

# Answer
## Haskell, 27 bytes

```
g 0=1
g n=(4-6/(n+1))*g(n-1)

```

A recursive formula. There's got to be a way to save on parens...

Directly taking the product was 2 bytes longer:

```
g n=product[4-6/i|i<-[2..n+1]]

```
> 3 votes

# Answer
# C, ~~122~~ ~~121~~ ~~119~~ 108 bytes

```
main(j,v)char**v;{long long p=1,i,n=atoi(v[1]);for(j=0,i=n+1;i<2*n;p=(p*++i)/++j);p=n?p/n:p;printf("%d",p);}

```

I used gcc (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125) to compile in a windows cygwin environment. Input comes in on the command line. It's similar to Sherlock9's Python solution but the loops are combined into one to avoid overflow and get output up to the 20th Catalan number (n=19).
> 3 votes

# Answer
# R, ~~35~~ ~~28~~ 16 bytes

```
numbers::catalan

```

Edit: Use numbers package builtin.
> 3 votes

# Answer
# 05AB1E, 6 bytes

```
Dxcr>/

```

**Explanation:**

```
Code:     Stack:               Explanation:

Dxcr>/

D         [n, n]               # Duplicate of the stack. Since it's empty, input is used.
 x        [n, n, 2n]           # Pops a, pushes a, a * 2
  c       [n, n nCr 2n]        # Pops a,b pushes a nCr b
   r      [n nCr 2n, n]        # Reverses the stack
    >     [n nCr 2n, n + 1]    # Increment on the last item
     /    [(n nCr 2n)/(n + 1)] # Divides the last two items
                               # Implicit, nothing has printed, so we print the last item

```
> 3 votes

# Answer
# Javagony, 223 bytes

```
public class C{public static int f(int a,int b){try{int z=1/(b-a);}catch(Exception e){return 1;}return a*f(a+1,b);}public static void main(String[]s){int m=Integer.parseInt(s[0])+1;System.out.println(f(m,2*m-1)/f(1,m)/m);}}

```

Fully expanded:

```
public class C {
    public static int f(int a,int b){
        try {
            int z=1/(b-a);
        } catch (Exception e){
            return 1;
        }
        return a*f(a+1,b);
    }
    public static void main(String[] s){
        int m=Integer.parseInt(s[0])+1;
        System.out.println(f(m,2*m-1)/f(1,m)/m);
    }
}

```
> 3 votes

# Answer
# R, 28 bytes

Not using a package, so slightly longer than a previous answer

```
choose(2*(n=scan()),n)/(n+1)

```
> 3 votes

# Answer
# Oasis, 9 bytes

```
nxx«*n>÷1

```

Try it online!

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

Here, we shall use the following relationship kindly provided by Stefano Sanfilippo:

Currently, this language can do recursion and closed form.

To specify that `a(0)=1` is simple: just add the `1` at the end.

For example, if a sequence begins with `a(0)=0` and `a(1)=1`, just put `10` at the end.

Unfortunately, all sequences must be 0-indexed.

```
nxx«*n>÷1                        stack
        1  a(0)=1

n          push n (input)        n
 x         double                2n
  x        double                4n
   «       minus 2               4n-2
    *      multiply: second      (4n-2)*a(n-1)
           argument is missing,
           so a(n-1) is used.
     n     push n (input)        (4n-2)*a(n-1) n
      >    add 1                 (4n-2)*a(n-1) n+1
       ÷   integer division      (4n-2)*a(n-1)/(n+1)
                               = ((4n-2)/(n+1))*a(n-1)
                               = ((4n+4-6)/(n+1))*a(n-1)
                               = ((4n+4)/(n+1) - 6/(n+1))*a(n-1)
                               = (4-6/(n+1))*a(n-1)

```

---

Closed-form:

## 10 bytes

```
nx!n!n>!*÷

```

Try it online!

```
nx!n!n>!*÷

n           push n (input)
 x          double
  !         factorial: stack is now [(2n)!]
   n        push n (input)
    !       factorial: stack is now [(2n)! n!]
     n      push n (input)
      >     add 1
       !    factorial: stack is now [(2n)! n! (n+1)!]
        *   multiply: stack is now [(2n)! (n!(n+1)!)]
         ÷  divide: stack is now [(2n)!/(n!(n+1)!)]

```
> 3 votes

# Answer
# TeX, 231 bytes

```
\newcommand{\f}[1]{\begingroup\count0=1\count1=2\count2=2\count3=0\loop\multiply\count0 by\the\count1\divide\count0 by\the\count2\advance\count1 by4\advance\count2 by1\advance\count3 by1
\ifnum\count3<#1\repeat\the\count0\endgroup}

```

## Usage

```
\documentclass[12pt,a4paper]{article}
\begin{document}
\newcommand{\f}[1]{\begingroup\count0=1\count1=2\count2=2\count3=0\loop\multiply\count0 by\the\count1\divide\count0 by\the\count2\advance\count1 by4\advance\count2 by1\advance\count3 by1
\ifnum\count3<#1\repeat\the\count0\endgroup}

\newcount \i
\i = 0
\loop
\f{\the\i}
\advance \i by 1
\ifnum \i < 15 \repeat
\end{document}

```
> 3 votes

# Answer
# Japt, 16 bytes

Even Mathematica is shorter. `:-/`

```
U*2ª1 o àU l /°U

```

Try it online!

### Ungolfed and explanation

```
U*2ª 1 o àU l /° U
U*2||1 o àU l /++U

         // Implicit: U = input number
U*2||1   // Take U*2. If it is zero, take 1.
o àU     // Generate a range of this length, and calculate all combinations of length U.
l /++U   // Take the length of the result and divide by (U+1).
         // Implicit: output result

```

Alternate version, based on the recursive formula:

```
C=_?(4+6/~Z *C$(Z-1):1};$C(U

```
> 2 votes

# Answer
# Vitsy, 13 Bytes

```
VV2*FVF/V1+F/
V              Capture the input as a final global variable.
 V             Push it back.
  2*           Multiply it by 2
    F          Factorial.
     VF        Factorial of the input.
       /       Divide the second to top by the first.
        V1+    1+input
           F   Factorial.
            /  Divide.
```

This is a function in Vitsy. How to make it a program that does this, you ask? Concatenate `N`. c:

Try it online!
> 2 votes

# Answer
# Milky Way 1.5.14, 14 bytes

```
':2K;*Ny;1+/A!

```

---

### Explanation

```
'               # read input from the command line
 :              # duplicate the TOS
  2      1      # push integer to the stack
   K            # push a Pythonic range(0, TOS) as a list
    ;   ;       # swap the TOS and the STOS
     *          # multiply the TOS and STOS
      N         # push a list of the permutations of the TOS (for lists)
       y        # push the length of the TOS
          +     # add the STOS to the TOS
           /    # divide the TOS by the STOS
            A   # push the integer representation of the TOS
             !  # output the TOS

```

or, alternatively, the *much* more efficient version:

---

# Milky Way 1.5.14, 22 bytes

```
'1%{;K£1+k1-6;/4+*}A!

```

---

### Explanation

```
'                      # read input from the command line
 1     1  1 6  4       # push integer to the stack
  %{  £           }    # for loop
    ;        ;         # swap the TOS and the STOS
     K                 # push a Pythonic range(0, TOS) as a list
        +       +      # add the TOS and STOS
         k             # push the negative absolute value of the TOS
           -           # subtract the STOS from the TOS
              /        # divide the TOS by the STOS
                 *     # multiply the TOS and the STOS
                   A   # push the integer representation of the TOS
                    !  # output the TOS

```

---

## Usage

```
python3 milkyway.py <path-to-code> -i <input-integer>

```
> 2 votes

# Answer
# Pari/GP, 17 bytes

```
n->(2*n)!/n!/n++!

```

Try it online!
> 2 votes

# Answer
# Octave, 22 bytes

```
@(n)prod(4-6./(2:n+1))

```
> 2 votes

# Answer
# Clojure/ClojureScript, 53 bytes

```
(defn c[x](if(= 0 x)1(*(c(dec x))(- 4(/ 6(inc x))))))

```

Clojure can be pretty frustrating to golf in. It's very pithy while still being very readable, but some of the niftier features are really verbose. `(inc x)` is more idiomatic than `(+ x 1)` and "feels" more concise, but doesn't actually save characters. And writing chains of operations is nicer as `(->> x inc (/ 6) (- 4))`, but it's actually longer than just doing it the ugly way.
> 2 votes

# Answer
# Ruby, 30 bytes

```
c=->n{n<1?1:c[n-1]*(4+6.0/~n)}

```

Thanks to xsot, saved few bytes by using complement.

**Ungolfed:**

```
c = -> n {
  n < 1 ? 1 : c[n-1]*(4+6.0/~n)
}

```

**Usage:**

```
> c=->n{n<1?1:c[n-1]*(4+6.0/~n)}
> c[10]
=> 16796.0

```
> 2 votes

# Answer
# Prolog, 42 bytes

Using recursion is almost always the way to go with Prolog.

**Code:**

```
0*1.
N*X:-M is N-1,M*Y,X is(4-6/(N+1))*Y.

```

**Example:**

```
19*X.
X = 1767263190.0

```

Try it online here
> 2 votes

# Answer
## Ceylon, 60 bytes

```
Integer c(Integer n)=>(1:n).fold(1)((p,i)=>p*(n+i)/i)/(n+1);

```

This works up to C<sub>30</sub>, as Ceylon's Integers are signed 64-bit numbers (C<sub>31</sub> has overflow, will be calculated as -4050872099593203).

I don't know if Ceylon has any built-in higher mathematical functions, but then importing the right package would probably longer than just calculating this by foot.

```
// Catalan number C_n
//
// Question:  http://codegolf.stackexchange.com/q/66127/2338
// My answer: http://codegolf.stackexchange.com/a/66425/2338

Integer c(Integer n) =>
        // sequence of length n, starting at 1.
        (1:n)
        // starting with 1, for each element i, multiply the result
        // of the previous step by (n+i) and then divide it by i.
    .fold(1)((p, i) => p * (n + i) / i)
        // divide the result by n+1.
        / (n + 1);

```
> 2 votes

# Answer
# MATL, 8 bytes

```
2*GXnGQ/

```

**Try it online!**

### Explanation

```
2*     % take number n as input and multiply by 2
G      % push input again
Xn     % compute "2*n choose n"
G      % push input again
Q      % add 1
/      % divide

```
> 2 votes

# Answer
# Vyxal `r`, 6 5 bytes

I *had* to use the `r` flag. It's only useful once in a blue moon.

```
‹?dƈ/

```

Formula: \\$\huge{\frac{{2n \choose n-1}}{n}}\\$

Explanation:

```
‹       decrement n
 ?      push n again
  d     double n
   ƈ    push 2n choose n-1 (because reversed)
    /   divide by n

```

Try it Online!
> 2 votes

# Answer
# tinylisp, 63 bytes

```
(load library
(d C(q((N)(i N(/(*(C(dec N))(s(* 4 N)2))(inc N))1

```

Try it online!

### Explanation

Uses one of the recurrence relations from Stefano Sanfilippo's C answer:

$$ \begin{align} C\_0 & = 1 \\ C\_n & = C\_{n-1} \cdot \frac{4n-2}{n+1} \end{align} $$

```
(d C(q((N)(i N(/(*(C(dec N))(s(* 4 N)2))(inc N))1
(d C                                               Define C
    (q((N)                                         as a function of N:
          (i N                                      If N is nonzero:
              (/                               )     Divide
                (*                     )              the product of
                  (C(dec N))                          a recursive call with N-1
                            (s(* 4 N)2)               and (4*N)-2
                                        (inc N)      by N-1
                                                1   Else, return 1

```
> 2 votes

# Answer
# Brachylog, 15 bytes

```
×₂{g{b|~b}ⁱ⁾Ė}ᶜ

```

Try it online!

Effectively brute forces all Dyck words of length \\$2n\\$. I don't know that an adaptation of one of the formulas can't be shorter, but my handful of (failed) attempts have all been roughly this length.

```
  {          }ᶜ    Count the number of possible ways to:
          ⁱ        iterate
   g       ⁾       starting with the empty list
×₂         ⁾       2n times,
     b             removing the first element
    { |~b}         or adding an element
            Ė      such that the end result is the empty list.

```
> 2 votes

# Answer
# Python 3, ~~83~~ ~~63~~ ~~62~~ 55 bytes

With thanks to Thomas Kwa.

```
f=lambda x:x<1or x*f(x-1)
c=lambda n:f(2*n)/f(n)/f(n+1)

```

`f` is the factorial function. `c` returns what is equivalent to `2*n C n` divided by `n+1`.
> 1 votes

# Answer
# Jolf, ~~15~~ 13 bytes

Try it here: ze link. You know what? I *almost* implemented a built-in. I just didn't have time. *Le sigh*. Also, there's a bug with my combination code, so I have to implement it with permutations. \>\_\< I'm now also pretty glad I didn't add comments.

```
//mk*2jjm!jhj

```

With permutation (9 bytes; invalid, as I fixed this after the challenge was posted):

```
/mK*2jjhj

```

With built-in (3 bytes; implemented after challenge :P. I take off my hat to @FlagAsSpam.):

```
m$j

```
> 1 votes

# Answer
# Maple, 18 bytes

```
(2*n)!/((n+1)!*n!)

```

Usage:

```
> f := n->(2*n)!/((n+1)!*n!);
> f(19);
  1767263190

```
> 1 votes

# Answer
# Python 2, 92 bytes

```
(lambda f:lambda n:f(2*n)/f(n)/f(n+1))((lambda r:r(r))(lambda r:lambda x:x<1or x*r(r)(x-1)))

```

Ideone it!

This answer purely serves to demonstrate the power of lambdas.
> 1 votes

# Answer
## Alice, 16 bytes

```
/o
\i@/..2*~C~h:

```

Try it online!

### Explanation

This is a basic framework for arithmetic programs to read and write integer I/O and process them in Cardinal mode:

```
/o
\i@/...

```

As for the actual computation, I'm using the usual formula given in the challenge:

```
..   Make two copies of the input.
2*   Double one copy.
~    Swap it with another copy.
C    Compute the binomial coefficient (2n,n).
~    Swap with the third copy.
h    Increment.
:    Divide to compute C_n = (2n,n)/(n+1)

```
> 1 votes

# Answer
# Pyt, 1 byte

```
Ć

```

Gets the input n implicity, then uses a builtin to get the nth Catalan number

Try it online!
> 1 votes

# Answer
# Brain-Flak, 78 bytes

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

```

Try it online!

Computes the first 2n rows of Pascal's triangle, then returns `((2n-1) C n) - ((2n-1) C (n+1))`.
> 1 votes

# Answer
# Factor \+ `math.combinatorics`, 28 bytes

```
[| n | n 2 * n 1 - nCk n / ]

```

Try it online!
> 1 votes

# Answer
# GAP, 28 bytes

```
c:=n->Binomial(2*n,n)/(n+1);

```

Try it online!
> 1 votes

# Answer
# tinylisp, ~~72 67~~ 64 bytes

*-5 bytes thanks to @Giuseppe* *-3 bytes thanks to @DLosc*

```
(load library
(d F factorial
(d g(q((n)(/(F(+ n n))(F n)(F(+ n 1

```

Try it online!
> 1 votes

# Answer
# Nekomata, 6 bytes

```
+$Ç$→/

```

Attempt This Online!

```
+$Ç$→/
+       Add the input with itself
 $      Swap
  Ç     Binomial coefficient
   $    Swap
    →   Increment
     /  Divide

```

---

# Nekomata \+ `-n`, 12 bytes

```
+Ø$ᵑ{ᵉçt?}Ø=

```

Attempt This Online!

A port of @Unrelated String's Brachylog answer.

```
+Ø$ᵑ{ᵉçt?}Ø=
 Ø$             Starting from the empty list
+  ᵑ{    }      Apply the following function 2*input times
     ᵉç             Prepend zero
       t?           Or drop the first element
          Ø=    Check if the result is empty

```

The `-n` flag counts the number of possible results.
> 1 votes

# Answer
# Jellyfish, ~~16~~ 12 bytes

```
p
%C+
 &
>+i

```

Try it online!
> 0 votes

# Answer
# \>\<\>, 29+2 = 31 bytes

```
:1+$?!\:2-
$/?=1l<*-$4,$6
;\n

```

Requires the input to be present on the stack at program start, so `+2` bytes for the `-v` flag. Try it online!

Uses the algorithm presented in Stefano Sanfilippo's answer (linky).

The first line compiles `n+1, n, n-1, ... , 2, 1` on the stack. The second line, running backwards, computes `C(n) = (4 - (6 / (n+1)) * C(n-1)`. Each iteration reduces the size of the stack by 1, so the remaining number is output when the length of the stack is 1.
> 0 votes

# Answer
## Clojure, 45 bytes

```
#(apply *(for[k(range 2(inc %))](/(+ % k)k)))

```

Uses the direct formula instead of recursion. Luckily `*` with zero arguments returns one :)
> 0 votes

# Answer
## cQuents, 13 bytes

```
f2$)/(f$+1)f$

```

1-indexed. Try it online!

### Explanation

```
:                 Implicit; sets mode to sequence
                  Given input n, output nth term in sequence; otherwise, output sequence
                  Each term in the sequence is equal to:
 f2$)             Factorial (2 * current)
     /            Divided by
      (        )  Group (implicit )
       f$+1)      Factorial (current + 1)
                  Implicit multiplication
            f$)   Factorial (current, implicit )

```
> 0 votes

# Answer
# Excel, 23 bytes

Unimaginative answer:

```
=COMBIN(2*A1,A1)/(A1+1)

```
> 0 votes

# Answer
## Lua, 86 bytes

```
c=setmetatable({[0]=1},{__index=function(c,n)c[n]=c[n-1]*(4-(6/(n+1)))print(c[n])end})

```

Try it online!
> 0 votes

# Answer
# Husk, 9 bytes

```
÷*Π¹Π→¹ΠD

```

Try it online!

Uses the formula in the description of the OEIS page.

0-indexed.
> 0 votes

# Answer
# Japt, 10 bytes

```
È*4a6/°Y}g

```

Try it

## Alternative

```
Ñª1 àU zUÄ

```

Try it
> 0 votes

# Answer
# Thunno 2, 6 bytes

```
Ḍscs⁺÷

```

Attempt This Online!

#### Explanation

```
Ḍscs⁺÷  # Implicit input   ->  n
Ḍ       # Double           ->  2n
 sc     # nCr with input   ->  (2n)C(n)
   s⁺   # Increment input  ->  (2n)C(n), n+1
     ÷  # Divide           ->  ((2n)C(n)) / (n+1)
        # Implicit output

```
> 0 votes

---
Tags: code-golf, sequence, number-theory, combinatorics, balanced-string
---


title: Multiply a string by a number!

text:
# Question
Title: Multiply a string by a number!
There was a challenge up a while ago about multiplying strings. It showed us how we can multiply not only numbers, but also strings. However, we still can't multiply a number by a string properly. There has been one attempt to do so but this is obviously wrong. We need to fix that!

## Your Task:

Write a function or program that multiplies two inputs, a string and an integer. To (properly) multiply an string by an integer, you split the string into characters, repeat each character a number of times equal to the integer, and then stick the characters back together. If the integer is negative, we use its absolute value in the first step, and then reverse the string. If the input is 0, output nothing (anything multiplied by 0 equals nothing).

## Input:

A string that consists solely of printable ASCII characters and newlines, and an integer (possible negative).

## Output:

The string multiplied by the integer.

## Examples:

```
Hello World!, 3            --> HHHeeellllllooo   WWWooorrrlllddd!!!
foo, 12                    --> ffffffffffffoooooooooooooooooooooooo
String, -3                 --> gggnnniiirrrtttSSS
This is a fun challenge, 0 -->
Hello
World!, 2                  --> HHeelllloo

                               WWoorrlldd!!

```

## Scoring:

This is , lowest byte count wins!

# Answer
# Jelly, ~~6~~ ~~5~~ 4 bytes

```
²Ɠxm

```

Try it online!

### How it works

```
²Ɠxm  Main link. Argument: n (integer)

²     Yield n².
 Ɠ    Read and eval one line of input. This yields a string s.
  x   Repeat the characters of s in-place, each one n² times.
   m  Takes each |n|-th character of the result, starting with the first if n > 0,
      the last if n < 0.

```
> 32 votes

# Answer
## JavaScript (ES6), 63 bytes

Takes input in currying syntax `(s)(n)`.

```
s=>n=>[...s].reduce((s,c)=>n<0?c.repeat(-n)+s:s+c.repeat(n),'')

```

### Test cases

```
let f =

s=>n=>[...s].reduce((s,c)=>n<0?c.repeat(-n)+s:s+c.repeat(n),'')

console.log(f(`Hello World!`)(3))
console.log(f(`foo`)(12))
console.log(f(`String`)(-3))
console.log(f(`This is a fun challenge`)(0))
console.log(f(`Hello
World!`)(2))
```
> 10 votes

# Answer
# Python 3, 44 bytes

```
f=lambda s,n:s and s[0]*n+f(s[1:],n)+s[0]*-n

```

Try it online!
> 10 votes

# Answer
# Python 2, ~~59~~ ~~57~~ ~~50~~ 46 bytes

*-2 bytes thanks to Anders Kaseorg. -4 bytes thanks to Dennis.*

```
lambda s,n:''.join(i*n**2for i in s)[::n or 1]

```

Try it online!
> 9 votes

# Answer
# 05AB1E, 10 bytes

```
S²Ä×J²0‹iR

```

Try it online!

```
S          # Split the string into characters
 ²Ä×       # Repeat each character abs(integer) times
    J      # Join into a string
     ²0‹i  # If the integer is less than 0...
         R #   Reverse the string

```
> 6 votes

# Answer
## R, ~~83~~ ~~78~~ ~~76~~ 74 bytes

```
function(s,i)cat('if'(i<0,rev,I)(rep(el(strsplit(s,'')),e=abs(i))),sep='')

```

Anonymous function.

Frederic saved 3 bytes, Giuseppe saved ~~2~~ 4, pajonk saved 2.

Explanation:

```
     el(strsplit(s,''))                      # split string into list characters
 rep(                  ,e=abs(i)))           # repeat each character abs(i) times

    'if'(i<0,rev, ){...}                     # if i>0, reverse character list
                 I                           # otherwise leave it alone: I is the identity function
cat(                    ,sep='')             # print the result

```

Tests:

```
> f('Hello World!', 3 )
HHHeeellllllooo   WWWooorrrlllddd!!!
> f('foo', 12)
ffffffffffffoooooooooooooooooooooooo
> f('String', -3)
gggnnniiirrrtttSSS
> f('This is a fun challenge', 0)
> f('Hello
+ World!', 2)
HHeelllloo

WWoorrlldd!!

```
> 6 votes

# Answer
# , ~~29, 23, 18~~, 17 bytes

```
æ_ñÀuñÓ./&ò
ÀäëÍî

```

Try it online!

Hexdump:

```
00000000: e65f f1c0 75f1 d32e 2f26 f20a c0e4 ebcd  ._..u.../&......
00000010: ee                                       .

```

Thanks to @nmjcman101 for saving 6 bytes, which encouraged me to save another 5!

The original revision was pretty terrible, but now I'm really proud of this answer because it handles negative numbers surprisingly well. (V has next to no numerical support and no support for negative numbers)

Explanation:

```
æ_          " Reverse the input
  ñ  ñ      " In a macro:
   À        "   Run the arg input. If it's positive it'll give a count. If it's negative
            "   running the '-' will cause V to go up a line which will fail since we're
            "   on the first line, which will break out of this macro
    u       "   (if arg is positive) Undo the last command (un-reverse the line)
      Ó./&ò " Put every character on it's own line

```

At this point, the buffer looks like this:

```
H
e
l
l
o

w
o
r
l
d
!
<cursor>

```

It's important to not the trailing newline, and that the cursor is on it.

```
À           " Run arg again. If it's negative, we will move up a line, and then give the
            " absolute value of the count. If it's positive (or 0) it'll just give the
            " count directly (staying on the last line)
 ä          " Duplicate... (count times)
  ë         "   This column.
   Íî       " Remove all newlines.

```
> 5 votes

# Answer
# Haskell, ~~41~~ 36 bytes

```
f n|n<0=reverse.f(-n)|1<3=(<*[1..n])

```

Try it online!

Example usage: `f (-3) "abc"` yields `"cccbbbaaa"`.

**Edit:** -5 bytes thanks to xnor!
> 5 votes

# Answer
# MATL, 9 bytes

```
y|Y"w0<?P

```

Inputs are: number, then string.

Strings with newlines are input using char `10` as follows: `['first line' 10 'second line']`.

Try it online! Or verify all test cases.

### Explanation

Consider inputs `-3` and `'String'`.

```
y      % Implicitly take two inputs. Duplicate from below
       % STACK: -3, 'String', -3
|      % Absolute value
       % STACK: -3, 'String', 3
Y"     % Run-length decoding
       % STACK: -3, 'SSStttrrriiinnnggg'
w      % Swap
       % STACK: 'SSStttrrriiinnnggg', -3
0<     % Less than 0?
       % STACK: 'SSStttrrriiinnnggg', 1
?      % If so
  P    %   Flip
       %   STACK: 'gggnnniiirrrtttSSS'
       % End (implicit). Display (implicit)

```
> 5 votes

# Answer
# , 19 15 13 bytes

```
(#~|)A.~0-@>]

```

Try it online!

**Explanation**

```
        0-@>]      NB. first or last index depending on sign of right arg
     A.~           NB. get first or last Anagram of left arg
(#~|)              NB. copy left arg, absolute-value-of-right-arg times

```
> 5 votes

# Answer
# 05AB1E, 10 bytes

```
0‹FR}ʒ¹Ä×?

```

Try it online!

**Explanation**

```
0‹F         # input_1 < 0 times do:
   R        # reverse input_2
    }       # end loop
     ʒ      # filter
      ¹Ä×   # repeat current char abs(input_1) times
         ?  # print without newline

```
> 4 votes

# Answer
# PHP\>=7.1, 65 bytes

```
for([,$s,$n]=$argv;$i<strlen($s)*abs($n);)echo$s[$i++/$n-($n<0)];

```

PHP Sandbox Online
> 4 votes

# Answer
# Brain-Flak (BrainHack), ~~154~~ 152 bytes

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

```

Try it online!

Just here to give DJMcMayhem some competition. **;)**

## Explanation

Here's a modified version of DJMcMayhem's explanation

```
#Compute the sign and negative absolute value
([(({})<(())>)]<>)<>{({}()<([{}]()<([{}])>)<>({}<>)<>>)<>}{}<>{}<>

#Keep track of the sign
({}<

    #For each char in the input string:
    ([][()])
    {
        {}

        #Push n copies to the alternate stack
        ({<({}<(({}<>)<>)>())>[()]}<{}{}>)

        #Endwhile
        ([][()])
    }{}{}<>

#Push the sign back on
>)

#If so...
{{}

    #Reverse the whole stack
    {({}<>)<>}

    #And toggle over, ending the loop
    (<>)
}

#Pop the counter off
{}

```
> 4 votes

# Answer
# Elm, 69 bytes

```
f n=if n<0 then List.reverse>>f -n else List.concatMap(List.repeat n)

```

Defines `f` to be a function that takes an integer and a list of characters and returns a list of characters. You can try it here. Here is a full test program:

```
import Html exposing (text)

f : Int -> List Char -> List Char
f n=if n<0 then List.reverse>>f -n else List.concatMap(List.repeat n)

main =
  text (String.fromList (f -3 ['S','t','r','i','n','g']))

```

### Explanation

This is my first Elm submission, so please let me know any golfing tricks I've missed.

Using currying, we define a function `f` that takes an integer `n` and returns a function from a list of chars to a list of chars. There are two cases in the function definition:

* If `n` is negative, call `f` on its absolute value (`f -n`); then compose (`>>`) the resulting function with `List.reverse`.
* Else, create a function that puts `n` copies of a value in a list (`List.repeat n`) and map that function over each char in the list, flattening the result into a list of chars (`List.concatMap`).
> 4 votes

# Answer
# Dyalog APL, 15 bytes

```
{⌽⍣(⍵<0)⊢⍺/⍨|⍵}

```

String as a left argument, number as a right argument.

Try it online!

**How?**

`⍺/⍨` \- repeat the string

`|⍵` \- abs(number) times

`⌽⍣` \- reverse if

`(⍵<0)` \- the number is below 0
> 3 votes

# Answer
# MATLAB, 37 bytes

```
@(s,n)flip(repelem(s,abs(n)),(n<0)+1)

```

This defines and anonymous function with inputs `s`: string and `n`: number.

Example runs:

```
>> @(s,n)flip(repelem(s,abs(n)),(n<0)+1)
ans =
    @(s,n)flip(repelem(s,abs(n)),(n<0)+1)

>> f = ans;

>> f('String', 3)
ans =
SSStttrrriiinnnggg

>> f('String', -3)
ans =
gggnnniiirrrtttSSS

>> f('String', 0)
ans =
   Empty matrix: 1-by-0

```
> 3 votes

# Answer
# Java (OpenJDK 8), ~~99~~ ~~98~~ ~~89~~ ~~87~~ 85 bytes

```
s->n->{for(int i=s.length*(n<0?n:-n),r=n<0?0:~i;i++<0;)System.out.print(s[(i+r)/n]);}

```

Try it online!

* -2 bytes thanks to @Xanderhall
* -2 bytes thanks to @Nevay
> 3 votes

# Answer
# Brain-Flak (Haskell), ~~202~~ 192 bytes

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

```

Try it online!

This is probably the worst possible language to do it in, but it's done. Thanks to @Wheatwizard for providing the Haskell interpreter, which allows mixed input formats. This would be about 150 bytes longer without it.

Explanation:

```
#Keep track of the first input (n)
(({})<

    #Push abs(n) (thanks WheatWizard!)
    (([({})]<>)){({}()<([{}])<>({}<>)<>>)<>}{}([{}]<><{}>)

    #For each char in the input string:
    ([][()])
    {
        {}

        #Push n copies to the alternate stack
        ({<({}<(({}<>)<>)>[()])>()}<{}{}>)

        #Endwhile
        ([][()])
    }{}{}<>

#Push the original n back on
>)

#Push n >= 0
([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}

#If so...
{{}

    #Reverse the whole stack
    {({}<>)<>}

    #And toggle over, ending the loop
    (<>)
}

#Pop the counter off
{}

```
> 3 votes

# Answer
# C89 bytes

```
main(int c,char**v){for(;*v[1];v[1]++)for(c=atoi(v[2]+(*v[2]=='-'));c--;)putchar(*v[1]);}

```

I saw Ben Perlin's version and wondered if you couldn't be shorter still and also have a full program; surely, `atoi()` and `putchar()` aren't that expensive in terms of bytes? Seems I was right!
> 3 votes

# Answer
# C (gcc), ~~108~~ ~~106~~ ~~103~~ 101 bytes

-2 bytes thanks to ceilingcat

```
e,p,j,d;f(s,i)char*s;{p=0,e=strlen(s);for(i*=d=i<0?p=e-1,e=-1:1;p^e;p+=d)for(j=i;j--;)putchar(s[p]);}

```

Try it online!
> 3 votes

# Answer
# Octave, 49 bytes

```
@(s,n){t=repmat(s,abs(n),1)(:)',flip(t)}{2-(n>0)}

```

Try it online!

I will provide an explanation tomorrow.
> 2 votes

# Answer
# Pyth, ~~13~~ 11 bytes

```
*sm*.aQdz._

```

Try it!

*-2 bytes thanks to @jacoblaw*

## explanation

```
*sm*.aQdz._
  m     z     # map onto the input string (lambda var: d)
   *.aQd      # repeat the char d as often as the absolute value of the input number
 s            # sum the list of strings into a single string
*        ._Q   # Multiply with the sign of the implicit input value: reverse for negative Q

```

## old approach, 13 bytes

```
_W<Q0sm*.aQdz

```

Try it!
> 2 votes

# Answer
# Ruby, 59 +1 = 60 bytes

Uses `-n` flag.

```
n=eval$_
a=$<.read
a.reverse!if n<0
a.chars{|i|$><<i*n.abs}

```

Try it online!
> 2 votes

# Answer
# Charcoal, 16 bytes

```
Ｆθ¿‹η0Ｆ±Ｉη←ιＦＩηι

```

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

```
Ｆθ              For each character in the input string
  ¿‹η0          If the input number is less than zero
      Ｆ±Ｉη      Repeat the negation of the input number times
          ←ι    Print the character leftwards (i.e. reversed)
      ＦＩη       Otherwise repeat the input number times
         ι      Print the character

```
> 2 votes

# Answer
# Japt, 12 bytes

```
®pVaÃ¬r!+sVg

```

Try it online!

## Explanation

Implicit input of string `U` and integer `V`.

```
®pVaÃ

```

Map (`®`) each letter of `U` (implicitly) to itself repeated (`p`) `abs(V)` (`Va`) times.

```
¬r

```

Turn the string into an array of chars (`¬`) and reduce (`r`) that with...

```
!+sVg

```

`"!+".slice(sign(V))` \- this either reduces with `+``a + b`, or with `!+``b + a`.
Thanks @Arnauld for the backwards-reduce idea!
> 2 votes

# Answer
# CJam, 9 bytes

```
q~__*@e*%

```

Try it online!
> 2 votes

# Answer
# Excel VBA, <sub>~~93~~ ~~89~~ ~~88~~ ~~86~~</sub> 85 Bytes

Anonymous VBE immediate window function that takes input as string from cell `[A1]` and int from cell `[B1]` and outputs to the VBE immediate window

```
l=[Len(A1)]:For i=1To l:For j=1To[Abs(B1)]:?Mid([A1],IIf([B1]>0,i,l+1-i),1);:Next j,i

```

-4 bytes for abandoning `[C1]` as intermediate variable

-1 byte for adding `a` as intermediate variable

-2 bytes for replacing `a` with `l`, (`[Len(A1)]`)
> 2 votes

# Answer
# 05AB1E, 9 bytes

Based off Riley's approach.

```
SÂÎ›@²Ä×J

```

Try it online!

### Explanation

```
SÂÎ›@²Ä×J   Arguments: s, n
S           Push s split into individual characters
 Â          Get a (without popping) and push a reversed
  Î›        n lower than 0 (true = 1, false = 0)
    @       Get value at that index in the stack
     ²Ä×J   Repeat each character abs(n) times and join
            Implicit output

```
> 2 votes

# Answer
# Python 3, 68 bytes

```
h=lambda s,n:h(s[::-1],-n)if n<0 else s[0]*n+h(s[1:],n)if s else s*n

```

Try it online!
> 2 votes

# Answer
# WendyScript, 46 bytes

```
<<f=>(s,x){<<n=""#i:s#j:0->x?x>0n+=i:n=i+n/>n}

f("Hello World", -2) // returns ddllrrooWW  oolllleeHH

```

Try it online!

## Explanation (Ungolfed):

```
let f => (s, x) {
  let n = ""
  for i : s
    for j : 0->x
      if x > 0 n += i
      else n = i + n
  ret n
}

```
> 2 votes

# Answer
# Forth, 132 bytes.

My first golf, Idk what I'm doing I'm sure it could be improved a lot.

```
: Z chars + c@ emit ; : X 0 do dup n Z loop ; : Y dup 0 < if negate then dup 0 > if n count 0 do over i 1 + swap X drop loop then ;

```

or

```
: Z chars + c@ emit ;
: X 0 do dup n Z loop ;
: Y dup 0 < if negate then dup 0 > if n count 0 do over i 1 + swap X drop loop then ;

```

The negate and comparisons are just for the 0 and negative cases. This is assuming we've already been given the string at 'n', I'm unsure if this is allowed.
> 2 votes

# Answer
# Mathematica, 89 bytes

```
(T=Table;t=""<>T[s[[i]]~T~Abs@#2,{i,Length[s=Characters@#]}];If[#2>0,t,StringReverse@t])&

```

**input**

> \["Hello World!", 3\]
> 1 votes

# Answer
# QBIC, 32 bytes

```
g=sgn(c)[_l;||[:*g|?_sA,b*g,1|';

```

## Explanation

```
            Takes inputs A$ ('Hello'), and c (-3) from the cmd line
g=sgn(c)    Save the sign of c          -1
[_l;||      FOR each char in A$
[:*g|       FOR the number of repetitions wanted    (ie: -3 * -1)
            Note that : reads a number from the cmd line, and c is the first
            available variable to save it in after a and b got used as FOR counters.
            Also note that a negative value times the sign becomes positive.
?_s         PRINT a substring
  A         of A$
 ,b*g       startng at char n, where n is the first FOR loop counter times the sign
                That means that when c is negative, so is this. A negative starting index
                on Substring instructs QBIC to take from the right.
 ,1|        taking 1 char.
';          This bit injects a literal ; in the output QBasic, to suppress newlines om PRINT

```
> 1 votes

# Answer
# Braingolf, 22 bytes

```
1-v{R.[v.R]v}R[v>R]v&@

```

Try it online!

Eeh, not bad.

Takes input as an integer and an array of characters.

Alternatively:

# Braingolf, 31 bytes

```
l1->[M]1-v&,{R.[v.R]v}R[v>R]v&@

```

Try it online!

Takes input as an integer and a string
> 1 votes

# Answer
# C, 109 bytes

```
char *f(int n, char *s){char *o=calloc(n,strlen(s)+1),*t=o;while(*s){for(int i=n;i--;)*t++=*s;s++;}return o;}

```

Starting with a function declaration that takes an int and a string and produces a string (it seems implied that memory is not preallocated and must be created) it seems that the straight-forward approach is shorter than any attempts at being cleaver that I had tried.

```
char *f(int n, char *s){
  char *o=calloc(n, strlen(s)+1),
    *t=o;

  while (*s) {
    for(int i=n; i--; )
      *t++=*s;
    s++;
  }

 return o;

```

}
> 1 votes

# Answer
# Julia, 44 bytes

```
(s,x)->for i in split(s,"") print(i^abs(x))end

```
> 1 votes

# Answer
## /Kona, ~~19~~ 18 bytes

```
{,/$[y>0;;|:]y#'x}

```

Now, in the 0 case, it does output *something*, but that's the empty string so I'm sure that's all gravy.

I actually missed the negative input part of this initially, which cost me eleven bytes! Definitely not my best work

Usage:

```
k){,/$[y>0;;|:]y#'x}["Hello World";3]
"HHHeeellllllooo   WWWooorrrlllddd!!!"
k){,/$[y>0;;|:]y#'x}["Hello World!";0]
""
k){,/$[y>0;;|:]y#'x}["String";-3]
"gggnnniiirrrtttSSS"

```
> 1 votes

# Answer
# PowerShell, 89 bytes

```
param($s,$n)-join($s[((0..($L=$s.Length)),(-1..-$L))[$n[0]-eq45]]|%{"$_"*"$n".trim('-')})

```

Try it online!

Generates a list of characters in the string, either forward or reversed, string-multiplies each, and joins the resulting array. `$n[0]-eq45` is the ASCII code of `-` and `.Trim('-')` is shorter than `[Math]::Abs($n)`
> 1 votes

# Answer
# **C#, 70 Bytes**

```
using System.Linq;(s,n)=>string.Join("",s.Select(c=>new string(c,n)));

```

The select function is used to create a new string with the original character repeated n-times, results are joined together.
> 1 votes

# Answer
# **C++, 152 bytes**

```
#define l(x,n)for(int x=0;x<n;++x)
typedef std::string s;s f(s t,int c){s r;l(i,t.size())l(j,abs(c))r+=t[i];if(c<0)reverse(r.begin(),r.end());return r;}

```

And here's the full code you can test with.

```
#include <iostream>

#define l(x,n)for(int x=0;x<n;++x)
typedef std::string s;s f(s t,int c){s r;l(i,t.size())l(j,abs(c))r+=t[i];if(c<0)reverse(r.begin(),r.end());return r;}

int main(int argc, const char * argv[]) {
    std::cout << f("Hello World!", 3) << std::endl;
    std::cout << f("foo", 12) << std::endl;
    std::cout << f("String", -3) << std::endl;
    std::cout << f("This is a fun challenge", 0) << std::endl;
    std::cout << f("Hello\nWorld!", 2) << std::endl;
    return 0;
}

```
> 1 votes

# Answer
# C#, 108 bytes

```
using System.Linq;s=>n=>{var a=s.Select(c=>new string(c,n>0?n:-n));return string.Concat(n<0?a.Reverse():a);}

```

Full/Formatted Version:

```
using System;
using System.Linq;

namespace TestBed
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string, Func<int, string>> f = s => n =>
            {
                var a = s.Select(c => new string(c, n > 0 ? n : -n));

                return string.Concat(n < 0 ? a.Reverse() : a);
            };

            Console.WriteLine(f("Hello World!")(3));
            Console.WriteLine(f("foo")(12));
            Console.WriteLine(f("String")(-3));
            Console.WriteLine(f("This is a fun challenge")(0));
            Console.WriteLine(f(@"Hello
World!")(2));

            Console.ReadLine();
        }
    }
}

```
> 1 votes

# Answer
# Brainfuck, 26 bytes

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

```

Try it online!
> 1 votes

# Answer
## vim, 45 bytes

```
:s/\(.\)/\1<C-v>
/g
adl<esc>gJaP<esc>"add
:%norm @a
:%j!

```

`<esc>` is 0x1b, and `<C-v>` is 0x16.

`:s/\(.\)/\1<C-v><nl>/g` splits the string into one character per line.

`adl<esc>gJaP<esc>"add` then constructs a command in buffer `a` that will copy a line `n` times, where `n` is the number that was previously on this line.

`%norm @a` and `:%j!` then apply that command to each line in the file and rejoin the lines respectively.

Try it online
> 1 votes

# Answer
# Unwanted, Unnecessary, Opportunistic, 7 bytes

```
IAM*|V^

```
> 1 votes

# Answer
## Clojure, 24 bytes

```
#(for[c % _(range %2)]c)

```

Returning a string instead of a sequence of characters pushes this to 35 bytes:

```
#(apply str(for[c % _(range %2)]c))

```
> 1 votes

# Answer
# \[C#\], 103 bytes

```
var r=n<0?-n:n;var a=new int[p.Length*r].Select((_,i)=>p[i/r]);return String.Concat(n<0?a.Reverse():a);

```

Try It Online!

Tried something a little different from the other C# answers, without using 'new string(str, x)'.
> 1 votes

# Answer
# Vyxal, 7 bytes

```
ȧ•?0<[Ṙ

```

Try it Online!

There's gotta be a better way to do this.

```
 •      # Repeat each char by...
ȧ       # absolute value of input
  ?0<[  # If it's negative
      Ṙ # Reverse

```
> 1 votes

# Answer
# \>\<\> (Fish), 61 bytes

```
:&0)?v>i:0(?^\
-$0&0/\p3a'r'&
 .07~v?:<+1&:/
{:}+1/ >o< ~\.28

```

Try it

## Explanation

Takes the number as the initial stack value, and the string as the STDIN.

Uses source code modification: Inserts a `r` command at `10,3` if the number is positive. If so invert the number. The `&` instruction is nicely in the perfect place both from the top and from the right side.

The `{:}` copies the character `-n` times.
> 1 votes

# Answer
# Thunno 2, 7 bytes

```
AḄ$0<?r

```

Attempt This Online!

#### Explanation

```
AḄ$0<?r  # Implicit input
 Ḅ       # Multiply each character of the second input by...
A        # ...the absolute value of the first input
  $      # Push the first input again
   0<    # And check if it's negative
     ?   # If it is negative:
      r  #  Reverse the string
         # Implicit output

```
> 1 votes

# Answer
## Mathematica, 56 bytes

```
""<>Thread@Table[Reverse[Characters@#2,2+Sign@#],Abs@#]&

```

Try it at the Wolfram sandbox! (Doesn't work in Mathics…)

Takes the number then the string as input.

The `Reverse` function can take a second parameter saying what level of the array to reverse at (so `Reverse[{{1,2},{3,4}}]` returns `{{3,4},{1,2}}` but `Reverse[{{1,2},{3,4}},2]` gives `{{2,1},{4,3}}`, for instance). When the input number is negative, we reverse at level 1, but when it's zero or positive, we reverse at level 2 or 3. Since `Characters@#2` is a list with only one level, reversing at deeper levels has no effect.

Once that's done, we repeat the list of characters then transpose the resulting array using `Thread` so the repeated characters end up next to each other.
> 0 votes

# Answer
# tcl, 120

```
proc M s\ n {if $n<0 {set s [string rev $s];set n [expr -$n]};lmap c [split $s ""] {append x [string repe $c $n]};set x}

```

# demo
> 0 votes

# Answer
# Retina, 76 bytes

```
Os^$`(?<=^-.+¶.*).

^.+
$*
s`(?<=¶.*)

{`^1

}s`(?<=^1.*)	(.)
	$1$1
\`^¶|

```

Try it online!
> 0 votes

# Answer
# Husk, 13 bytes

```
So?I↔>0o`ȯṁRa

```

Try it online!

### Ungolfed/Explanation

```
       o`ȯṁ    -- with the input string..
           Ra  -- ..multiply each character by the absolute value |N|
So?            -- depending on N either apply..
   I           -- ..the identity..
     >0        -- ..if N>0 or else..
    ↔          -- ..reverse it

```
> 0 votes

# Answer
# Japt `-P`, 10 bytes

```
ÆVÃÕzUÌÉ©2

```

Try it

```
ÆVÃÕzUÌÉ©2     :Implicit input of integer U & string V
Æ              :Map the range [0,U)
 V             :  Return V
  Ã            :End map
   Õ           :Transpose
    z          :Rotate clockwise this many times
     UÌ        :  Sign of difference between U & -1
       É       :  Subtract 1
        ©2     :  Logical AND with 2
               :Implicitly join & output

```
> 0 votes

# Answer
# C (gcc), 80 bytes

```
i;L;f(s,n)char*s;{L=strlen(s);for(i=0;i*i<L*n*L*n;)putchar(s[i++/n+~-L*(n<0)]);}

```

Try it online!

-1 byte from ceilingcat
> 0 votes

# Answer
# Raku, 50 bytes

```
{($^a.comb »x»$^b.abs).join.&{$b <0??.flip!!$_}}

```

Try it online!
> 0 votes

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

```
n=>g=(h,i=n,[c,...x]=h)=>c?i?i>0?c+g(h,i-1):g(h,i+1)+c:g(x):h

```

Try it online!

No longer longer than Q256411, but even same length it's only
> 0 votes

---
Tags: code-golf, string, number, arithmetic
---


title: Compress Jelly's code page

text:
# Question
Title: Compress Jelly's code page
In this challenge, you'll print out the SBCS of Jelly, a popular golfing language. Its code page looks like this:

|  | \_0 | \_1 | \_2 | \_3 | \_4 | \_5 | \_6 | \_7 | \_8 | \_9 | \_A | \_B | \_C | \_D | \_E | \_F |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| **0\_** | `¡` | `¢` | `£` | `¤` | `¥` | `¦` | `©` | `¬` | `®` | `µ` | `½` | `¿` |  | `Æ` | `Ç` | `Ð` |
| **1\_** | `Ñ` | `×` | `Ø` | `Œ` | `Þ` | `ß` | `æ` | `ç` | `ð` | `ı` | `ȷ` | `ñ` | `÷` | `ø` | `œ` | `þ` |
| **2\_** |  | `!` | `"` | `#` | `$` | `%` | `&` | `'` | `(` | `)` | `*` | `+` | `,` | `-` | `.` | `/` |
| **3\_** | `0` | `1` | `2` | `3` | `4` | `5` | `6` | `7` | `8` | `9` | `:` | `;` | `<` | `=` | `>` | `?` |
| **4\_** | `@` | `A` | `B` | `C` | `D` | `E` | `F` | `G` | `H` | `I` | `J` | `K` | `L` | `M` | `N` | `O` |
| **5\_** | `P` | `Q` | `R` | `S` | `T` | `U` | `V` | `W` | `X` | `Y` | `Z` | `[` | `\` | `]` | `^` | `_` |
| **6\_** | ``` | `a` | `b` | `c` | `d` | `e` | `f` | `g` | `h` | `i` | `j` | `k` | `l` | `m` | `n` | `o` |
| **7\_** | `p` | `q` | `r` | `s` | `t` | `u` | `v` | `w` | `x` | `y` | `z` | `{` | `|` | `}` | `~` |  |
| **8\_** | `°` | `¹` | `²` | `³` |  |  |  |  |  |  |  |  |  |  |  | `Ɓ` |
| **9\_** | `Ƈ` | `Ɗ` | `Ƒ` | `Ɠ` | `Ƙ` |  | `Ɲ` | `Ƥ` | `Ƭ` | `Ʋ` | `Ȥ` | `ɓ` | `ƈ` | `ɗ` | `ƒ` | `ɠ` |
| **A\_** | `ɦ` | `ƙ` | `ɱ` | `ɲ` | `ƥ` | `ʠ` | `ɼ` | `ʂ` | `ƭ` | `ʋ` | `ȥ` |  |  |  |  |  |
| **B\_** |  |  |  |  |  |  |  |  |  |  |  |  |  |  | `Ȧ` |  |
| **C\_** | `Ċ` |  | `Ė` |  | `Ġ` |  | `İ` | `Ŀ` |  |  | `Ȯ` |  |  |  |  |  |
| **D\_** |  |  | `Ż` |  |  |  |  |  |  |  |  |  |  |  |  |  |
| **E\_** |  | `§` | `Ä` |  |  |  | `ȧ` |  | `ċ` |  | `ė` |  | `ġ` |  | `ŀ` |  |
| **F\_** |  | `ȯ` |  |  |  |  |  |  |  | `ż` | `«` | `»` |  |  |  |  |

Or, in a code block:

```
¡¢£¤¥¦©¬®µ½¿€ÆÇÐ
Ñ×ØŒÞßæçðıȷñ÷øœþ
 !"#$%&'()*+,-./
0123456789:;<=>?
@ABCDEFGHIJKLMNO
PQRSTUVWXYZ[\]^_
`abcdefghijklmno
pqrstuvwxyz{|}~¶
°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾Ɓ
ƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠ
ɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤ
ỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂ
ĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆ
ẊẎŻạḅḍẹḥịḳḷṃṇọṛṣ
ṭ§Äẉỵẓȧḃċḋėḟġḣŀṁ
ṅȯṗṙṡṫẇẋẏż«»‘’“”

```

**Rules:**

1. You can substitute  with `\n` (`0x10`), `§` with , or `Ä` with `ṿ` if you wish
2. You may use combining diacritics if these can be normalized to the correct character
3. You may represent characters with their Unicode code points or UTF-8/16/32 representations
4. You may output the characters with any reasonable formatting, as long as they are in order (e.g., a 256 character string, an array of characters, a 2d array representing a table with any dimensions, a string with newlines delimiting each character, etc.)

This is , so shortest answer in bytes (per language) wins.

# Answer
# Modified Regenerate `-a --sep=`, 228 bytes

```
[¡-¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ -~
°¹²³⁴-⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥ]|̣[AB-DEHIK-OR-WYZ]|[A-IL-PR-TW-Z]̇|̣[abdehik-or-wyz]|[a-hl-pr-tw-z]̇|[«»‘’“”]

```

Attempt This Online!

I thought Regenerate would be the perfect tool for this. Unfortunately, it only supports ASCII, so I made a trivial modification to allow it to use Unicode.

This is a regex that uses a bunch of character classes to match the various chars, along with combining diactritics to match all the dotted letters. ~~This somehow beat Vyxal :)~~ not anymore :(

The `-a` flag is to list all matches, listing all the possible characters within those character classes. The `--sep=` flag is so that the matches are separated by nothing.
> 7 votes

# Answer
# Jelly (trivial), 2 bytes

```
ØJ

```

Try it online!

> `ØJ`: Yield Jelly's codepage.
> 6 votes

# Answer
# Vyxal `d`, 246 bytes

```
5ʀ⁺<+»*⌊~⁼UIȮǏẇ↳:∵o3tʀ-ð∪ßḭ∩E∑ɽ∨Ẏs„ǎ⁼ṡ{ṪhCcṪėǒ_(»8365τ94ʀ32+₀»=ǒf↲‛ȧ∩¶⁋Ż⌊⁰gḞ~{OGtṪʀ9]•æ§s⁽=%ǔṀ‡Ǐ⟨0⌈Ŀ0w₃pε→sż›7~1Ẋġ:/t≈gʀḞ}ƛƛo"2†⌈ẎḢj\⟑↵$Vꜝ₅İ;ƒ₆βḭ↔#₄ε€@1 SyȧƈḭKǎuẋ→]k≬»»-ṫ»τ20ʀ⁺R+ø⟇C«?kZǎẎQ>l«C803v"»«g}9£~Ŀg»7926τka«× D∇«FC775v"»ƛioꜝ∵~∇¶sẇ»8222τWC

```

Try it Online!
> 5 votes

# Answer
# Vyxal `D`, 201 bytes (UTF-8)

```
`.[-]+`kA`CFGJPQX JKQUV`½vF:N+÷\i-"½vvf`̣̇`f+ƒYf∑`¡©€Æ  ŒÞ  ıȷñ %¶° ²⁴%ƁⱮƝȤɓƈɗƒɠƙɱƥʠɼƭʋȥΠ«‘`kPs10\*"Ṡ%λC¦C∑;øṙ

```

Try it Online!

Warning: This contains a *ton* of unprintables.

One technique this answer uses is to replace bytes preceding multiple `0x01` to `0x1F` with the cumulative sums of those byte sequences. It might be even golfier to allow printable ASCII with this approach but I'm not gonna try now. The code for this <sup>no longer</sup>contains an epic emoji:

All the dotted letters are created with combining characters. I take advantage of how the lowercase form of the second dotted alphabet is the uppercase form minus `i`.

That's pretty much it! This is horribly cursed, but it was fun to make.
> 4 votes

# Answer
# Python, 344 bytes

```
x="̣".join("ABDEHIKLMNORSTUVWYZȦ")+"ḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻ"
print("¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ"+'%c'*95%(*range(32,127),)+"¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥ"+x+x.replace("İ","").lower()+"«»‘’“”")
```

Attempt This Online!

xnor saved 4 bytes with `'%c'`. Thanks!
> 4 votes

# Answer
# Jelly, 170 bytes

```
“¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ”;ØṖ⁵Ż+⁽ø9Ọ“¶°¹²³”;“ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭ§Äẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż”⁾«»⁾‘’⁾“”

```

Try it online!

Builtins are boring, so here is a slightly-less-but-still-kinda-boring answer. Despite multiple attempts to shorten the code by manipulating the code points, it turns out that string literals are the way to go.

That said, we do use some actual encoding in places, and use a couple of tricks to save bytes. The main trick used is "unparseable nilads": when Jelly encounters a nilad that doesn't form one of the chaining patterns, then the current value of the chain is printed, and the nilad becomes the argument to the rest of the chain.

Outputs a newline instead of

## How it works

```
“¡¢...øœþ”;ØṖ⁵Ż+⁽ø9Ọ“¶°¹²³”;“ƁƇƊ...ẋẏż”⁾«»⁾‘’⁾“” - Main link. No arguments
“¡¢...øœþ”                                       - String literal
           ØṖ                                    - Printable ASCII
          ;                                      - Concatenate
             ⁵                                   - Unparseable nilad. Output the characters, and continue with 10 as argument
              Ż                                  - Zero range; [0, 1, ..., 10]
                ⁽ø9                              - Compressed integer: 8308
               +                                 - Add to each; [8308, 8309, ..., 8318]
                   Ọ                             - Convert from code points
                    “¶°¹²³”                      - String literal
                           ;                     - Prepend; [182, 176, ..., 179, 8308, ..., 8318]
                            “ƁƇƊ...ẋẏż”          - Unparseable nilad: string literal
                                       ⁾«»       - Unparseable nilad: "«»"
                                          ⁾‘’    - Unparseable nilad: "‘’"
                                             ⁾“” - Unparseable nilad: "“”"

```

Note that we have to use `⁾«»`, `⁾‘’` and `⁾“”` as all these characters are special characters in strings.
> 3 votes

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

```
$=>`¡¦-©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ [-]~-
°¹²³⁴⁾-ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥ<̣ABDEHIKO-RW-YZ><̇AI->Ŀ<̇MP-RT-WZ-><̣abdehiko-rw-yz><̇ah->ŀ<̇mp-rt-wz->«»‘’“”`[R='replace'](/..-/g,g=([a,b])=>a<b?a+g(String.fromCharCode(a.charCodeAt()+1)+b):b)[R](/<(.)(.+?)>/g,(_,x,y)=>y[R](/./g,'$&'+x)).normalize`NFC`

```

Try it online!
> 3 votes

# Answer
# Pip, 198 bytes

```
Y{^zRMg}._MU"̣cfgjpqx ̇jkquv"^sY[UCyyR"i̇"x]i:C1X5\"¡\i©€Æ  ŒÞ  ıȷñœþ\PA¶°  ²⁴\i\iƁⱮƝȤɓƈɗƒɠƙɱƥʠɼƭʋȥ\y«‘\"R`.[-]+`$.C$+*:A*_H\,#_

```

Try It Online!

-21 thanks to DLosc.

This is a huge mess. Sorta a port of my Vyxal answer, but got a bit out of hand. Beats Vyxal!
> 3 votes

# Answer
# Charcoal, 222 bytes

```
≔Ｉ⪪”}∨q；'⁶γV_⁶ＢιP§τÀ%OC?^H·εY⁴⊞›⊙D⁹↷Ｓχ↓\⸿↶T×⮌RR,s≕⁵aＨ↓E¬[≕\G�ν⁶⁹GG≦XＣq⎇bIV¿↑+σQkiVÀ⌕✳◧´IkE«⁻∕s⁴ⅉＮ▶δ§⦃εＤr\E∧⁵¶Ｌ=/ＵJ⊕Ｍ⁰↓|À｜⊗ς▶≡c℅⬤_÷⌈9∧vºξＰveυΦ"ＲＵ(⊘↧β↨|ＱκRMGXＺ↑Ｈ℅→Ｓ↖kAw+⪫Ｂ:↗:≡⊙iν∨⎚‴S;⁻¤η⪫x¶⁵tZÀzＢΣr⟦Ｘ⎚5y↶M⪫)Ｈ⪪↥Ｗ” υ⭆υ⎇ι℅Σ…υ⊕κγ

```

Try it online! Link is to verbose version of code. Explanation: The most cost-effective approach seems to be to take a compressed list of Unicode ordinal differences, calculate the cumulative sum and convert to Unicode. Additionally, one of the values is `0` which indicates that the ASCII characters  to `~` should be interpolated at this point instead, which saves 3 bytes. Oddly, omitting the value completely (i.e. just having an empty string in the list) actually undoes the saving.
> 2 votes

# Answer
# Bubblegum, 418 bytes

```
00000000: 04c1 0312 c300 0004 c0b7 d7e3 1a83 ba8d  ................
00000010: 6de3 2e7a 475e 925d bcf1 c117 3ffc 2140  m..zG^.]....?.!@
00000020: 8606 033e 7294 e35c e39a 1bee b8e7 95b7  ...>r..\........
00000030: f6c0 079f 1428 d26a ec21 a4cd 9051 7b64  .....(.j.!...Q{d
00000040: 3149 4151 4959 4555 4d5d 4353 4b5b 4757  1IAQIYEUM]CSK[GW
00000050: 4fdf c0d0 c8d8 c4d4 ccdc c2d2 cada c6d6  O...............
00000060: cede c1d1 c9d9 c5d5 cddd c3d3 cbdb c7d7  ................
00000070: cf3f 2030 2838 2434 2c3c 2232 2a3a 2636  .? 0(8$4,<"2*:&6
00000080: 2e3e 2131 2939 2535 2d3d 2333 2b3b 2737  .>!1)9%5-=#3+;'7
00000090: 2fbf a0b0 a8b8 a4b4 acbc a2b2 aaba a6b6  /...............
000000a0: 8e0b d0d0 581d 4a0e 0341 3075 b3fd 9861  ....X.J..A0u...a
000000b0: 9999 7946 3af4 6965 c8a2 2792 f377 7755  ..yF:.ie..'..wwU
000000c0: a5db 94d3 7d7a 10f7 28ee 49dc b3b8 1771  ....}z..(.I....q
000000d0: 495c 1657 89ab c5fd 21ee 4f71 7f59 d7c6  I\.W....!.Oq.Y..
000000e0: f6d6 bed8 37fb 2dbb b56d d9a1 5dda 7d3e  ....7.-..m..].}>
000000f0: 2cde 6c52 7cd9 d7a2 5b8c 6dad d815 7b3b  ,.lR|...[.m...{;
00000100: 2abb c58f d2b3 abf2 2e1f 4175 4101 e81e  *.........AuA...
00000110: 8a40 43e8 5bd0 1e74 067b e008 fa1e 5c07  .@C.[..t.{....\.
00000120: f7c1 4be8 21f8 1754 027d 847a cdc7 20cf  ..K.!..T.}.z.. .
00000130: 54ef 5bf3 096a 9b4a d337 5bf3 1bec 8083  T.[..j.J.7[.....
00000140: 7c0d fe04 7f83 bbe0 3954 0475 0bf5 78d5  |.......9T.u..x.
00000150: 503d 5008 7a80 62d0 08fa 0e74 005d c03e  P=P.z.b....t.].>
00000160: 3886 7e00 37c0 03f0 2a9d fc0b a06e a04f  8.~.7...*....n.O
00000170: 506f f904 e49b ea7b 67be 401d 5349 06d7  Po.....{g.@.SI..
00000180: 2ae4 82c3 7c03 fe02 d7c0 3df0 022a 86ba  *...|.....=..*..
00000190: 837a bafe 4817 a916 e75b 9c9a 384d 715a  .z..H....[..8MqZ
000001a0: ff01                                     ..

```

Try it online!
> 1 votes

# Answer
# Thunno 2 (trivial), 2 bytes

```
kC

```

Attempt This Online!

Thunno 2 and Jelly share the same codepage :)

> `kC`: Thunno 2 Codepage
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, unicode, jelly
---