title: Tips for golfing in GolfScript

text:
# Question
Title: Tips for golfing in GolfScript
What, this post doesn't exist yet?

Of course, GolfScript is *made* for golfing, so you might think that no specific tips are really needed. But to make full use of GolfScript's features, you need to learn some non-obvious tricks. This post is for collecting such helpful tips and tricks.

To start with, here are the official GolfScript reference pages. You should really familiarize yourself with these first:

In particular, I would very much suggest reading the pages in this order — the quick reference is of little use until you're already reasonably familiar with the built-ins, and the tutorial includes some important details that are not explained on the other pages.

---

Ps. For the sake of inspiration and personal interest, here are some questions *I'd* like to see nice answers to:

* How to do limited transliteration in GolfScript? `{FROM?TO=}%` works *if* you can be sure all the inputs are found in `FROM` (or don't mind them all being mapped to the last element of `TO`), but all the ways I've seen for leaving unmapped values unchanged have been more or less klugey.
* How to best convert a string into an array of ASCII codes and back? Which operations do this as a side effect? What's the best way to dump the characters in a string onto the stack (like `~` does for arrays)?

# Answer
## Rational / Float / Complex

I've read so many times that GolfScript has only integers that I started to believe it. Well, it's not true.

```
2-1? # Raise 2 to the power of -1. Result: 0.5
4-1? # Raise 4 to the power of -1. Result: 0.25
+    # Add. Result: 0.75

```

The output is

```
3/4

```

with the standard GolfScript interpreter and

```
0.75

```

on Web GolfScript.

Similar hacks allow to cast to Rational, Float or even Complex:

```
{-2.?./*}:rational
{2.-1??./*}:float
{-2.-1??./*}:complex

```
> 35 votes

# Answer
# Shuffling an array

The easiest way to shuffle an array in GolfScript is to sort it by a random sort key. If you only need to crudely shuffle a few values, the following code will do:

```
{;9rand}$

```

Note that, even for short lists, this will not give a very good shuffle. Due to the birthday paradox, to get a reasonably uniform shuffle, the argument to `rand` needs to be significantly greater than the square of the length of the list being shuffled.

Replacing the `9` above with `99` thus gives reasonably good results for lists of up to ten elements, but exhibits noticeable bias for longer lists.

The following code, which uses 99 = 387,420,489 possible values, is good for up to about 1000 items or so (and acceptable for up to about 20,000):

```
{;9.?rand}$

```

For really long lists, add one more 9 for 9999 ≈ 3.7 × 10197 values:

```
{;99.?rand}$

```

---

### Testing:

Here's the distribution of the first element in a 10-element list shuffled using the different variants shown above, sampled over 10,000 trials:

* The output of `10,{;9rand}$0=` shows a very clear bias, with `0` being more than three times as likely to end up in the first position as `1`:

```
0 16537 #######################################################
1 5444  ##################
2 7510  #########################
3 8840  #############################
4 9124  ##############################
5 12875 ##########################################
6 9534  ###############################
7 8203  ###########################
8 7300  ########################
9 14633 ################################################

```
* With `10,{;99rand}$0=`, most of the bias is gone, but a noticeable amount still remains:

```
0 10441 ##################################
1 9670  ################################
2 9773  ################################
3 9873  ################################
4 10134 #################################
5 10352 ##################################
6 10076 #################################
7 9757  ################################
8 9653  ################################
9 10271 ##################################

```
* With `10,{;9.?rand}$0=`, the output is basically indistinguishable from a truly random sample:

```
0 9907  #################################
1 9962  #################################
2 10141 #################################
3 10192 #################################
4 9965  #################################
5 9971  #################################
6 9957  #################################
7 9984  #################################
8 9927  #################################
9 9994  #################################

```

---

**Ps.** For *really* bad shuffling of numeric arrays or strings, the following code may sometimes be acceptable:

```
{rand}$

```

It will generally be ridiculously biased, but as long as all elements of the input array (or all character codes in the string) are greater than one, it has a non-zero probability of producing any permutation of the array, which may sometimes satisfy poorly written challenge requirements.
> 12 votes

# Answer
# Negating a number

One thing GolfScript lacks is a built-in negation operator. The obvious ways to convert a number on the stack to its negative, like `-1*` or `0\-`, need three chars. However, there's a way to do it in two:

```
~)

```

This works because GolfScript uses two's complement arithmetic, so that ~*x* equals −*x*−1.

Of course, the variant `(~` also works; choosing between them is generally a matter of taste.
> 10 votes

# Answer
## If your program mysteriously breaks, check your variables

I just spent a while debugging an apparently correct program which used `!` as a variable (on the grounds that I wasn't going to use it again). Unfortunately I *did* use `if`, and it turns out that the implementation of `if` calls `!` to decide which branch to follow.
> 8 votes

# Answer
To address a specific subquestion:

> How to best convert a string into an array of ASCII codes and back? Which operations do this as a side effect? What's the best way to dump the characters in a string onto the stack (like ~ does for arrays)?

For those who don't understand the problem, GolfScript's type system gives priority to the types in the order integer, array, string, block. This means that ordinary array operations applied to a string almost always give you a string. E.g.

```
'ABC123'{)}%

```

will leave `'BCD234'` on the stack.

As a result, the best way to convert a string into an array of ASCII codes is almost certainly to dump the characters on the stack and then gather them into an array.

What's the best way to dump the characters in a string onto the stack? `{}/`

What's the best way to convert a string into an array of ASCII codes? `[{}/]` (with the usual caveat that if there's nothing else on the stack you can skip the `[`)

What's the best way to convert an array of ASCII codes into a string? `''+` (Note that this also flattens the array, so e.g. `[65 [66 67] [[[49] 50] 51]]''+` gives `'ABC123'`)
> 8 votes

# Answer
## Wrapping the top item of the stack into an array

> Is there a nice way to transform `... x` into `... [x]`?

For full generality, the best option appears to be 4 chars. However, in certain special cases it's possible to reduce this.

### 1 char

`]` works in the special case that `x`is the only thing on the stack.

### 3 chars

`[]+` works in the special case that `x` is an integer.

`.,/` works in the special case that `x` is a truthy array or string. E.g. `"AB".,/` gives `["AB"]`; `3,.,/` gives `[[0 1 2]]`. However, `"".,/` and `[].,/` both give `[]`.

### 4 chars

`[.;]` works unconditionally.
> 8 votes

# Answer
> I'd like to ask the best ways to do: min, max, and absolute value. All my solutions seem to take way more characters than they should. – Claudiu

## min / max

To find the smallest / largest value in an array, just sort it and take the first / last element:

* `$0=` (3 chars) - minimum element in an arry
* `$-1=` (4 chars) - maximum element in an array

If you know the length of the array, and it's 10 elements or less, you can find the maximum in three chars by replacing `-1` with the index of the last element.

If you have the values on the stack, you can just collect them into an array first. For this, an occasionally useful trick is that `[\]` collects the top two elements of the stack into an array, while `[@]` collects the top three. Thus, we get:

* `[\]$0=` (6 chars) - minimum of two values on stack
* `[@]$0=` (6 chars) - minimum of three values on stack
* `[\]$1=` (6 chars) - maximum of two values on stack
* `[@]$2=` (6 chars) - maximum of three values on stack

The same trick can also be used to find the **median** of three values, which can be occasionally useful:

* `[@]$1=` (6 chars) - median of three values on stack

---

Here's another potentially useful trick for finding the min/max of two values *while leaving the original values on the stack*:

* `.2$>$` (5 chars) - find minimum of two values on stack, while leaving original values untouched
* `.2$<$` (5 chars) - find maximum of two values on stack, while leaving original values untouched

The way it works is that `.2$` clones the top two elements on the stack in reversed order (i.e. `a b``a b b a`), `<` / `>` compares the copies and returns 0 or 1, and scalar `$` then copies either of the two input values depending on the result of the comparison.

---

If you have two nonnegative integers on the stack, you can use `,\,&,` (5 chars) to find their minimum and `,\,|,` (5 chars) to find their maximum. This trick uses set intersection and union, respectively, over the ranges. You can save another character if it's possible to apply `,` to each argument separately without having to exchange them. Since this method computes a range for each argument, it's not very efficient for larger numbers, but could be very useful for smaller inputs.

An even shorter way to find the minimum of two non-negative integers on the stack is `,<,` (3 chars). Alas, this trick does not work for finding the maximum.

---

## absolute value

The GolfScript built-in absolute value operator is `abs` (3 chars). While this is two chars more than I'd prefer, it's hard to beat in general.

In some cases (e.g. for sorting by absolute value) you might find the square of a number an adequate substitute for its absolute value; this can be computed in two chars, either `2?` or `.*`. Thus, we get:

* `{.*}$0=` (7 chars) - minimum element by absolute value in array
* `{.*}$-1=` (8 chars) - maximum element by absolute value in array

Similarly, instead of e.g. testing if the absolute value of a number is less than 3 with `abs 3<` (6 chars, including space), you can test if its square is less than 9 with `.*9<` (4 chars, no space needed).
> 8 votes

# Answer
> What is the best way to modify an array at a given index? – user1502040

That's a good question. There's no direct way to assign a value to an array element in GolfScript, so, one way or another, you're going to have to rebuild the whole array.

The shortest general way I know to insert a new value `x` at index `i` in an array is to split the array at the given index and append `x` to the first half before joining them together again:

* `.i<[x]+\i>+` (11 chars) - insert the value `x` into array at (0-based) index `i`

To *replace* the value at index `i` with `x`, we just need to shorten the second half of the array by one element:

* `.i<[x]+\i)>+` (12 chars) - replace the element at (0-based) index `i` with the value `x`

Alternatively, shortening the first half instead will effectively do the same, but with 1-based indexing, which may sometimes be preferable:

* `.i(<[x]+\i>+` (12 chars) - replace the element at (1-based) index `i` with the value `x`

In all the examples above, if `x` is a number, the square brackets around it may be omitted to save two characters, since it will be auto-coerced into an array by `+` anyway:

* `.i<x+\i>+` (9 chars) - insert the number `x` into array at (0-based) index `i`
* `.i<x+\i)>+` (10 chars) - replace the element at (0-based) index `i` with the number `x`
* `.i(<x+\i>+` (10 chars) - replace the element at (1-based) index `i` with the number `x`

The brackets may also be omitted if either `x` or the input "array" (or both) are actually strings, in which case the result will also be coerced into a string (using the usual array → string conversion rules).

---

Ps. As a special case, if we know that the array has between `i` and 2 × `i` elements, we can insert a new element `x` at the (0-based) index `i` with `i/[x]*` (6 chars). What this actually does is split the array into chunks of up to `i` elements and insert `x` between each chunk. Note that, in this case, the brackets are necessary even if `x` is a number.

---

Pps. An alternative approach is to use dynamically named variables. For example,

```
 'foo' 42 ':x'\+~

```

will assign the value `'foo'` to the variable `x42`, while

```
 42 'x'\+~

```

will retrieve it.

You can optimize this further by omitting the `x` prefix and just assigning directly to the numeric literals — this is perfectly legal in GolfScript, and allows you to save one char from the assignment code and shorten the retrieval code to just ``~` (or nothing at all, if the index is constant!). The down side, of course, is that assigning to a numeric literal will override the value of that literal anywhere else in your code. Often, though, the use of number literals can be avoided (or at least restricted to the beginning of the program, before any of them are reassigned), in which case this trick is perfectly fine.
> 7 votes

# Answer
# Assigning to number literals

Often, instead of writing `1:x` and then using/updating the variable `x`, you can just use and update `1` directly:

```
1:^;{^.p.+:^;}5*
{1.p.+:1;}5*       (4 bytes shorter)

```

Of course, this also works for other starting values, but will break if that value occurs anywhere else in your code.

# Punctuation as variable names

If you *have* to use variables, it's also often wise to use punctuation that isn't already in your code -- lots of programs can do without `&`, `|`, `^`, or `?`. This way, for example, you can write `&n` instead of `x n` to push your variable and then push a newline.
> 6 votes

# Answer
# Final output manipulation

By default, when your program ends, the GolfScript interpreter outputs everything on the stack, plus a final newline, exactly as if your program ended with:

```
]puts

```

What the documentation doesn't directly mention is that the interpreter *literally* calls the built-in `puts` to produce this output, and that this built-in is *literally* defined as:

```
{print n print}:puts;

```

Thus, you can suppress or manipulate the final output by redefining `puts`, `print` and/or `n` (or  if you're feeling really twisted). Here are some examples:

### Suppress final newline:

```
'':n;

```

(Of course you can leave out the `;` if you don't mind an extra empty string on the stack.)

### Suppress final output completely:

```
:puts

```

This overwrites `puts` with whatever happens to be on top of the stack. If that happens to be something you don't want to execute, you can use e.g. `0:puts;` instead. Note that this also suppresses `p` (which is defined as `{`puts}:p;`), but you can still use `print` for output if you want.
> 5 votes

# Answer
### Limited transliteration

To address a specific subquestion: given a string, what's the best way to perform a `tr`? E.g. `tr/ABC/abc/`

If all of the characters in the string will be affected, this is quite easy: `{'ABC'?'abc'=}%` (overhead: 9 chars).

However, that breaks if some of the characters aren't transliterated and `'ABC'?` gives `-1`.

If the transliteration is non-cyclic it can be done one replacement at a time with string splits and joins: `'AaBbCc'1/2/{~@@/\*}/` (overhead: 15 chars). This may be improvable, but there's an alternative approach which is currently better and works for cyclic transliterations.

Currently, the shortest general solutions have an overhead of 14 characters:

* One approach involves an escape character: `{.'ABC'?'abc**0**'=\or}%`, where the `**0**` denotes a literal null byte. (Of course, this method is not *completely* general: it cannot map any other character into a null byte.)
* Alternatively, `{.'ABC'?'abc'@),+=}%` has the same overhead, but uses only printable ASCII characters. The `@),+` is a convoluted (but, apparently, the shortest) way to ensure that the replacement string always ends with the input character.
> 5 votes

# Answer
# Turn a string to an array of char

You can do this by typing: `1/` after it.

Example: `"String"1/` pushes to stack the array `['S''t''r''i''n''g']`.

This is handy when you want to move chars around the string.
> 5 votes

# Answer
## Removing duplicates from an array

The set operators `|` (union), `&` (intersection) and `^` (symmetric difference) will collapse multiple array elements into one. Thus, the simplest way to remove duplicate elements from an array is to take its union or intersection with itself:

```
.|

```

or:

```
.&

```

These operators will treat strings as arrays of characters, so they can also be used to remove duplicate characters from strings.
> 4 votes

# Answer
## Filtering an array

The most general way to filter an array is to use `{ },`, which evaluates the code block for each element of the array, and selects those elements for which the resulting value is true (i.e. it acts like `grep` in Perl).

However, using the array subtraction operator `-` is often shorter. This operator takes two arrays, and removes every element that occurs in the second array from the first. It does *not* alter the order of the elements in the first array or collapse duplicates. A useful trick is to apply the subtraction operation twice to yield a non-collapsing array intersection operator:

* `a b -`: remove any elements found in array `b` from array `a`
* `a. b --`: remove any elements *not* found in array `b` from array `a`

---

In particular, this can be used to **count the number of times an element occurs** in an array:

* `a.[c]--,`: count the number of times the element `c` occurs in the array `a`

In general, this method is not optimal, since either of:

* `a[c]/,(`: count the number of times the element `c` occurs in the array `a`
* `a{c=},,`: count the number of times the element `c` occurs in the array `a`

is one character shorter (and, if it's OK for the count to be off by one, `a[c]/,` saves one character more). However, in the special case where `c` is a number and `a` is a normal array (not a string), the square brackets around `c` may be omitted because the `-` operator coerces its arguments to the same type:

* `a.c--,`: count the number of times the number `c` occurs in the array (not string!) `a`

(If `a` is a string and `c` is a number between 0 and 9, `a.c--` will count the number of times the *digit* `c` occurs in `a`.)

---

A similar trick can by used to find the **most common element in an array**:

```
:a{a\[.]-,}$0=

```

Again, if the input is an array of numbers, the whole `[.]` sequence may be omitted. Alas, this does *not* work for strings without the `[.]`.
> 4 votes

# Answer
# Read from STDIN

GolfScript can read from stdin:

```
"#{STDIN.read}"

```

This will continue reading from STDIN until the EOF is reached. Alternatively:

```
"#{STDIN.gets}"

```

or

```
"#{STDIN.readline}"

```

Other things available:

```
getbyte
getc
gets([sep])
gets(limit)
gets(sep, limit)
inspect # perhaps useful for an underhanded contest
isatty
read([length])
readbyte
readchar
readline([sep])
readline(limit)
readline(sep, limit)
readlines([sep])
readlines(limit)
readlines(sep, limit)
readpartial(maxlen [, outbuf])

```

For each of these, they can only be used once (and also once for each change of the parameter, also once more with empty parentheses); after that, the original value is what you'll get instead of a new value.
> 4 votes

# Answer
# Defining new built-in operators

The standard GolfScript interpreter has a rarely used feature that allows interpolated Ruby code in double quoted string literals.

One reason why this feature isn't more commonly used is that, awkwardly, the interpolated code is executed *at compile time*, and the output is cached by the GolfScript interpreter so that the same string literal will thereafter always yield the same value, even inside string eval.

However, one thing this feature turns out to be good for is defining new GolfScript operators implemented in Ruby code. For example, here's how to define a new binary addition operator that works just like the standard built-in `+` operator:

```
"#{var'add','gpush a+b'.cc2}";

```

It doesn't really matter where you put the definition in your code; the new operator gets defined as soon as the double-quoted string containing the Ruby code is parsed. The `add` operator defined above works *exactly* like the built-in `+` operator, and can be used in exactly the same way:

```
1 2 add          # evaluates to 3
"foo" "bar" add  # evaluates to "foobar"

```

Of course, defining a new addition operator is pretty useless, unless you've done something silly like erase the built-in `+` operator. But you can use the same trick to define new operators that do things Golfscript cannot (easily) do natively such as, say, uniformly shuffling an array:

```
"#{var'shuf','gpush a.factory(a.val.shuffle)'.cc1}";

10,shuf          # evaluates to 0,1,2,...,9 in random order

```

or printing the contents of the whole stack:

```
"#{var'debug','puts Garray.new($stack).ginspect'.cc}";

4,) ["foo" debug  # prints ["" [0 1 2] 3 "foo"], leaving the stack untouched

```

or interactive input:

```
"#{var'gets','gpush Gstring.new(STDIN.gets)'.cc}";

]; { "> " print gets ~ ]p 1 } do   # simple GolfScript REPL

```

or even web access:

```
"#{
  require 'net/http'
  require 'uri'
  var'get','gpush Gstring.new(Net::HTTP.get_response(URI.parse(a.to_s)).body)'.cc1
}";

"http://example.com" get

```

Of course, a somewhat golfier (and riskier!) implementation of the latter would be e.g.:

```
"#{var'get','gpush Gstring.new(`curl -s #{a}`)'.cc1}";

```

While not particularly golfy in itself, this lets you extend the capabilities of GolfScript beyond what the built-in commands provide.

---

### How does it work?

The authoritative reference on how to define new GolfScript operators in this way is, of course, the source code for the interpreter. That said, here's a few quick tips:

* To define a new operator `name` that runs the Ruby code `code`, use:

```
var'name','code'.cc

```
* Inside the code, use `gpop` to read a value off the stack, and `gpush` to push one back in. You can also access the stack directly via the array `$stack`. For example, to push both `a` and `b` onto the stack, it's golfier to do `$stack<<a<<b` than `gpush a;gpush b`.

+ The positions of the `[` array start markers are stored in the `$lb` array. The `gpop` function takes care of adjusting these markers down if the stack shrinks below their position, but manipulating the `$stack` array directly does not.
* The `.cc` string method that compiles Ruby code in a string into a GolfScript operator is just a convenience wrapper around `Gblock.new()`. It also has the variants `.cc1`, `.cc2` and `.cc3` that make the operator automatically pop 1, 2 or 3 arguments off the stack and assign them to the variables `a`, `b` and `c`. There's also an `.order` method that works like `.cc2`, except that it automatically sorts the arguments by type priority.
* All values on the GolfScript stack are (and should be!) objects of type `Gint`, `Garray`, `Gstring` or `Gblock`. The underlying native integer or array, where needed, can be accessed via the `.val` method.

+ However, note that `Gstring.val` returns an array of `Gint`s! To turn a `Gstring` into a native Ruby string, call `.to_s` on it instead (or use it in a context that does that automatically, like string interpolation). Calling `.to_gs` on any GS value turns it into a `Gstring`, so any GS value can be stringified with `.to_gs.to_s`.
* The `gpush` function doesn't auto-wrap native Ruby numbers, strings or arrays into the corresponding GS types, so you'll often have to do it yourself by explicitly calling e.g. `Gstring.new()`. If you push anything other than one of the GS value types onto the stack, any code that later tries to manipulate it is likely to crash.
* The GS value types also have a `.factory` method that calls the type's constructor, which can be useful e.g. for rewrapping arrays/strings after manipulating their contents. All the types also have a `.coerce` method that performs type coercion: `a.coerce(b)` returns a pair containing `a` and `b` coerced to the same type.
> 4 votes

# Answer
# Tuck an integer literal into a block

If you have some code that pushes a block and then an integer between 100 and 255:

```
{2,{2+base}/n}105,%

```

You can save a byte by extracting the integer as a byte from the block with `)` or `(`.

```
{2,{2+base}/ni}),%
{i2,{2+base}/n}(,%

```

(This is A005836 by tails on anarchy golf.)

The `i` has ASCII value 105. GolfScript code is not treated as UTF-8, so you can put a raw byte like 200 or 250 in the file. See this answer by tails for another example.
> 4 votes

# Answer
## Decoding hexadecimal input

GolfScript has no hex integer literals, so, alas, you can't just parse hexadecimal input with `~`. Instead, if your code must take hex input, you'll need to parse it manually.

This 8-char loop, applied to a string, will convert lowercase hex digits to their numeric equivalents:

```
{39%9-}%

```

If you have to (also) accept uppercase hex digits, the easiest (and likely shortest) solution is to first lowercase them with `32|`, for a total of 11 chars:

```
{32|39%9-}%

```

Note that the output will technically still be a string (consisting of the ASCII characters 0 – 15), but most GolfScript array functions will accept strings, too. If you absolutely need an array, you can always use `[{39%9-}/]` (where the first `[` is optional if the stack is otherwise empty).

To convert the output of the code above into an integer, you can simply use `16base` (6 chars). If you want an array of bytes instead, the shortest solution I've found in simply to decode each pair of hex digits with `2/{16base}%` (11 chars). All put together, the shortest code I've found to turn a hex string into a byte array is 8 + 11 = 19 chars:

```
{39%9-}%2/{16base}%

```

Note that the output of this code *is* indeed an array, not a string. If needed, you can stringify it by concatenating it e.g. with `""+` or, if you don't mind an extra newline at the end, `n+`.
> 3 votes

---
Tags: code-golf, tips, golfscript
---


title: Hello, Permutations!

text:
# Question
Title: Hello, Permutations!
For this challenge, you will be required to write 3 programs:

1. The first program should be a quine, i.e, it should print it's own source code.
2. The second program should read the input and print all of it.
3. The third program should simply print the string `"Hello, Permutations!"`, with or without quotes.

In addition to that, all the three programs should be **permutations**, i.e, starting from any of the three programs, you should be able to obtain the other by re-arranging it's characters. So all programs will have the same byte count and frequency of characters. For example: `abcd`, `dbca` and `adbc` are permutations.

# Rules

* You may choose to write functions instead of programs.
* For the first program, you are not allowed to read the source file and print it.
* You only need to read the input for the second program. No input will be provided to the other two programs.
* Standard loopholes are forbidden.
* This is , so the shortest code (in bytes) wins.

# Answer
> 13 votes
# Underload (stringie), 33 bytes each

```
((aS(:^):SHello, Permuttions!):^)
(S(Hello, Permutations!)(:::^^S))
((Hello, Permutations!)S(:::^^S))

```

Try it online!

These are function submissions that input via the argument stack, but output to standard output. (The functions also produce garbage output using the more normal mechanism for function output, but according to our normal I/O rules, we only look in one place.)

## Explanations

```
(aS(:^):SHello, Permuttions!):^
(aS(:^):SHello, Permuttions!)     string literal
                             :    non-destructive
                              ^     eval
 a                                enclose {the string literal} in parens
  S                               print it
   (:^)                           string literal
        S                         print that too
       :                          retaining a copy
         Hello, Permuttions       no-ops
                           !      discard the retained copy

S(Hello, Permutations!)(:::^^S)
S                                 print {function input}
 (Hello, Permutations!)           string literal {2nd return value}
                       (:::^^S)   string literal {1st return value}

(Hello, Permutations!)S(:::^^S)
(Hello, Permutations!)            string literal
                      S           print it
                       (:::^^S)   string literal {return value}

```

If we weren't exploiting this site's I/O rules, it'd cost one extra byte (along with a little code rearrangement) to output the output we wanted (either to standard output or as the function return value), and delete the output we didn't want. But just leaving the extra characters that we're forced to use in order to make a permutation on the argument stack is very slightly shorter.

The quine is an eval quine: we write most of the program in a string literal and `eval` it, but we still have the original string literal available (because we made the `eval` non-destructive) and can print it in addition to running it. (This isn't code reading itself, rather the `:^` reads one string and uses it for two different purposes.)

# Answer
> 13 votes
# , ~~58~~ 56 characters, ~~22~~ 21 bytes each

```
00000000011111111222233333444444445555**7**1**7**1**6**2234430404053
```

Try it online!

```
1313131300000002244444444445555**7**2111**7**20000**6**0322351311443
```

Try it online!

```
**7**532510130304043205104345101144411240324104020054321**67**43
```

Try it online!

> **Update**: Since the first version of this answer, I golfed off a **`7`** and a `0` – the hello program was slightly rearranged to be able to make use of the **`6`** rather than needing a `0`, and the quine was entirely rewritten to use fewer **`7`**s. The text below has been updated to match; see the edit history for the previous version of this answer.

No cheating with I/O this time: these are all full programs which output to standard output, and (in the case of the second program) input from standard input. The cat program was the hardest of the three to write by far, because it's the only program that requires a loop.

7's character encoding (which is just octal) encodes eight characters per three bytes. This program is thus 21 bytes long (⅜ of 56). Because this is an integer, we don't have to worry too much about the weird sub-byte encoding, but in order to make the programs "conceptually shorter", I ensured that they all ended with a `3` (the interpreter treats trailing 1 bits like trailing whitespace, so the final two bits of the encoding are arguably not part of the program). Note that I can't end a program with a **`7`** because it would be ignored entirely, causing the program to no longer be 56 characters long (and thus the programs to not be permutations of each other).

## Explanations

My usual reminder: 7 has 12 commands, but only 8 of them have names. I use the notation `0`, `1`, `2`, `3`, `4`, `5` for the commands that append **`6`**, **`7`**, **`2`**, **`3`**, **`4`**, **`5`** respectively to the top stack element (the last four of these commands cannot appear literally in a program and can only be created at runtime by using them to create a program on the stack).

### Quine

```
00…55**7**1**7**1**6**22…53
00…55              An arbitrary string literal
     **7**             Separator between elements of the initial stack
      1**7**1**6**22…53    Literal representing the main program

```

The first pass through a 7 program can't do anything more than push literals to the stack (the rightmost goes towards the top of the stack). However, after doing that, the top stack element is implicitly executed (non-destructively; it remains on top of the stack, and a copy is executed). It does the following:

```
**7**1**2234436464653**
**7**1                     Push stack element "**7**"
  **2**                    Duplicate it
   **23**                  Use one copy as an I/O routine (sets I/O format 7)
     **443**               Swap the "**7**" and main program
        **6**              Uneval the main program, and
                         append it to the stack element below
         **46**            Uneval the second stack element, while
                         swapping it to the top of the stack
           **46**          Uneval the second stack element, while
                         swapping it to the top of the stack
             **5**         Execute the new top of stack
                         (this undoes the uneval and appends it
                          to the element below)
              **3**        Output (+ some irrelevant side effects)

```

It's a little hard to follow this, so here's a description of what's happening to the stack. It starts with two stack elements: the arbitrary literal, below the main program (both of these start out in evaluated, ready-to-run, form). The program immediately adds a third (the literal **`7`**), which is (nondestructively) used to set the I/O format (to format 7, "the same format as is used for the source code"). It then works out what source code is most likely to have produced the executable/evaluated main program via using the **`6`** command (and I intentionally wrote it in a way that would round-trip properly), and appends it to the **`7`** – this generates a string literal, the source code for the latter half of the quine (from the first **`7`** onwards). Then it undoes the evaluation of the arbitrary literal below (working out the source code that generated that arbitrary literal, too – source code consisting only of nonbolded characters roundtrips perfectly as they have a very obvious effect on the stack), and prepends that to our calculated second half of the quine's source code, producing the source code of the quine as a whole (and outputs it).

The confusing part is that the **`46465`** near the end, which undoes the evaluation of the arbitrary literal and prepends it to the rest of the quine's source code, has the two operations (unevaluating and prepending) interleaved with each other. This is because there isn't a direct "append" instruction in 7. Rather, there are two ways to append things – the **`6`** command does both an unevaluate and an append, and string literals append themselves to the top stack element when executed rather than creating a new stack element. So in order to append two string literals without a net change to the escaping level, the latter needs to be unevaluated in-place (and it needs an empty element beneath to append to due to the other effect of **`6`**), and then executed using **`5`**. The most convenient way to cancel out the side effect of **`6`** is to use the swap command **`4`** – this places an empty stack element in between the two elements it's swapping. So we need to interleave swaps in with the unescapes, and this means interleaving the routines that operate on the two relevant stack elements, swapping between the routines every time the stack element swaps.

Incidentally, this is a proper quine under CGCC's definition because the 1 in `**7**1**6**` is used to output the first **`7`** in the output (in addition to representing itself). (You can observe this by changing this section of code to, e.g., `**7**10101**6**` – the separator changes to **`76767`** in the output, and you get a `6767` at the start of the output because the same literal is also output to set the I/O format.)

### Cat program

I actually hadn't written a cat program in 7 before, and it's not as trivial a task as it looks.

```
13131313…**7**2111**7**20000**6**03…43
13131313…                    Literal representation of program **73737373…**
         **7**                   Separator between elements of initial stack
          2111**7**20000**6**03…43   Literal representation of program **2777**20000**63…43**

```

Two programs, here, which run in (7's usual reverse) sequence.

The program on the left (which runs last) pops the stack (**`73`**) four times. It won't have four elements on it at that point, and a pop on an empty stack is defined to exit the program (stack underflow is normally an error, but this is a special case). So the rest of that program never runs, and it gives us a place to put all the digits we have to include (due to the permutation restriction) but aren't using for anything.

The program on the right is more interesting, and implements the cat behaviour. It assumes that a copy of itself will exist on the top of the stack when it starts running (this will always be the case on the first iteration, because 7 leaves the top of stack in place when it starts running it).

The program on the right is also a silly sort of polyglot. The numerical value of a string in 7 is defined as the total number of `1` and **`7`** characters in it, minus the total number of `0` and **`6`** characters; other characters are ignored. With six **`7`**s, four `0`s and a **`6`**, this string has a numerical value of +1. This is intentional and required for the program to work, because the string in question is used interchangeably as an implementation of the cat program, and a representation of the integer 1, while the program is running. (This sort of polyglotting is pretty unusual, but helped me save the need for a second **`6`** character, which would have hurt the byte count because the hello program (the longest) doesn't have any natural reason to use one and so we can't just borrow one from its string literal.)

The string literal **`20000`** is also a polyglot. This is used only as an I/O control string. The numerical value of -4 means "input a character", when we try to interpret it as a character code (input is done by outputting otherwise impossible/illegal values, like negative character codes); the leading 2 means "output character codes as characters". The default character set for character I/O is 8-bit SBCS. So on the first iteration, we configure I/O for byte-at-a-time operation, and reinterpret the same value that does that as -4 and thus input a character in the process. In the subsequent iterations, I/O is already configured as byte-at-a-time, so only the numerical value of -4 matters.

Bearing those factors in mind, we can now look at how the program works:

```
**2777**20000**6322357377443**
**2**                          Duplicate top of stack
  **77**20000**6**                 Escaped literal 20000 (non-bolded)
 **7**        **3**                Output literal (actually takes input)

```

Input is implemented by duplicating the top of stack a number of times equal to the input, off-by-one (so that EOF can be 0, NUL is 1, SOH is 2, etc.). The same off-by-one applies on output. So the stack is now our 1/cat polyglot, below an integer (which is repeated copies of the cat program) representing our input. We can output it immediately to implement cat behaviour.

```
**2777**20000**6322357377443**
           **223**             Non-destructive output of top of stack
              **5**            Pop and eval top of stack
               **73**          Pop top of stack
                 **77**        Push two empty stack elements
                   **443**     Swap those empty elements

```

After producing our output, we loop by executing ourself again. Or do we?

The program has to halt on EOF. If you look carefully, you'll note that we aren't executing the original cat program (the one with an integer value of 1); that's on the stack just below the element we eval'ed. The stack element actually being executed is the one we just output: the character code that was read in from the user. Remember that this is made up of a number of copies of the cat program, so in most cases we can simply just execute it and it'll work the same way as the original program. However, if the character code we read in is EOF, it'll consist of no copies of the cat program, so there will be nothing to run. We then pop the remaining cat program from the stack, and there are no printing or looping commands left in the program, so it must eventually end up exiting naturally. This gives us a clean exit at EOF, whilst being very very esoteric. (The two **`7`** commands at the end are clearly pointless, of course; they exist purely to get the numerical value of the cat program right, and don't cost any bytes because they're needed to maintain the permutation property anyway, as they're generated from `1`s and we have plenty of those in the hello string literal. The **`433`** at the end is a no-op, also made from characters that would need to be added somewhere anyway – its purpose is to ensure that the original program ends with a `3`.)

### Hello program

```
**7**53…1**67**43
**7**                Empty padding element on initial stack
 53…1            Literal representation of string **53…7**
     **6**           Uneval that string (on the first pass!)
      **7**          Separator between elements of the initial stack
       **43**        Modified "print a literal" program

```

This is a version of the 7 hello-world program, modified a little more extensively than in the original version of this answer.

The standard hello-world program in 7 consists of a string literal followed by `**7**403` – during the first pass through the program, the literal is evaluated into live executable code, but the **`40`** swaps it to the top of the stack and unevaluates it (getting back at the original string literal), and the **`3`** then prints it (and also pops the **`463`** stack element that's the currently executing code – remember, the top stack element gets executed after the first pass through the program, but is *not* popped in the process). That's what I did for the first version of this answer.

However, this program needs to contain a **`6`** somewhere, so that it can be a permutation of the cat program. It's possible to make use of this to save the `0` from the original version of the answer – instead of unevaluating the string literal while the "print a literal" program is executing, we can instead unevaluate it on the first pass through the program (because **`6`** and **`7`** commands run immediately). Program execution starts with two empty elements on the stack, so the **`6`** unevaluates the string literal (returning it to its original form in the source code) and appends it to one of them. That lets us write the program that actually prints the literal as just **`43`** rather than **`463`** (so the original source that represents it is just `43` rather than `403`).

An unfortunate consequence of this way of doing things (as opposed to the normal way to write a hello-world program) is that the **`43`** never actually ends up getting popped from the stack. It thus runs again when the end of the program is reached, and ends up crashing the program due to stack exhaustion rather than exiting cleanly. However, we do have the right output on standard output, and that's all that matters.

The literal is, as usual for 7, encoded in a domain-specific language intended for encoding strings; the `5` at the start of the long literal selects this. It contains four different sets of 32 characters (uppercase letters, lowercase letters, digits and common symbols, and rare symbols), with shift codes to switch between them; and within each set, each character is encoded as two octal digits in the `0`-`5` range (because **`6`** and **`7`** are needed as delimiters). Apart from the reinterpretation of 5 bits as two base-6 digits, this encoding wasn't invented for 7; it is in fact the US-TTY encoding (a variant of Baudot), which was commonly used before ASCII was invented, and which is often a little shorter for commonly used strings than ASCII would be, despite containing all the same characters.

`Hello, Permutations!` requires five shift codes (which can be visualised as `H**ł**ello**Ø**, **Ł**P**ł**ermutations**Ø**!`), so it's 20 + 6 = 25 characters long, thus 50 octal digits when encoded as a 7 literal (51 total when allowing for the `5` to select the encoding). This comes to 18¾ bytes, just slightly shorter than the string would be in ASCII.

# Answer
> 9 votes
# JavaScript (V8), 31 bytes

```
t=>//==+
'Hello, Permutations!'

```

```
t=l=>//Helo, Permuaions!
't='+t

```

```
t=l=>//Heo, Permutations!=+''
l

```

Try it online!

The comment is placed in the middle of the function to appear in the stringified output.

Alternatively for 30 bytes, but only works in Firefox 86- due to a bug where the trailing comment is included in the stringified output:

```
t=>'Hello, Permutations!'//==+
t=l=>'t='+t//Helo, Permuaions!
t=l=>l//Heo, Permutations!=+''

```

Try it online!

Or for 32 bytes it can be done without using comments:

```
(t='=+')=>'Hello, Permutations!'
t=l=>('Helo Permuaions!','t='+t)
t=(l='Heo, Permutations!'+'')=>l

```

# Answer
> 9 votes
# Ruby, <sup>~~43~~</sup> 37 bytes each

*Saved 5 bytes thanks to @Sisyphus, plus another with further golfing.*

### Quine

```
eval o="print'eval o=%p'%o#g,tHumPs!"

```

Try it online!

### Cat

```
print gets#="'=%'%um,Halve ovalPoop!"

```

Try it online!

### Print

```
p"Hello, Permutations!"#v='va =%p'%og

```

Try it online!

Verify that the three programs are permutations of each other here.

# Answer
> 7 votes
# Python 2, 55 bytes each

Each is a lambda function which performs the specified task.

```
lambda t='lambda t=%r:t%%t#Helo,Puins!':t%t#Helo,Puins!
lambda s:s ##!!%%%%'',,:==HHPPaabdeeiilllmnnoorttttttuu
lambda:'Hello, Permutations!'## !%%%%,:==HPabdilnsttttu

```

Quine it online!, Cat it online!, Print it online!

# Answer
> 3 votes
# PHP, ~~71~~ ~~69~~ 67 bytes (quine)

```
eval($o='!Printf ("eval(\$o=%c%s%c);//gHemut",39,$o,39);');//gHemut

```

Try it online!

# PHP, 67 bytes (cat)

```
!list(, $o)=$argv;ecHo($o);//'Pnf"eval(\=%%%cemut"39,,39)';//gHemut

```

Try it online!

# PHP, 67 bytes (Hello, Permutations!)

```
ecHo('Hello, Permutations!');//v$=tf("va(\$=%%%cg"39,$,39););//gemu

```

Try it online!

This is the best I've got so far.. still searching

EDIT: I could get rid of the `d` with `list(,$o)=$argv;` instead of `end($argv)`

EDIT 2: saved 2 bytes by moving the space and the `!` inside the part of the quine that doesn't have to be repeated

# Answer
> 3 votes
## Functions:

# Haskell, 61 bytes (quine)

```
--dHel,Prmuta!
i=c++show c;c="--dHel,Prmuta!\ni=c++show c;c="

```

Try it online!

Not sure what the rules are for a "function quine" in Haskell. This code defines `i` to be a string containing the given source code.

# Haskell, 61 bytes (cat)

```
--dHel,Prmuta!c++show c;c="--Hel,Prmuta!\n=c++show c;c="
i=id

```

Try it online!

# Haskell, 61 bytes (print)

```
--d,Prmua!c++hw c;c=--dH\=c++shwc;c=
i="Hello, Permutations!"

```

Try it online!

Verify they're anagrams

---

## Full programs:

# Haskell, 75 bytes (quine)

```
--lid,HelP!
main=putStr$c++show c;c="--lid,HelP!\nmain=putStr$c++show c;c="

```

Try it online!

# Haskell, 75 bytes (cat)

```
-- !!""$$++++,,--;;===HHPPSS\cccccdehhillllmnoopprssttuuww
main=interact id

```

Try it online!

# Haskell, 75 bytes (print)

```
-- !$$++++,--;;===HPS\ccccccddhhiillnpsww
main=putStr"Hello, Permutations!"

```

Try it online!

Verify they're anagrams

# Answer
> 2 votes
# 05AB1E, ~~38~~ 32 bytes each

-6 bytes thanks to @Kevin Cruijssen

```
0"”Ÿ™,„œmu¦–!”„ SK"0"D34çý"D34çý
,0"”Ÿ™„œmu¦–!”„ SK"0"D34çý"D34çý
0""0"D34çý"D34çý”Ÿ™,„œmu¦–!”„ SK

```

Try it online quine

Try it online cat

Try it online Hello, Permutations!

# Answer
> 2 votes
# PHP, 33 bytes

```
 !""$,1;;<=?HP[]aeegillmnoorsttuv

```

Try first

```
<?=$argv[1];"Hello, Pemuttions!";

```

Try second

```
<?="Hello, Permutations!";$gv[1];

```

Try third

Verify

# Answer
> 2 votes
# Golfscript, ~~40~~ 35 bytes

The following three programs are each quine, cat, and "Hello, Permutations!".

Edit: I could save some bytes realizing that undefined commands are ignored in golfscript.

```
".7<:n;`Hello, Permutatios!".7<:n;`

```

Try quine online!

```
"":n Hello,..<<``:Permutations;77!;

```

Try cat online!

```
"Hello, Permutations!":n;7..<<``:7;

```

Try "Hello, Permutations!" online!

## Explanation:

The whole input is implicitly stored on a stack as a single string.

Also, each element on the stack is implicitly printed when the program halts.

Note that `n` is printed at the end regardless of its value(which is initially newline). Therefore, one should re-define `n` to prevent trailing newlines. On the other hand, one can use this property as `print(end="string")` trick in Python.

1. Quine

```
".7<:n;`Hello, Permutatios!"        # Puts this string on the stack. Note that backslashes are escaped.
                            .       # Duplicates the string. Now, there are two identical strings on the stack.
                             7<     # Truncates the original string, so it will be 7 chars long(.7<:n;` to be precise).
                               :n;  # Defines n to be the truncated string.
                                  ` # 'Unevals' the string top of the stack. The unevaled string will generate the first half of the source-code when printed.

```

After that, the un-evaled string will be implicitly printed. Also, the truncated string will be printed instead of a newline.

2. Cat

~~'#' marks a comment section in Golfscript. Therefore, the program is identical to the following:~~

'#' is not used anymore.

```
"":n                                # Defines n to be an empty string. This has the same effect as doing 'print(string, end="")' in Python.
     Hello                          # Does nothing.
          ,..<<``                   # These commands generate and consume the same number of elements, which mean that there is 1 element left ("") on the stack.
                 :Permutations;     # Defines that element to be 'Permutations' and discard it.
                               77!; # Puts 77 on the stack, 'not' it, and discard it. Does nothing.

```
3. "Hello, Permutations!"

~~Again, behind '#' is ignored.~~

```
"Hello, Permutations!":n;           # Defines this string as 'n' to make it implicitly printed.
                         7..<<``:7; # Again, these are valid commands, but they are arranged to do nothing.

```

# Answer
> 2 votes
# brainfuck, 396 bytes

# Quine:

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

```

Try it online!

This is basically the shortest known brainfuck quine, extended a little bit, so it contains an extra `,` that is needed for the cat program.

# Cat:

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

```

Try it online!

The only interesting part of this is the `+[-[+.[-]],]`, which is a little overcomplicated cat program. It needs to be like this, so it uses only one comma and still doesn't print an extra null-char at the end.

The rest is just the remaining characters put in brackets, so they won't be executed.

# Hello, Permutations:

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

```

Try it online!

This actually needed a little bit of brain power. I had lots of `+` and `>` symbols, but only three `-`, one `.` and nine `<` symbols.

So this uses a similar approach like the quine. First, I write a list of how often each character is divisible by 32. This list will be multiplied by 4, then I add to each cell the remaining factor of 8, multiply each cell by 8 and finally, add the remaining units. Then all characters are printed in the usual way. After that, I just dump the remaining characters.

# Answer
> 2 votes
# GolfScript, 27 bytes

## Quine

```
{!,Hello Permutatios":n"}:n

```

Try it online!

## Cat

```
"":n}{:Hello, Permutations!

```

Try it online!

## Hello

```
"Hello, Permutations!"}{:n:

```

Try it online!

# Answer
> 1 votes
# R console, 35 bytes

Uses comments in a similar way to most of the other approaches.

```
function(at){'readle(Hlo, Pmts!#)'}
cat(readline())#futton{'Hlo, Pms!'}
cat('Hello, Permutations!')#dnf(){}

```

Character breakdown:

```
'   ! # ( ) , { } a c d e f H i l m n o P r s t u
2 1 1 1 2 2 1 1 1 2 1 1 2 1 1 1 2 1 2 2 1 1 1 3 1

```

# Answer
> 1 votes
# \>\<\>, 37 bytes each

```
"""r00g::ol?!;80.sniotatumeP ,olleH><
>io00.::ol?;80gsntatumreP ,olleH<"""!
"!snoitatumreP ,olleH">o<00.::l?;80g"

```

Quine: Try it online!

Cat: Try it online

Hello Permutation: Try it online!

# Answer
> 1 votes
# Befunge-98 (FBBI), 31 bytes each

```
"mHello Peruttions!j~@,k'-a,'
~,'!jHello, Permutations"'-k@
"'k,@-'j~!snoitatumreP ,olleH

```

There are two unprintable bytes: RS (ASCII 30) before the first `'` in the first program, DC3 (ASCII 19) after the first `'` in the third program, and the same bytes in the unused areas of each other program. To represent these characters in the explanations, I have used `<30>` and `<19>` respectively.

## Quine

Try it online!

```
"mHello Peruttions!<19>j~@,k<30>^S'-a,'
"                                        Begin string mode
 mHello Peruttions!<19>j~@,k<30>'-a,'    Push the rest of the code as a string
"                                        End string mode
 m                                       Not defined in Befunge: reverse direction
"                                        Begin string mode
 mHello Peruttions!<19>j~@,k<30>'-a,'    Push the rest of the code backwards
"                                        End string mode
                                 -       Subtract
                                  a               10 from
                                   ,'                     44, leaving 34 (the quote character) on top
                           k             Repeat
                            <30>'               31 times:
                          ,                               print the top character
                         @               End the program

```

Mostly a standard quine, but reuses the `a` and `,` characters from `Hello, Permutations!` to help construct a `34`, and the `m` to reverse direction.

## Cat

Try it online!

```
~,'!jHello, Permutations<19><30>"'-k@
~                                        Get a character from input
 ,                                       Print the character
    j                                    Jump forward
  '!                                                  33 spaces, going back to the start
                                         On EOF:
~                                        Reverse direction
                                    @    End the program

```

A standard cat program, using `j` to skip over the unused section.

## Hello, Permutations!

Try it online!

```
"'<19>k,@<30>-'j~!snoitatumreP ,olleH
"                                       Begin string mode
 '<19>k,@<30>-'j~!snoitatumreP ,olleH   Push this string, ending in "Hello, Permutations!" backwards
"                                       End string mode
      k                                 Repeat
 '<19>                                         20 times:
       ,                                                 print the top character
        @                               End the program

```

Relies on the FBBI-specific behavior that no spaces are pushed when wrapping in string mode.

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

Pretty straight forward solution

1. Quine

```
exec(l:="input('exec(l:=%r)'%l)#Ho, Pmutationsp!")

```

Try it online!

2. Print the input

```
input(input())#()::==''""%%Hello, Permatos!cceelxx

```

Try it online!

3. Print "Hello, Permutations!"

```
input("Hello, Permutations!")#()()::==''%%cceelxxp

```

Try it online!

# Answer
> 1 votes
# Klein 001, 32 bytes

## Quine

```
:?/:2+@Hello,Permutations!?[[> "

```

Try it online!

## Cat

```
@:?/:2+Hello,Permutations!?[[> "

```

Try it online!

## Hello, Permutations!

```
"Hello, Permutations!>+?:?:[[@2/

```

Try it online!

# Answer
> 1 votes
# Excel, 136 bytes

## Quine

```
=LEFT(LET(e,CHAR(34),t,"=LEFT(LET(e,CHAR(34),t,!,SUBSTITUTE(t,CHAR(33),e&t&e)),136)022 aillmnoorPusN",SUBSTITUTE(t,CHAR(33),e&t&e)),136)

```

## Cat

```
=LEFT(H2&"e,CeAR(34),t,T=LEFT(LET(e,CHAR(34),t,!,SUBSTITUTE(t,C1AR(33),e&t&e)),136)036 aillmnoorPus)t,SUBSTITUTE(t,CHAR(33),e&",LEN(H2))

```

## Hello, Permutations!

```
=LEFT("Hello, Permutations!FT(LET(e,CHAR(34),t,2,SUBSTITUTE(t,CHAR(33),e&&&)),136)LET(e,CAR(34)t,=LEN,SUBSTITUTE(t,CHAR(33),e&))136",20)

```

# Answer
> 1 votes
# Vyxal `D`, 33 bytes

## Quine

```
`q\`:Ė\`+#Hello, Permutations!`:Ė

```

Try it Online!

```
`q\`:Ė\`+                     `:Ė # Standard eval quine
         #Hello, Permutations!    # Ignored but quined string

```

## Hello, Permutations!

```
`Hello, Permutations!`#+:Ė`q\`:Ė\

```

Try it Online!

```
`Hello, Permutations!`            # String
                      #+:Ė`q\`:Ė\ # Ignored

```

## Cat

```
#`Hello, Permutations!`+:Ė`q\`:Ė\

```

Try it Online!

The entire program is a NOP that abuses implicit cat.

# Answer
> 1 votes
# Perl 5 \+ `-p0513`, 45 bytes

## Quine

Pretty standard quine composition with an additional payload of chars needed for the `Hello, Permutations!`.

```
$_=q{$_="\$_=q{$_};eval",!HPimnooqrsttu};eval
```

Try it online!

## Cat

All the code is encased in a string evaluated in void context.

```
q{$_=$_="\$_=q{$_};eval",!HPimnooqrsttu;eval}
```

Try it online!

## Hello, Permutations!

Sets `$_` to the string `Hello,$"Permutations!` where `$"` defaults to space.

```
$_=qq{Hello,$"Permutations!};q{"$$;==\___avv}
```

Try it online!

I've experimented quite a lot with this before posting, and I'm sure there's a way to reduce this more, but I can't see it yet... I suspect changing the Quine to something different is the key!

---
Tags: code-golf, quine, source-layout
---


# Question
Title: ASCII art uncompression from a base-n number
This is inspired by an 05AB1E answer by Magic Octupus Urn.

Given two arguments, a positive integer and a string/list of characters:

1. Translate the number to base-n, where n is the length of the string.
2. For each character, replace every appearance of the index of that character in the base-n number with that character.
3. Print or return the new string.

### Examples:

```
Input:
2740, ["|","_"]
2740 -> 101010110100 in base 2
     -> Replace 0s with "|" and 1s with "_"
Output: _|_|_|__|_||

Input:
698911, ["c","h","a","o"]
698911 ->  2222220133 in base 4
       ->  Replace 0s with "c", 1s with "h", 2s with "a", and 3s with "o"
Output -> "aaaaaachoo"

Input:
1928149325670647244912100789213626616560861130859431492905908574660758972167966, [" ","\n","|","_","-"]
Output:
    __   __
   |  |_|  |
___|       |___
-   -   -   -
 - - - - - - -
- - - - - - - -
_______________

Input: 3446503265645381015412, [':', '\n', '.', '_', '=', ' ', ')', '(', ',']
Output:
_===_
(.,.)
( : )
( : )

```

Rules:

* IO is flexible.
    + You can take the number in any base, as long as it is consistent between inputs
    + The list of characters has to be 0-indexed though, where 0 is the first character and n-1 is the last
* Possible characters can be any printable ASCII, along with whitespace such as tabs and newlines
* The given list of characters will have a length in the range `2-10` inclusive. That is, the smallest base is binary and the largest is decimal (*no pesky letters here*)
* Standard loopholes are forbidden
* Feel free to answer even if your language can't handle the larger test cases.

As this is , the shortest code for each language wins. (*I know all you golfing languages have one byte built-ins ready to go* ;)

# Answer
# 05AB1E, ~~7~~ 6 bytes

```
gв¹sèJ

```

Since it was inspired by an 05AB1E answer, an answer given in 05AB1E seems fitting. :)

-1 byte thanks to *@Emigna* by removing the foreach and doing this implicitly.

Try it online or verify all test cases.

**Explanation:**

```
g         # `l`: Take the length of the first (string) input
 в        # And then take the second input in base `l`
          # For each digit `y` of this base-converted number:
  ¹sè     #  Push the `y`'th character of the first input
     J    # Join everything together (and output implicitly)

```
> 8 votes

# Answer
# Python 3, 49 bytes

Cannot comment yet, so I post the Python 2 answer adapted to Python 3.5.

```
f=lambda n,s:n and f(n//len(s),s)+s[n%len(s)]or''

```
> 7 votes

# Answer
# Java 8, ~~72~~ 50 bytes

```
a->n->n.toString(a.length).chars().map(c->a[c-48])

```

-22 bytes thanks to *@OlivierGrégoire* by returning an `IntStream` instead of printing directly.

Try it online.

**Explanation:**

```
a->n->                  // Method with char-array and BigInteger parameters
  n.toString(a.length)  //  Convert the input-number to Base `amount_of_characters`
   .chars()             //  Loop over it's digits (as characters)
   .map(c->a[c          //   Convert each character to the `i`'th character of the input
              -48])     //   by first converting the digit-character to index-integer `i`

```
> 6 votes

# Answer
# Japt, 2 bytes

Can take the second input as an array or a string. Fails the last 2 test cases as the numbers exceed JavaScript's max integer. Replace `s` with `ì` to output an array of characters instead.

```
sV

```

Try it
> 5 votes

# Answer
# Haskell, ~~40~~ 39 bytes

```
0!_=[]
n!l=cycle l!!n:div n(length l)!l

```

Try it online!

As Haskell's `Int` type is limited to `9223372036854775807`, this fails for larger numbers.

-1 byte thanks to Laikoni.

## Ungolfed

```
(!) :: Int -> [Char] -> [Char]

0 ! _ = []  -- If the number is 0, we reached the end. Base case: empty string
n ! l =
  let newN = (n `div` length l) in   -- divide n by the base
    cycle l!!n                       -- return the char encoded by the LSD ...
    : newN!l                         -- ... prepended to the rest of the output (computed recursively)

```

Try it online!
> 5 votes

# Answer
# MATL, 2 bytes

```
YA

```

Try it online!

Inputs are a number and a string.

Fails for numbers exceeding `2^53`, because of floating-point precision.

### Explanation

What do `YA` know, a builtin (base conversion with specified target symbols).
> 4 votes

# Answer
# JavaScript (ES6), 48 bytes

Takes input in currying syntax `(c)(n)`, where **c** is a list of characters and **n** is an integer.

Safe only for **n \< 253**.

```
c=>n=>n.toString(c.length).replace(/./g,i=>c[i])

```

Try it online!

---

# JavaScript (ES6), 99 bytes

### *With support for big integers*

Takes input in currying syntax `(c)(a)`, where **c** is a list of characters and **a** is a list of decimal digits (as integers).

```
c=>g=(a,p=0,b=c.length,r=0)=>1/a[p]?g(a.map((d,i)=>(r=d+r*10,d=r/b|0,r%=b,d|i-p||p++,d)),p)+c[r]:''

```

Try it online!
> 4 votes

# Answer
# x86 32-bit machine code (32-bit integers): 17 bytes.

(also see other versions below, including 16 bytes for 32-bit or 64-bit, with a DF=1 calling convention.)

Caller passes args in registers, including a pointer to the *end* of an output buffer (like my C answer; see it for justification and explanation of the algorithm.) glibc's internal `_itoa` does this, so it's not just contrived for code-golf. The arg-passing registers are close to x86-64 System V, except we have an arg in EAX instead of EDX.

On return, EDI points to the first byte of a 0-terminated C string in the output buffer. The usual return-value register is EAX/RAX, but in assembly language you can use whatever calling convention is convenient for a function. (`xchg eax,edi` at the end would add 1 byte).

The caller can calculate an explicit length if it wants, from `buffer_end - edi`. But I don't think we can justify omitting the terminator unless the function actually returns both start+end pointers or pointer+length. That would save 3 bytes in this version, but I don't think it's justifiable.

* EAX = n = number to decode. (For `idiv`. The other args aren't implicit operands.)
* EDI = end of output buffer (64-bit version still uses `dec edi`, so must be in the low 4GiB)
* ESI/RSI = lookup table, aka LUT. not clobbered.
* ECX = length of table = base. not clobbered.

`nasm -felf32 ascii-compress-base.asm -l /dev/stdout | cut -b -30,$((30+10))-` (Hand edited to shrink comments, line numbering is weird.)

```
   32-bit: 17 bytes        ;  64-bit: 18 bytes
                           ; same source assembles as 32 or 64-bit
 3                         %ifidn __OUTPUT_FORMAT__, elf32
 5                         %define rdi edi
 6   address               %define rsi esi
11          machine        %endif
14          code           %define DEF(funcname) funcname: global funcname
16          bytes
22                         ;;; returns: pointer in RDI to the start of a 0-terminated string
24                         ;;; clobbers:; EDX (tmp remainder)
25                         DEF(ascii_compress_nostring)
27 00000000 C60700             mov     BYTE [rdi], 0
28                         .loop:                    ; do{
29 00000003 99                 cdq                    ; 1 byte shorter than   xor edx,edx / div
30 00000004 F7F9               idiv    ecx            ; edx=n%B   eax=n/B
31
32 00000006 8A1416             mov     dl, [rsi + rdx]   ; dl = LUT[n%B]
33 00000009 4F                 dec     edi               ; --output  ; 2B in x86-64
34 0000000A 8817               mov     [rdi], dl         ; *output = dl
35
36 0000000C 85C0               test    eax,eax           ; div/idiv don't write flags in practice, and the manual says they're undefined.
37 0000000E 75F3               jnz     .loop         ; }while(n);
38
39 00000010 C3                 ret
           0x11 bytes = 17
40 00000011 11             .size: db $ - .start

```

It's surprising that the simplest version with basically no speed/size tradeoffs is the smallest, but `std`/`cld` cost 2 bytes to use `stosb` to go in descending order and still follow the common DF=0 calling convention. (And STOS decrements *after* storing, leaving the pointer pointing one byte too low on loop exit, costing us extra bytes to work around.)

# Versions:

I came up with 4 significantly different implementation tricks (using simple `mov` load/store (above), using `lea`/`movsb` (neat but not optimal), using `xchg`/`xlatb`/`stosb`/`xchg`, and one that enters the loop with an overlapping-instruction hack. See code below). The last needs a trailing `0` in the lookup table to copy as the output string terminator, so I'm counting that as +1 byte. Depending on 32/64-bit (1-byte `inc` or not), and whether we can assume the caller sets DF=1 (`stosb` descending) or whatever, different versions are (tied for) shortest.

DF=1 to store in descending order makes it a win to xchg / stosb / xchg, but the caller often won't want that; It feels like offloading work to the caller in a hard-to-justify way. (Unlike custom arg-passing and return-value registers, which typically don't cost an asm caller any extra work.) But in 64-bit code, `cld` / `scasb` works as `inc rdi`, avoiding truncating the output pointer to 32-bit, so it's sometimes inconvenient to preserve DF=1 in 64-bit-clean functions. . (Pointers to static code/data are 32-bit in x86-64 non-PIE executables on Linux, and always in the Linux x32 ABI, so an x86-64 version using 32-bit pointers is usable in some cases.) Anyway, this interaction makes it interesting to look at different combinations of requirements.

* **IA32 with a DF=0 on entry/exit calling convention: 17B (`nostring`)**.
* IA32: **16B (with a DF=1 convention: `stosb_edx_arg` or `skew`)**; or with incoming DF=dontcare, leaving it set: **16+1B `stosb_decode_overlap`** or 17B `stosb_edx_arg`
* **x86-64 with 64-bit pointers, and a DF=0 on entry/exit calling convention: 17+1 bytes (`stosb_decode_overlap`)**, 18B (`stosb_edx_arg` or `skew`)
* x86-64 with 64-bit pointers, other DF handling: **16B (DF=1 `skew`)**, 17B (`nostring` with DF=1, using `scasb` instead of `dec`). 18B (`stosb_edx_arg` preserving DF=1 with 3-byte `inc rdi`).

Or if we allow returning a pointer to 1 byte before the string, **15B** (`stosb_edx_arg` without the `inc` at the end). **All set to call again and expand another string into the buffer with different base / table...** But that would make more sense if we didn't store a terminating `0` either, and you might put the function body inside a loop so that's really a separate problem.
* x86-64 with 32-bit output pointer, DF=0 calling convention: no improvement over 64-bit output pointer, but 18B (`nostring`) ties now.
* x86-64 with 32-bit output pointer: no improvement over the best 64-bit pointer versions, so 16B (DF=1 `skew`). Or to set DF=1 and leave it, 17B for `skew` with `std` but not `cld`. Or 17+1B for `stosb_decode_overlap` with `inc edi` at the end instead of `cld`/`scasb`.

---

# With a DF=1 calling convention: 16 bytes (IA32 or x86-64)

Requires DF=1 on input, leaves it set. Barely plausible, at least on a per-function basis. Does the same thing as the above version, but with xchg to get the remainder in/out of AL before/after XLATB (table lookup with R/EBX as base) and STOSB (`*output-- = al`).

With a normal DF=0 on entry/exit convention, **the `std` / `cld`/`scasb` version is 18 bytes for 32 and 64-bit code, and is 64-bit clean** (works with a 64-bit output pointer).

Note that the input args are in different registers, including RBX for the table (for `xlatb`). Also note that this loop starts by storing AL, and ends with the last char not stored yet (hence the `mov` at the end). So the loop is "skewed" relative to the others, hence the name.

```
                            ;DF=1 version.  Uncomment std/cld for DF=0
                            ;32-bit and 64-bit: 16B
157                         DEF(ascii_compress_skew)
158                         ;;; inputs
159                             ;; O in RDI = end of output buffer
160                             ;; I in RBX = lookup table  for xlatb
161                             ;; n in EDX = number to decode
162                             ;; B in ECX = length of table = modulus
163                         ;;; returns: pointer in RDI to the start of a 0-terminated string
164                         ;;; clobbers:; EDX=0, EAX=last char
165                         .start:
166                         ;    std
167 00000060 31C0               xor    eax,eax
168                         .loop:                    ; do{
169 00000062 AA                 stosb
170 00000063 92                 xchg    eax, edx
171
172 00000064 99                 cdq                    ; 1 byte shorter than   xor edx,edx / div
173 00000065 F7F9               idiv    ecx            ; edx=n%B   eax=n/B
174
175 00000067 92                 xchg    eax, edx       ; eax=n%B   edx=n/B
176 00000068 D7                 xlatb                  ; al = byte [rbx + al]
177
178 00000069 85D2               test    edx,edx
179 0000006B 75F5               jnz     .loop         ; }while(n = n/B);
180
181 0000006D 8807               mov     [rdi], al     ; stosb would move RDI away
182                         ;    cld
183 0000006F C3                 ret

184 00000070 10             .size: db $ - .start

```

A similar non-skewed version overshoots EDI/RDI and then fixes it up.

```
                            ; 32-bit DF=1: 16B    64-bit: 17B (or 18B for DF=0)
70                         DEF(ascii_compress_stosb_edx_arg)  ; x86-64 SysV arg passing, but returns in RDI
71                             ;; O in RDI = end of output buffer
72                             ;; I in RBX = lookup table  for xlatb
73                             ;; n in EDX = number to decode
74                             ;; B in ECX = length of table
75                         ;;; clobbers EAX,EDX, preserves DF
76                             ; 32-bit mode: a DF=1 convention would save 2B (use inc edi instead of cld/scasb)
77                             ; 32-bit mode: call-clobbered DF would save 1B (still need STD, but INC EDI saves 1)
79                         .start:
80 00000040 31C0               xor     eax,eax
81                         ;    std
82 00000042 AA                 stosb
83                         .loop:
84 00000043 92                 xchg    eax, edx
85 00000044 99                 cdq
86 00000045 F7F9               idiv    ecx            ; edx=n%B   eax=n/B
87
88 00000047 92                 xchg    eax, edx       ; eax=n%B   edx=n/B
89 00000048 D7                 xlatb                  ; al = byte [rbx + al]
90 00000049 AA                 stosb                  ; *output-- = al
91
92 0000004A 85D2               test    edx,edx
93 0000004C 75F5               jnz     .loop
94
95 0000004E 47                 inc    edi
96                             ;; cld
97                             ;; scasb          ; rdi++
98 0000004F C3                 ret
99 00000050 10             .size: db $ - .start
    16 bytes for the 32-bit DF=1 version

```

I tried an alternate version of this with `lea esi, [rbx+rdx]` / `movsb` as the inner loop body. (RSI is reset every iteration, but RDI decrements). But it can't use xor-zero / stos for the terminator, so it's 1 byte larger. (And it's not 64-bit clean for the lookup table without a REX prefix on the LEA.)

---

# LUT with explicit length *and* a 0 terminator: 16+1 bytes (32-bit)

This version sets DF=1 and leaves it that way. I'm counting the extra LUT byte required as part of the total byte count.

The cool trick here is **having the same bytes decode two different ways**. We fall into the middle of the loop with remainder = base and quotient= input number, and copy the 0 terminator into place.

On the first time through the function, the first 3 bytes of the loop are consumed as the high bytes of a disp32 for an LEA. That LEA copies the base (modulus) to EDX, `idiv` produces the remainder for later iterations.

The 2nd byte of `idiv ebp` is `FD`, which is the opcode for the `std` instruction that this function needs to work. (This was a lucky discovery. I had been looking at this with `div` earlier, which distinguishes itself from `idiv` using the `/r` bits in ModRM. The 2nd byte of `div epb` decodes as `cmc`, which is harmless but not helpful. But with `idiv ebp` can we actually remove the `std` from the top of the function.)

Note the input registers are difference once again: EBP for the base.

```
103                         DEF(ascii_compress_stosb_decode_overlap)
104                         ;;; inputs
105                             ;; n in EAX = number to decode
106                             ;; O in RDI = end of output buffer
107                             ;; I in RBX = lookup table, 0-terminated.  (first iter copies LUT[base] as output terminator)
108                             ;; B in EBP = base = length of table
109                         ;;; returns: pointer in RDI to the start of a 0-terminated string
110                         ;;; clobbers: EDX (=0), EAX,  DF
111                             ;; Or a DF=1 convention allows idiv ecx (STC).  Or we could put xchg after stos and not run IDIV's modRM
112                         .start:
117                             ;2nd byte of div ebx = repz.  edx=repnz.
118                             ;            div ebp = cmc.   ecx=int1 = icebp (hardware-debug trap)
119                             ;2nd byte of idiv ebp = std = 0xfd.  ecx=stc
125
126                             ;lea    edx, [dword 0 + ebp]
127 00000040 8D9500             db  0x8d, 0x95, 0   ; opcode, modrm, 0 for lea edx, [rbp+disp32].  low byte = 0 so DL = BPL+0 = base
128                             ; skips xchg, cdq, and idiv.
129                             ; decode starts with the 2nd byte of idiv ebp, which decodes as the STD we need
130                         .loop:
131 00000043 92                 xchg    eax, edx
132 00000044 99                 cdq
133 00000045 F7FD               idiv    ebp            ; edx=n%B   eax=n/B;
134                             ;; on loop entry, 2nd byte of idiv ebp runs as STD.  n in EAX, like after idiv.  base in edx (fake remainder)
135
136 00000047 92                 xchg    eax, edx       ; eax=n%B   edx=n/B
137 00000048 D7                 xlatb                  ; al = byte [rbx + al]
138                         .do_stos:
139 00000049 AA                 stosb                  ; *output-- = al
140
141 0000004A 85D2               test    edx,edx
142 0000004C 75F5               jnz     .loop
143
144                         %ifidn __OUTPUT_FORMAT__, elf32
145 0000004E 47                 inc     edi         ; saves a byte in 32-bit.  Makes DF call-clobbered instead of normal DF=0
146                         %else
147                             cld
148                             scasb          ; rdi++
149                         %endif
150
151 0000004F C3                 ret
152 00000050 10             .size: db $ - .start
153 00000051 01                     db 1   ; +1 because we require an extra LUT byte
       # 16+1 bytes for a 32-bit version.
       # 17+1 bytes for a 64-bit version that ends with DF=0

```

This overlapping decode trick can also be used with `cmp eax, imm32`: it only takes 1 byte to effectively jump forward 4 bytes, only clobbering flags. (This is terrible for performance on CPUs that mark instruction boundaries in L1i cache, BTW.)

But here, we're using 3 bytes to copy a register and jump into the loop. That would normally take 2+2 (mov + jmp), and would let us jump into the loop right before the STOS instead of before the XLATB. But then we'd need a separate STD, and it wouldn't be very interesting.

Try it online! (with a `_start` caller that uses `sys_write` on the result)

It's best for debugging to run it under `strace`, or hexdump the output, so you can see verify that there's a `\0` terminator in the right place and so on. But you can see this actually work, and produce `AAAAAACHOO` for an input of

```
num  equ 698911
table:  db "CHAO"
%endif
    tablen equ $ - table
    db 0  ; "terminator" needed by ascii_compress_stosb_decode_overlap

```

(Actually `xxAAAAAACHOO\0x\0\0...`, because we're dumping from 2 bytes earlier in the buffer out to a fixed length. So we can see that the function wrote the bytes it was supposed to and *didn't* step on any bytes it shouldn't have. The start-pointer passed to the function was the 2nd-last `x` character, which was followed by zeros.)
> 4 votes

# Answer
# Jelly, 4 bytes

```
ṙ1ṃ@

```

Try it online!

is literally a built-in for this. The other three bytes account for Jelly's one-based indexing.
> 3 votes

# Answer
# Python 2, ~~49~~ 48 bytes

-1 byte thanks to Jo King

```
f=lambda n,s:n and f(n/len(s),s)+s[n%len(s)]or''

```

Try it online!

### Alternative version (won't finish for large numbers), ~~45~~ 43 bytes

-2 bytes thanks to Jo King

```
f=lambda n,s:s*n and f(n/len(s),s)+(s*n)[n]

```

Try it online!
> 3 votes

# Answer
# Charcoal, ~~3~~ 1 bytes

```
~~θη~~
```

Try it online! Link is to verbose version of code. Edit: Saved 2 bytes thanks to @ASCII-only. Previous version before the builtin was added, 8 bytes:

```
⭆↨θＬη§ηι

```

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

```
    η       Second input
   Ｌ        Length
  θ         First input
 ↨          Base convert to array
⭆           Map over values and join
      η     Second input
       ι    Current value
     §      Index into list
            Implicitly print result

```
> 3 votes

# Answer
## C++, ~~150~~ 144 bytes, `uint64` input

-6 bytes thanks to Zacharý

```
#include<string>
using s=std::string;s u(uint64_t n,s b){s t;for(;n;n/=b.size())t=std::to_string(n%b.size())+t;for(auto&a:t)a=b[a-48];return t;}

```

Using a variable to store the size would increase the bytecount by 1

To call the function :

```
u(2740, "|_")

```

First the number, second is the string ( char array )

Test cases :

```
std::cout << u(2740, "|_") << '\n' << u(698911, "chao") << '\n';
return 0;

```
> 3 votes

# Answer
# , 112 bytes

```
import std.conv;C u(C,I)(I n,C b){C t;for(I l=b.length;n;n/=l)t=to!C(n%l)~t;foreach(ref c;t)c=b[c-48];return t;}

```

Try it online!

This is a port of HatsuPointerKun's C++ answer

The calling style is `u(ulong(n), to!(char[])(b))`, where `n` and `b` are the left and right arguments

## D specific stuff

Sadly, we need to import `std.conv` to do any type conversions above **very** basic type conversion.

Using the golfy template system, and giving the function the required types (which is why calling it is not just `u(n,b)`), we can shorten occurrences of `char[]` and `ulong` to `1` byte each, when inside f the function.

D initializes our types for us, so `C t;` is short for `C t=cast(char[])([])`

`to!C` converts the integer `n%l` to a character array (using codepoints), and `~` is concatenation

`foreach(ref c;t)` is like C++'s `for(... : ...)` loop, but a little longer. `ref` is like `&`, it treats `c` as copied-by-reference (i.e., we can modify `t`). Luckily, D infers the type of `c` without *any* keyword denoting type.
> 3 votes

# Answer
# APL (Dyalog Unicode), ~~14 13~~ 12 bytes

```
⊢⌷⍨∘⊂⊥⍣¯1⍨∘≢

```

Try it online!

Infix tacit function; can't handle the largest test case because of floating point representation.

Saved ~~1~~ 2 bytes thanks to @Adám!

~~13 bytes added for the headers: `⎕IO←0`: **I**ndex **O**rigin = 0 and `⎕FR←1287`: **F**loat **R**epresentation = 128 bits.~~ (I'd forgotten that this doesn't apply.)

### How?

```
⊢⌷⍨∘⊂⊥⍣¯1⍨∘≢   ⍝ Tacit function, infix.
           ≢   ⍝ Tally (number of elements in) the right argument.
         ⍨∘    ⍝ Then swap the arguments of
     ⊥⍣¯1      ⍝ Base conversion (to base ≢<r_arg>)
    ⊂          ⍝ Enclose (convert to an array)
  ⍨∘           ⍝ Then swap the arguments of
 ⌷             ⍝ Index
⊢              ⍝ (Into) the right argument.

```
> 2 votes

# Answer
# Pyth, ~~9~~ ~~8~~ 7 bytes

```
s@LQjEl

```

Saved a byte thanks to hakr14 and another thanks to Mr. Xcoder.
Try it here

### Explanation

```
s@LQjEl
    jElQ      Convert the second input (the number) to the appropriate base.
 @LQ          Look up each digit in the list of strings.
s             Add them all together.

```
> 2 votes

# Answer
# Twig, 66 bytes

Created a `macro` that must be `import`ed into a template.

```
{%macro d(n,c)%}{%for N in n|split%}{{c[N]}}{%endfor%}{%endmacro%}

```

---

## Values expected:

For the first arguments (`n`):

* number
* string

For the second argument (`c`):

* Array of numbers
* Array of strings

---

## How to use:

* Create a `.twig` file
* Add `{% import 'file.twig' as uncompress %}`
* Call the macro `uncompress.d()`

## Ungolfed (non-functional):

```
{% macro d(numbers, chars) %}
    {% for number in numbers|split %}
        {{ chars[number] }}
    {% endfor %}
{% endmacro %}

```

---

---

You can test this code on: https://twigfiddle.com/54a0i9
> 2 votes

# Answer
# C89, limited-range signed `int n`, ~~64~~ 53 bytes

* changelog: take a `char **out` and modify it, instead of taking and returning a `char *`

Takes the number as an `int`, the lookup table as an array + length.
Output is written into a `char *outbuf`. Caller passes (by reference) a pointer to the end of the buffer. Function modifies that pointer to point to the first byte of the string on return.

```
g(n,I,B,O)char*I,**O;{for(**O=0;n;n/=B)*--*O=I[n%B];}

```

This is valid C89, and works correctly even with optimization enabled. i.e. doesn't depend on gcc `-O0` behaviour when falling off the end of a non-void function or have any other UB.

Passing a pointer to the end of a buffer is normal for an optimized int-\>string function, such as glibc's internal `_itoa`. See this answer for a detailed explanation of breaking an integer into digits with a div / mod loop like we're doing here, in C as well as x86-64 asm. If the base is a power of 2, you can shift/mask to extract digits MSD first, but otherwise the only good option is least-significant-digit first (with modulo).

Try it online!. Ungolfed version:

```
/* int n = the number
 * int B = size of I = base
 * char I[] = input table
 * char **O = input/output arg passed by ref:
 *    on entry: pointer to the last byte of output buffer.
 *    on exit:  pointer to the first byte of the 0-terminated string in output buffer
 */
void ungolfed_g(n,I,B,O)char*I,**O;
{
    char *outpos = *O;     /* Golfed version uses *O everywhere we use outpos */
    *outpos = 0;           /* terminate the output string */
    for(;n;n/=B)
        *--outpos = I[n%B]; /* produce 1 char at a time, decrementing the output pointer */
    *O = outpos;
}

```

In this explicit-length version, the input is a `char table[]` which does *not* need a terminating 0 byte, because we never treat it as a string. It could be an `int table[]` for all we care. C doesn't have containers that know their own length, so pointer+length is the normal way to pass an array with a size. So we choose that instead of needing to `strlen`.

The maximum buffer size is approximately `sizeof(int)*CHAR_BIT + 1`, so it's small and compile-time constant. (We use this much space with base=2 and all the bits set to 1.) e.g. 33 bytes for 32 bit integers, including the `0` terminator.

---

# C89, signed `int`, table as an implicit-length C string, 65 bytes

```
B;f(n,I,O)char*I,**O;{B=strlen(I);for(**O=0;n;n/=B)*--*O=I[n%B];}

```

This is the same thing but the input is an implicit-length string so we have to find the length ourselves.
> 2 votes

# Answer
# Bash + core utilities, 49 bytes

```
dc -e`echo -en $2|wc -c`o$1p|tr -dc 0-9|tr 0-9 $2

```

Try it online!

# Comments/explanation

This takes command-line arguments as input (the number in base 10, then a single string with the list of characters) and outputs to stdout. Special characters like space, newline, etc may be entered in octal notation (for example, `\040` for a space), or `\n` for a newline, `\t` for tab, or any other escape sequence that `echo -e` and `tr` interpret identically.

A lot of the bytes here are to handle special characters and larger test cases. If I only have to handle non-terrible characters and the numbers are small (for example, the first test case), the following 24 bytes will do it:

```
dc -e${#2}o$1p|tr 0-9 $2

```

This uses parameter expansion `${#2}` to get the number of characters in the string, builds a dc program to do the base conversion, and then sends the converted number through `tr`.

This won't handle newlines or spaces or tabs, though, so to deal with escape sequences without affecting the base, I do a character count `wc -c` after interpreting the escapes with `echo -en`. This expands the program to 38 bytes:

```
dc -e`echo -en $2|wc -c`o$1p|tr 0-9 $2

```

Unfortunately, dc has an annoying "feature" where if it's outputting a large number, it will line wrap it with a slash+newline sequence, so the larger test cases have this extra output. To remove it, I pipe dc's output through `tr -dc 0-9` to remove non-numeric characters. And there we are.
> 2 votes

# Answer
# Attache, 17 bytes

```
{_[_2&ToBase!#_]}

```

Try it online!

## Explanation

```
{_[_2&ToBase!#_]}
{               }  ?? anonymous lambda; input: _ = dictionary, _2 = encoded
   _2&ToBase       ?? convert _2 to base
            !#_    ?? ... Size[_]
 _[            ]   ?? and take those members from the dictionary

```
> 2 votes

# Answer
# Vyxal, 1 byte

```
τ

```

Try it Online!

# 05AB1E, 3 bytes

```
ÅвJ

```

Try it online!
> 2 votes

# Answer
# Stax, ~~6~~ 5 bytes

```
n%|E@

```

Run and debug it

Explanation:

```
n%|E@ Full program, implicit input in order list, number
n%    Copy the list to the top and get its length
  |E  Convert the number to that base
    @ Map: index

```
> 1 votes

# Answer
# Canvas, 7 bytes

```
Ｌ┬｛╵⁸＠ｐ

```

Try it here!

Straight forward implementation:

```
L┬{╵⁸@p
L      get the length of the input (popping the item)
 ┬     base decode the other input
  {    for each number there
   ╵     increment
    ⁸@   in the 1st input get that numbered item
      p  and output that

```

The input character set can be a string too as long as it doesn't contain a newline, because Canvas doesn't have a newline character & automatically converts it to a 2D object.
> 1 votes

# Answer
# SOGL V0.12, 10 bytes

```
l;A─{IaWp}

```

Try it Here!

Pretty long, considering the idea is pretty much implemented in the language: here, entering

```
¶    __   __    ¶   |  |_|  |   ¶___|       |___¶-   -   -   -  ¶ - - - - - - - ¶- - - - - - - -¶_______________¶

```

gives out a compressed string using this method.
> 1 votes

# Answer
# Ruby, 31 bytes

```
->n,b{n.to_s(b.size).tr"0-9",b}

```

Try it online!
> 1 votes

# Answer
# Stax, 2 bytes

```
:B

```

Run and debug it

`:B` is an instruction in stax that does this. It would normally operate on a "string"\* instead of an array of "strings". In the end, this means that the output is an array of single character arrays. But output implicitly flattens anyway.

\*Stax doesn't actually have a string type. Text is represented by integer arrays of codepoints.
> 1 votes

# Answer
# , 12 bytes

```
]{~#@]#.inv[

```

## How?

```
      #.inv    convert
           [   the left argument (the number)
   #@]         to base the length of the right argument (the list of characters)
  {~           and use the digits as indices to
]              the list of characters

```

Try it online!
> 1 votes

# Answer
# Powershell, ~~88~~ 87 bytes

```
$n,$a=$args;$d=0;for(;$n-ne0){$n=[bigint]::DivRem($n,$a.count,[ref]$d);$s=$a[$d]+$s};$s

```

implicit using a .NET class BigInteger.

Test script:

```
$f = {
    $n,$a=$args;$d=0;for(;$n-ne0){$n=[bigint]::DivRem($n,$a.count,[ref]$d);$s=$a[$d]+$s};$s
}

@(
    @{
        n        = [bigint]::Parse("2740")
        ascii    = @("|", "_")
        expected = "_|_|_|__|_||"
    }
    @{
        n        = [bigint]::Parse("698911")
        ascii    = @("c", "h", "a", "o")
        expected = "aaaaaachoo"
    }
    @{
        n        = [bigint]::Parse("1928149325670647244912100789213626616560861130859431492905908574660758972167966")
        ascii    = @(" ", "`r`n", "|", "_", "-")
        expected = @"

    __   __
   |  |_|  |
___|       |___
-   -   -   -
- - - - - - -
- - - - - - - -
_______________

"@
    }
    @{
        n        = [bigint]::Parse("3446503265645381015412")
        ascii    = @(":", "`r`n", ".", "_", "=", " ", ")", "(", ",")
        expected = @"
_===_
(.,.)
( : )
( : )
"@
    }
) | % {
    $r = &$f $_.n $_.ascii
    $r -eq $_.expected
    $r
}

```

output:

```
True
_|_|_|__|_||
True
aaaaaachoo
True

    __   __
   |  |_|  |
___|       |___
-   -   -   -
 - - - - - - -
- - - - - - - -
_______________

True
_===_
(.,.)
( : )
( : )

```

## Explanation

```
$n,$a=$args                # let $n is first argument (expected [bigint])
                           # let $a is second argument (expected char array)
$d=0                       # define variable $d to use as reference value
for(;$n-ne0){              # while bigint $n not equals 0
    $n=[bigint]::DivRem($n,$a.count,[ref]$d);
                           # .NET function DivRem returns the quotient of the division
                           # and place remainder to $d
                           # https://msdn.microsoft.com/en-us/library/system.numerics.biginteger.divrem
    $s=$a[$d]+$s           # add a char to the string
}
$s                         # return string

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 49 bytes

```
Outer[Part,{#},#2~IntegerDigits~Tr[1^#]+1,1]<>""&

```

Try it online!
> 1 votes

# Answer
# C (gcc), 110 bytes

```
char s[99],S[99];i;f(x,_)char*_;{i=strlen(_);*s=*S=0;while(x)sprintf(S,"%c%s",_[x%i],s),strcpy(s,S),x/=i;x=s;}

```

Try it online!

Description:

```
char s[99],S[99];           // Two strings, s and S (capacity 99)
i;                          // A variable to store the length of the string
f(x,_)char*_;{              // f takes x and string _
    i=strlen(_);            // set i to the length of _
    *s=*S=0;                // empty s and S
    while(x)                // loop until x is zero
        sprintf(S,"%c%s",   // print into S a character, then a string
                _[x%i],s),  // character is the x%i'th character of _, the string is s
        strcpy(s,S),        // copy S into s
        x/=i;               // divide x by the length of the string (and loop)
    x=s;}                   // return the string in s

```
> 1 votes

# Answer
# CJam, 11 bytes

```
liq_,@\b\f=

```

Try it online! Takes input as the number, then a newline, then the characters in the ASCII art.

## Explanation

```
li           e# Read the first line and convert it to an integer
  q_,        e# Read the rest of the input and push its length n
     @\b     e# Convert the number to its base-n equivalent, as an array of numbers
        \f=  e# Map over the array, taking each element's index from the string

```
> 1 votes

# Answer
# JavaScript, 39 bytes

Port of Rod's Python solution.

```
s=>g=n=>n?g(n/(l=s.length)|0)+s[n%l]:""

```

Try it online
> 1 votes

# Answer
# SimpleTemplate, 86 bytes

Wow, this was a huge challenge!

This was made hard due to the lack of direct access to specific indexes when the index is a variable.
A bug also made it longer, requiring to store the values inside a variable.

```
{@setA argv.1}{@eachargv.0}{@setC C,"{@echoA.",_,"}"}{@calljoin intoC"",C}{@/}{@evalC}

```

---

## Values expected:

The first argument (`argv.0`) can be:

* An integer
* A string with numbers
* An array of integers

The second argument (`argv.1`) can be:

* A string
* An array

## How this works?

It works this way:

* Cycles through the number/string passed as the first argument
* Sets the variable `C` to be an array containing:
    + The previous value `C`
    + The string `"{@echoA."`
    + The value of the loop
    + The string `"}"`
* Joins everything together (using PHP's `join` function)
This results in, for example, `C` containing `"{@echoA.0}{@echoA.1}..."`
* Evaluates the result of `C`

## Ungolfed:

```
{@set args argv.1}
{@each argv.0 as number}
    {@set code code, "{@echo args.", number , "}"}
    {@call join into code "", code}
{@/}
{@eval code}

```

---

You can try this code on: https://ideone.com/NEKl2q

---

### Optimal result

If there weren't bugs, this would be the best result, accounting for the limitations (77 bytes):

```
{@eachargv.0}{@setC C,"{@echoargv.1.",_,"}"}{@calljoin intoC"",C}{@/}{@evalC}

```
> 1 votes

# Answer
# Perl 6, 32 bytes

```
{$^a.base($^b).comb>>.&{$b[$_]}}

```

Try it online!

Anonymous code block that take an integer and a list of characters and returns a list of characters.

### Explanation:

```
{                              }  #Anonymous code block
 $^a.base($^b)                    #Convert number to base (len(list))
              .comb               #Convert number to list of characters
                   >>             #Map each character to
                     .&{$b[$_]}   #To the index of that character in the list

```
> 0 votes

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