title: Tips for golfing in 05AB1E

text:
# Question
Title: Tips for golfing in 05AB1E
Do you have any tips for ing in 05AB1E, a golfing language created by Adnan?

Your tips should be at least somewhat specific to 05AB1E.

Please post one tip per answer.

# Answer
Since it wasn't part of the Wiki on 05AB1E's GitHub pages (I think it should), I'm just gonna add it here now that I better understand it myself.

# How to use the dictionary?

05AB1E has the following words.ex dictionary file containing all the words it knows. But how do we access the words in this dictionary? Let's take the word `"testing"` as example:

`"testing"` can be found on row 1453 of the dictionary file. Since the first two lines aren't words, and we need the 0-indexed word, we subtract 3.
So, now we have the index (`1450`), but how to use it?

We open and start a compressed string with . We then look at the second column of the info.txt file. (So  is 00;  is 01; etc.)
In the case of `"testing"` this means `î` (14) and `»` (50).

The compressed String for `"testing"` is therefore: `“î»“` Try it online. As with almost all 05AB1E pieces of code, the trailing  is optional if you don't access the string, so without works as well in this case.

**Some things to note:**

All characters that doesn't have any index in the info.txt file can be used as is. This can be useful for adding an `s` to output a plural instead of singular word or use punctuation like `,.?!` for example.
`ÿ` (string-interpolation) can also be used when you want to insert values from the stack within the string.
NOTE: Every loose character that doesn't have any index in the info.txt file counts as a word for the compression types below.

There are different types of compressed strings you can use:

* `'`: Take a single compressed word as is (no trailing `'` required) - `'î»`: "testing"
* : Takes two compressed words with space delimiter (no trailing  required) - `„î»î»`: "testing testing"
* : Takes three compressed words with space delimiter (no trailing  required) - `…î»î»î»`: "testing testing testing"
* : Take the compressed string with space delimiter - `“î»î»“`: "testing testing"
* : Take the compressed string as is without implicit spaces - `’î»î»’`: "testingtesting"
* : Take the compressed string in title-case with space delimiter - `”î»î»”`: "Testing Testing"
* : Take the compressed string in full uppercase with space delimiter - `‘î»î»‘`: "TESTING TESTING"

Here a useful program to get the compressed string based on a space-delimited input of words:

```
'“? lAð«Ã#¸˜ vyU "€‚ƒ„…†‡ˆ‰Š‹ŒŽ•–—™š›œžŸ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîï" Dâ vy"“ÿ“".V XlQi y?1#] '“,

```

### Try it online.

This program will:

1. Take the input as lowercase, removes any non-alphabetic characters (except for spaces), and then splits the words by spaces (`lAð«Ã#`), or wraps the words in a list if only a single word was inputted (`¸˜`)
2. Loops over each word (`vyU`)
3. Then has an inner loop over each compressed word from the dictionary (`"€...ï"Dâvy`), which it will try to run as 05AB1E program (`"“ÿ“".V`)
4. And if it's equal to the current word it will print it and break the inner loop `XlQiy?1#`

With an input `good bye world` the output would therefore be `“‚¿Þ¡‚ï“`. Try it online.

NOTE: You'd still have to see if the word exist in the dictionary in order for this generator to work, and it will ignore any special characters or plural words. Only the words that are exactly the same in the dictionary will be found.

Here an example where I use `…Ÿ™‚ï!` for the string "hello world!" and `’‚¿Þ¡ ÿ ‚ï!’` for the string "goodbye ÿ world!". Note how the spaces and exclamation mark are used as is, because they don't have indices in the info.txt file. In addition, it uses `ÿ` to insert the "cruel" that was at the top of the stack, which unfortunately wasn't part of the dictionary (but was still compressed using the method at the section below).

# How to compress strings not part of the dictionary?

Although the words.ex dictionary file is pretty big (10,000 words to be exact), it can happen that you need a word which isn't part of it, or a string which is just plain gibberish. So is there a way to compress those as well?
There certainly is, by using `.•`, which is a compressed base-255 alphabet based string. NOTE: This method can only be used for characters in the lowercase alphabet and spaces.

Here is a useful program to convert a word/string to the compressed base-255 alphabet based string:

```
vAyk})> 27β 255B ".•ÿ•"

```

### Try it online..

What this program above does is:

* `vAyk})>`: Take the 1-indexed alphabet indices of the individual letters of the input, with spaces becoming index 0
* `27β`: Convert these indices from base 27 to a single number
* `255B`: Convert this number to Base-255 using 05AB1E's own code page
* `".•ÿ•"`: Places a leading `.•` and trailing  before this compressed string

Here an example answer where *@Kaldo* uses `.•zíΘ•` to compress the word "goose".

# How to compress large integers?

Let's say we want to use a very big number for something, but it can't really be retrieved by pow-calculations. For example, let's say we want to access the large integer `18238098189071058293` for whatever reason.

In this case we can use both a leading and trailing  to compress a number in the format `[1-9][0-9]+`.
The example number above will become `•15Y₁Ò'Θpc•`. Try it online. Again, just like with the compressed dictionary string, the trailing  can optionally be removed.

Optionally, when the integer is small enough so only 2 compressed characters have to be used, we can use `Ž` instead, in which case we won't need a trailing byte to close it and the integer is compressed in 3 bytes instead of 4. For example, the integer `13562` would result in `•rl•`, but because it only uses two characters, it can be `Žrl` instead.

Also, numbers in the range `[101, 355]` can be compressed in 2 bytes using `Ƶ` plus an additional character from 05AB1E's codepage. So for example, `Ƶ–` can be used for the integer `250`. Here an overview of all available numbers. These characters are converted from Base-255 to Base-10, and then 101 is added (since the numbers in the range `[0,100]` are already 1 or 2 bytes).

How are these `15Y₁Ò'Θpc` and `rl` created? Very simple, the number is converted to Base-255 using 05AB1E's own codepage. So you can use the following program to get a compressed number, for which it will then use `Ƶ.`, `Ž..`, or `•...•` depending on the size of the compressed integer:

```
101 355Ÿså i 101-255B"Ƶÿ" ë 255B Dg2Qi "Žÿ" ë "•ÿ•"

```

### Try it online.

Here an example answer where *@Emigna* uses `•3Èñ•` for the integer `246060`.

# How to compress integer lists?

Sometimes you want to compress an entire list of integers instead of a single number. For example, let's say we want the list `[5,94,17,83,4,44,32,19,4,45,83,90,0,14,3,17,17,81]` for whatever reason. In this case, we can use the following instead: `•5O›YJ&p‘ÑÎ!6¯8,•₃в` Try it online.

Here a useful program to generate both this compressed number and the Base we want to convert to:

```
Z>© β 255B ®s"•ÿ•ÿв"

```

### Try it online.

What this program above does is:

* `Z>`: Get the max number + 1 of the input-list (`©`: and store it in the register)
* `β`: Convert the input list from base `max+1` to a single number
* `255B`: Compress this single number (as we did at the section above)
* `®s"•ÿ•ÿв"`: Returns the result in the format: leading , compressed number, , max+1, trailing `в`

Here an example answer where I use `•4Œ”dóŒfÝŸĀTUÕáOyÖOÀÁàu¼6¹₆Žr‡_›y³eß₂©ǝ²ƶ"SAÎAñ'¡û†Ø(•91в` to compress the list `[85,30,29,39,28,37,33,88,31,40,34,89,35,41,32,90,36,38,42,43,44,60,45,61,46,62,47,63,48,64,49,65,81,50,66,51,67,52,68,53,69,86,54,70,87,55,71,56,72,82,57,73,79,80,58,74,59,75,76,77,78,83,84]`.
PS: In this answer `•6j|eDEJÞó(ÍêΓλùÄÞKüzHÇ-ø`JδŠ₂+Öηôî®À8†6/ðÎ6ùøΓ°ÓĆ;ˆ©Ā•2ô` is an equal-bytes (57) alternative, since all numbers have exactly two digits. In some cases (especially small lists) this can be a shorter alternative.

One thing to note is that it's usually shorter to use a slightly larger single-byte integer constant (i.e. `T₂₆₃т₅₁₄` for `10,26,36,95,100,255,256,1000` respectively) instead of the maximum+1 found by the program above. Let's say our example `[5,94,17,83,4,44,32,19,4,45,83,90,0,14,3,17,17,81]` was `[5,95,17,83,4,44,32,19,4,45,83,90,0,14,3,17,17,81]` instead, it would find `•6MÖ∊]ć;?,ćiåÑ6Š•96в` (20 bytes) as shortest, but `•CRā»ïζyˆöÍ†y“a±•тв` (19 bytes) with the single-byte constant `100` would be 1 byte shorter.
You can still get the compressing program above by replacing the `Z>` with the single-byte constant (or its value): Try it online.

**Integer compression vs Integer list compression:**

With these two it can go either way. Sometimes a compressed list is shorter, sometimes a compressed integer, sometimes a completely different alternative is shorter. So always use your own judgment and golfing skills to possibly golf things further, instead of relying on the above generators completely. Here some examples:

`[44, 59]` (used in this answer of *@Emigna*):

`[2,4,6,0]` (used in this answer of *@Emigna*):

* `•3ā•7в` is 6 bytes (generated by the compressed integer list generator)
* `Ž3ā7в` is 5 bytes
* But in this case, `Ž9¦S` with 4 bytes would be the best option (compressed integer 2460 to a list of digits)

`10101001100101001` (initially used in this answer of mine):

* `•a½₄Ƶ6®í•` is 9 bytes (generated by compressed large integer generator)
* `•1∊}•2вJ` is 8 bytes (generated by compressed integer list generator with added join)
* `•1∊}•b` with 6 bytes would be even shorter (compressed integer list, with a *to binary* instead of , which implicitly joins)
* But `Ž«ǝbĆ` with 5 bytes would be the shortest option here (compressed integer, to binary, and enclose - appending its own head)

`[85,30,29,39,28,37,33,88,31,40,34,89,35,41,32,90,36,38,42,43,44,60,45,61,46,62,47,63,48,64,49,65,81,50,66,51,67,52,68,53,69,86,54,70,87,55,71,56,72,82,57,73,79,80,58,74,59,75,76,77,78,83,84]` (used in this answer of mine):
> 42 votes

# Answer
# Using the Canvas (`Λ` or )

Since it wasn't part of the docs, and *@Adnan* is currently a bit too busy to write it, I asked permission to add it as a tip here for now.

The Canvas function (`Λ` or ) can be used to draw ASCII-lines on the screen. It has three required parameters:

* ***a*** Length: The size of the line(s). This can be a single integer, or a list of integers
* ***b*** String: The character(s) we want to display. This can be a single character, a string, a list of characters, or a list of strings (in the last three cases it will use all of them one-by-one including wrap-around)
* ***c*** Direction: The direction the character-lines should be drawn in. In general we have the digits `[0,7]` for the directions, for which we can use one or multiple. There are also some special options that require a certain character (more about that later).

The direction-digits `[0,7]` map to the following directions:

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

```

Some example 05AB1E answers where the Canvas is used:

Let's do something similar as the last one, so assume we use the Canvas `Λ` function with the following three parameters:

* ***a***: `[3,3,5,5,7,7,9,9]`
* ***b***: `!@#`
* ***c***: `[0,2,4,6]`

This will give the following output:

```
  !@#!@#!
  #     @
  @ #!@ #
  ! @ # !
  # ! ! @
  @   @ #
  !#@!# !
        @
@!#@!#@!#

```

Try it online.

So how does it work? Well, here are the steps with these inputs above:

1. Draw `3` characters (`!@#`) upwards (direction `0`)
2. Draw `3-1` characters (`!@`) towards the right (direction `2`)
3. Draw `5-1` characters (`#!@#`) downwards (direction `4`)
4. Draw `5-1` characters (`!@#!`) towards the left (direction `6`)
5. Draw `7-1` characters (`@#!@#!`) upwards (direction `0`)
6. Draw `7-1` characters (`@#!@#!`) towards the right (direction `2`)
7. Draw `9-1` characters (`@#!@#!@#`) downwards (direction `4`)
8. Draw `9-1` characters (`!@#!@#!@`) towards the left (direction `6`)

The `-1` are there because the lines overlap. So the first two steps are:

```
#
@
!

```

And

```
 !@

```

Which combined is:

```
#!@
@
!

```

**Some minor notes:**

* Apart from the options `[0,7]` there are a few specific options available, which basically translate to a certain direction-sequence.
* The Canvas builtin will implicitly add trailing spaces to make the output a rectangle.
* The `Λ` will output immediately, and  results a string that is pushed to the stack, which we can still re-use, modify, and do anything with that we'd want. Some examples:
* Depending on the given options, either the lengths or directions are leading when drawing the output:
    + If a list of lengths is given, those lengths will always be leading. In this case, wrap-around can be used for the directions-list. Some examples:
    + If a single length-integer is given, the directions will be leading instead. In this case, you can't use wrap-around of the directions-list. For example:
> 16 votes

# Answer
# Implicit input

Back in the days when 05AB1E was released, implicit input was quite new and fancy. Nowadays it seems to be necessary in order to keep track with other competitive languages (like Jelly, MATL, Pyth, etc.).

For example, when you want to add two numbers, you can do `II+`:

```
I    # Input_1.
 I   # Input_2.
  +  # Add them up.

```

**Test it here**

---

However, using **implicit input**, we can shorten in to just 1 byte, namely `+`:

```
+    # Take two numbers implicitly and add them up.

```

**Test it here**

---

This only happens when the length of the stack is smaller than the arity of the operator. A last example is `3+`. The arity of the `+` operator is **2** while there is only **1** element in the stack:

```
3    # Push the number 3 on top of the stack.
 +   # Request implicit input and add to the 3.

```

**Test it here**
> 14 votes

# Answer
# Predefined variables

They are a bit hidden in 05AB1E. Here's a list of all the predefined variables:

* `¾`, pushes **`0`** if the counter\_variable is not changed before this command.
* `X`, pushes **`1`** if variable X is not changed before this command with `U`.
* `Y`, pushes **`2`** if variable Y is not changed before this command with `V`.
* `®`, pushes **`-1`** if the register is not changed before this command with `©`.
* `¯`, pushes **`[]`** (empty array) if nothing is added to the global\_array before this command.
* `¸`, pushes **`[""]`** on an empty stack if there is no input. (Thank you @Emigna for finding this one.)
> 11 votes

# Answer
# Substrings

`£` is the command for taking the first `b` characters of string `a`.
**ex:** `"hello_world"5£` `->` `"hello"`

But if `b` is a list of indices it instead splits the string into parts of (upto) those sizes.
**ex:** `"hello_world"5L£` `->` `['h', 'el', 'lo_', 'worl', 'd']`
> 11 votes

# Answer
# Small 05AB1E golfing tips

Will expand this with small golfing tips I learned along the way. (Only just started 05AB1E personally.)

* If you have a list of lists and first want to join each inner list by spaces, and then those space-delimited strings by newlines, the to-the-point approach would be `ðý»` of course. However, the `»` already implicitly joins inner lists by spaces before joining by newlines, so the `ðý` isn't necessary in this case: try it online.
* `D` (duplicate) and `Ð` (triplicate) in combination with `s` (swap) and `Š` (triple-swap `a,b,c` to `c,a,b`) are usually shorter than using `©` (save in *global\_variable*) and `®` (push *global\_variable*) inside loops. This saved a byte in this answer of mine, as well as two in this answer of mine.
* `½` (if 1, then increase *counter\_variable* by 1) isn't necessary at the end of a `µ` (while *counter\_variable* != a, do...), since it's done implicitly (saved a byte in this answer of mine).
* `.B` implicitly splits on new-lines. This was useful in this answer of mine when we were looking for an alternative for `¡` (split) while still keeping empty items (NOTE: Solution in the linked answer doesn't work when elements contain trailing spaces after splitting.) - Hopefully a builtin will be added to split but keep empty lines in the future.
* \[legacy version only\]  (which of the digits of the input-integer can evenly divide the input-integer) will contain the number itself for the digits `0` (instead of divide-by-zero errors). For example, `1053` will result in `[1,1053,0,1]` (1053 is divisible by 1 and 3; is not divisible by 5; and gives a division-by-zero error for 0). This was pretty useful in this answer of mine by taking the power of the list, since only `1` is truthy in 05AB1E and everything else is falsey. `SÖP` resulting in truthy (`1`) therefore means an input-integer is evenly divisible by each of its digits.
* After seeing `û` (palindromize a given string) I was surprised there isn't an *is\_palindrome* builtin. But later on I realized only 2 bytes are needed to accomplish that, which are `ÂQ` (where `Â` is bifurcate, which is short for `DR`: Duplicate & Reverse copy; and `Q` is to check if the top two values on the stack are equal).
* When you want to filter a list by multiple things, it's usually cheaper to have multiple loose filters, rather than all combined in one filter. Because when you have two filters you'll need something along the lines of `Ds*` (duplicate, swap, multiply to act as logical-AND) vs  (close first filter, filter again) when you use two filters. For example: in this challenge we have to list all numbers of four digits long, containing at least one `0`, and with a digit sum equal to `9`. Using a range `[1000,10000]` covers the number of four digits long, but then you are left with two more filters. Initially I used `₄4°ŸʒD0åsSO9Q*` (14 bytes), but by using two filters a byte can be saved: `₄4°Ÿʒ0å}ʒSO9Q` (13 bytes). (Which later got golfed to `₄4°ŸεW°ö9Q` (10 bytes) by *@Grimmy*.)
* When you want to zip with integer `0` as filler, you could use . One issue with this however is that the filler `0` will become a string `"0"`, so if you later try to sort with mixed strings and integer, this will most likely not give the result you'd want. Here an example of how it will sort the zipped inner lists: `0ζ€{`. This can be fixed by adding an explicit cast to int (`ï`) after the zip, and only then sort: `0ζï€{`. However, using the `¾` as constant `0` with the zip-filler, will cause it to remain an integer instead of a string during the zip. So `¾ζ€{` will save a byte here. This tip was provided by *@Mr.Xcoder* to save a byte in this answer of mine. (The same applies to `X` instead of `1` and `Y` instead of `2`.)
* If you want to sum the digits of multiple numbers in a list, you could use `€SO`. Shorter however is using , which automatically vectorizes. This tip was provided by *@Grimmy* to save a byte here (and 2 bytes here).
* If you're only dealing with non-negative integers, and you want to get a truthy value (`1`) when the integer is either 0 or 1, you could of course use the obvious `2‹`. However, using `!` (factorial) will also only result in 1 (truthy) for `0` and `1`, and every other value will result in something higher (and thus falsey, since only `1` is truthy in 05AB1E). This tip was provided by *@Grimmy* to save a byte here.
* If you want a list of all overlapping pairs (i.e. `[1,2,3,4,5,6,7,8,9]``[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9]]`), most probably already know `ü‚` can be used (Try it online). But what if you want a list of overlapping triplets or quartets? The most obvious approach would seem to be `Œ3ù` (substrings & keep those of length 3 - Try it online). But `ü` actually has a (currently undocumented) feature as shortcut for this `ü3` (Try it online), which works with any integer given to `ü`, including `2` to create overlapping pairs (Try it online).
* If the stack is empty, some builtins will use the last value that was previously on the stack (and thus there is also no implicit input!), saving you on a potential duplicate. For example, in this 05AB1E answer the `×` will use the `9L` list twice, without a need to duplicate it first. And in this 05AB1E program the `ÿ` inside the string will use the `11` all three times, without the need to triplicate it first.
* If we've used `|` to get all (remaining) inputs, the next `I` or implicit input will push this same list instead of the final input. Knowing this can sometimes save bytes, like in the top program of this answer of mine.
* There is a flatten builtin `˜` to flatten a multi-dimensional list to a single list: try it online. There is also a way to flatten a (potentially multi-dimensional) list of strings to a single list of characters with `S`: try it online. But what if we only want to flatten it down one level, instead of all the way? In that case, `€``  can be used if the order of items isn't important (try it online) or `í€``  if retaining the order of items is important (try it online). The unordered version is used pretty often in matrix-related challenges, like I used in this answer of mine.
* You probably know how `δ` (apply double-vectorized) can be used on two list arguments to execute it on every pair (e.g. `δ‚` will create pairs using the values in the two lists - try it online). You probably also know how it can be used as an apply-map with both a list and loose argument (e.g. `0δK` will remove all 0s from each inner list, which is shorter than a regular map `ε0K}` \- try it online). What you might not know, at least it was new to me, is when two integers are given as arguments, it implicitly uses their `[1,n]` ranged lists instead (e.g. `δ‚` again on two integer arguments will convert both to a list and applies the pairing to those - try it online). This saved two bytes in a couple of answers of mine (here and here for example).
> 8 votes

# Answer
# Pop or get

As in other stack-based languages, 05AB1E's functions usually **pop** (consume) their inputs from the stack and push their outputs onto the stack.

However, some functions **get** their inputs from the stack without consuming them. An example is the `head` function, `¬`, which produces the first element from the input list. See an example program here: `¬+`. This adds the first number of the input list to each number of that list.

To know which functions pop and which get, see the corresponding column in the function information file.
> 6 votes

# Answer
# 05AB1E ASCII-Art Golfing

The below code helps turn ASCII-art into 05AB1E using a custom base conversion.

```
|»©ÐÙSDŠ¢øΣθ}R€н¬®sÅ?iD2£RDŠKsì}J©žLR‡®gö₅B®s"•ÿ•“ÿ“ÅвJ"

```

Try it online.

This is accomplished by:

1. Listing out the unique characters in the ASCII drawing.
2. Order them by how many times they occur in the string in descending order (most occurring to least occurring characters).
3. Reverse the first two items if the ASCII drawing starts with the most occurring character (to prevent leading 0s in the compressed integer).
4. Map the characters of the input to `0-9A-Za-z` in that order, each distinct character getting its own mapping-character, until every one has been replaced.
5. Base compress it, using the highest base you needed to replace (based on the amount of unique characters).
6. Base convert it again to base-255 (for 05AB1E compression).
7. Format everything in the format: `•<compressed_integer>•“<sorted_distinct_characters>“ÅвJ`.

The  allows you to also compress string-quotes `"`; the `Åв` will use this string to base-convert the generated integer using the string as custom base; and `J` will join all these characters together to a single string, which is output implicitly.

Accepts patterns with up to and including 62 unique characters, good for ASCII-art.
The less amount of unique characters, the better the compression.

---

**Example output for Draw the XNOR digital timing diagram (214 bytes, 9 unique characters):**

```
    ┌─┐ ┌─┐ ┌─────┐ ┌─┐ ┌─┐ ┌───┐
A ──┘ └─┘ └─┘     └─┘ └─┘ └─┘   └──
  ┌───┐ ┌───┐ ┌─┐ ┌─────┐   ┌─┐ ┌─┐
B ┘   └─┘   └─┘ └─┘     └───┘ └─┘ └
    ┌─────┐   ┌─┐   ┌─┐   ┌───┐
X ──┘     └───┘ └───┘ └───┘   └────

```

Would be:

# 05AB1E, 106 bytes

```
•I£.µ*:]ó±øqaµb₄ΘYQmœ¹µû₄p´ζÂĆ_5ŠKÑ×ðòË|₄#¹¶úôÂ-Í|¯ε¼É₂ïδ&é–9»ÞFò1î×HÃBjý2ĆÉ≠FYÂÂèC j‘£Å₅Œ•“─ └┘┐┌
XBA“ÅвJ

```

Try it online.

**(106/214)\*100 = 49.53% the size of the original ASCII-art string.**

Which is the same byte-count as my actual submission for that challenge in 05AB1E (legacy).

---

# Code explanation:

NOTE: Code is absolutely not golfed. It's quickly written to convert ASCII art to the most efficient compression, so it's quite ugly and long..

```
|»               # Take multi-line input
  ©              # Store it in the register to reuse later
ÐÙS              # Only leave unique characters (as list)
   DŠ¢ø          # Map it with the count for each of those characters
       Σθ}R      # Sort it based on that count (highest to lowest)
           €н    # Remove the count again, so the sorted characters remain
¬®sÅ?i           # If the input starts with the most occurring character:
      D2£RDŠKsì} #  Swap the first two characters in the list
J©               # Join everything together, and store it in the register to reuse later
  žLR‡           # Map each character to [0-9A-Za-z]
      ®gö        # Get the amount of unique characters, and convert it to that Base
         ₅B      # And then convert that to Base-255
®s               # Push the string and swap so the compressed integer is at the top again
  "•ÿ•“ÿ“ÅвJ"    # Insert it in the correct output format
                 #  `•<compressed_integer>•“<sorted_distinct_characters>“ÅвJ`
"•ÿ•"            # (after which the result is output implicitly with trailing newline)

```
> 4 votes

# Answer
# Implicit `http://`

When using `.w` to make requests to URLs, you may be tempted to prepend `žX` (the builtin for `"http://"`) to the URL. Don't do it! According to line 239 of `gen_commands.ex` (general commands), if the URL does not start with `http`, it will automatically prepend `http://`. Not only that, but for URLs like `http://http-server.com`, while 05AB1E won't prepend `http://` to `http-server.com` as it starts with `http`, HTTPoison, 05AB1E's Elixir HTTP client, will automatically prepend `http://` (following the function calls all the way down to 05AB1E).
> 4 votes

# Answer
# Conditionals and loops

Loops and conditionals automatically receive closing brackets at the end of a program, so you only need to add them in the code if you need to something outside of the loop/conditional.

For example, this (ungolfed) program creating a list of the first `n` prime numbers do not need closing brackets. `[¹¾Q#NpiNˆ¼`

But if we wanted to perform some operation on the resulting list, for example taking delta's we'd need to close the loop first. `[¹¾Q#NpiNˆ¼]¯¥`
> 3 votes

# Answer
# Automatic vectorization

Note that some operators in 05AB1E vectorize automatically on arrays. For example, the code `5L3+`, which disassembles to the following pseudocode:

```
[1, 2, 3, 4, 5] + 3

```

would become:

```
[4, 5, 6, 7, 8]

```

If it doesn't vectorize automatically, you can also use the  operator. It takes a single character command, and performs that (monadic) operator on each element. An example to split each element is the following code (**try it here**):

```
€S

```

Whereas the normal `S` operator would split each element in the array and flattens it into a single array (**try it here**).
> 3 votes

# Answer
# Ordering of the Inputs

The order that you take input can have a drastic effect on your code, and, oftentimes if you're using `s` to swap the top of the stack with the next highest thing on the stack, you're not thinking about the problem correctly. Try to reorder inputs and see if you can get rid of the need to swap by either swapping the inputs ahead of time, adding it to the stack earlier on or duplicating it somewhere. The most obvious I&O can be the least successful 05AB1E answer.
> 3 votes

# Answer
# Strings and ints are equal types

Not something that everybody agrees with, but it works.

Consider the following two programs:

```
4 5+
"4""5"+

```

They both result into **9**. That is because every value is first evaluated (with `ast.literal_eval`). Because of that, we can perform all string manipulation operators on ints and all int manipulation operators on strings.

For example, `12345û` palindromizes the number `12345`, resulting in `123454321`. After that, we can do the regular math on this number.

```
12345û50000-

```

This would result into: **123404321**.
> 1 votes

# Answer
# Hidden loops and iterators

05AB1E has the following normal loops and iterators:

* `F`, which iterates through **0 .. n-1**.
* `G`, which iterates through **1 .. n-1**.
* `ƒ`, which iterates through **0 .. n**.
* `v`, which iterates over each element **s\[0\], s\[1\], .., s\[n\]**.
* `ʒ`, which is not exactly a loop, but a *filter-by* command. We abuse this command for it's unintended behaviour of looping through each element.

Using these loops, we can derive the following *hidden loops*:

* Instead of `gF`, you can use `v` which also has an `N`-index that can be used.
* The `vy -> ʒ` replacement is a bit more tricky:
    + You need to immediately print the results. This surpresses the automatic print from printing the top of the stack.
    + The code snippet is run on a **new temporary stack**. This means that stack-dependent snippets cannot be used.
    + Invoking `y` is not possible in these kind of loops.
> 0 votes

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


title: Reversible hex dump utility (aka `xxd`)

text:
# Question
Title: Reversible hex dump utility (aka `xxd`)
`xxd` is a utility, bundled with `vim`, that has been used to encode answers to code golf problems on this site. It converts a binary file into a hex dump and back again.

Implement the `xxd` and `xxd -r` commands in the programming language(s) of your choice. Scoring is based on the character/byte lengths of a) your program(s) and b) any command line argument(s) necessary to switch a combined program between modes (they need not be `-r`). As in golf, lower scores are better.

* For two separate programs: *forward code* \+ *reverse code*
* For a combined program: *combined code* \+ sum(*forward arguments*) + sum(*reverse arguments*) - 2

## Specification of the chosen `xxd` subset

The forward command (*e.g.* `xxd`) accepts 0 ≤ *n* ≤ 216 bytes from standard input and generates ceil(*n* / 16) lines of standard output in the following format (all hex digits lowercase):

* Offset of the first encoded byte (format string `"%07x:"`); ends in `"0"`
* At most 16 hex-encoded bytes, grouped into pairs (format string `" %02x"` for even bytes, `"%02x"` for odd bytes) and right-padded with spaces to 42 characters
* The encoded bytes interpreted as ASCII characters, values not between 0x20 and 0x7e (`'\40'` and `'\176'`) inclusive becoming `"."`
* A newline (`"\n"`; `"\r\n"` allowed when standard output is in binary mode)

Minimal ungolfed C implementation:

```
#include <stdio.h>
int main() {
    unsigned char L[16];
    int t = 0, n, i, s;

    for (; (n = fread(L, 1, 16, stdin)); t += n) {
        printf("%07x:", t);
        s = 42;
        for (i = 0; i < n; i++)
            s -= printf(i & 1 ? "%02x" : " %02x", L[i]);
        printf("%*s", s, "");
        for (i = 0; i < n; i++)
            putchar(L[i] > '\37' && L[i] < '\177' ? L[i] : '.');
        printf("\n");
    }

    return 0;
}

```

The reverse command (*e.g.* `xxd -r`) accepts any unmodified output of the forward command (given a valid input to that command) and produces that original input.

## Example usage

```
$ xxd < /dev/null | wc -c
0
$ php -r 'echo join(range("\0",~"\0"));' | xxd
0000000: 0001 0203 0405 0607 0809 0a0b 0c0d 0e0f  ................
0000010: 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f  ................
0000020: 2021 2223 2425 2627 2829 2a2b 2c2d 2e2f   !"#$%&'()*+,-./
0000030: 3031 3233 3435 3637 3839 3a3b 3c3d 3e3f  0123456789:;<=>?
0000040: 4041 4243 4445 4647 4849 4a4b 4c4d 4e4f  @ABCDEFGHIJKLMNO
0000050: 5051 5253 5455 5657 5859 5a5b 5c5d 5e5f  PQRSTUVWXYZ[\]^_
0000060: 6061 6263 6465 6667 6869 6a6b 6c6d 6e6f  `abcdefghijklmno
0000070: 7071 7273 7475 7677 7879 7a7b 7c7d 7e7f  pqrstuvwxyz{|}~.
0000080: 8081 8283 8485 8687 8889 8a8b 8c8d 8e8f  ................
0000090: 9091 9293 9495 9697 9899 9a9b 9c9d 9e9f  ................
00000a0: a0a1 a2a3 a4a5 a6a7 a8a9 aaab acad aeaf  ................
00000b0: b0b1 b2b3 b4b5 b6b7 b8b9 babb bcbd bebf  ................
00000c0: c0c1 c2c3 c4c5 c6c7 c8c9 cacb cccd cecf  ................
00000d0: d0d1 d2d3 d4d5 d6d7 d8d9 dadb dcdd dedf  ................
00000e0: e0e1 e2e3 e4e5 e6e7 e8e9 eaeb eced eeef  ................
00000f0: f0f1 f2f3 f4f5 f6f7 f8f9 fafb fcfd feff  ................
$ xxd <<< 'The quick brown fox jumps over the lazy dog.'
0000000: 5468 6520 7175 6963 6b20 6272 6f77 6e20  The quick brown
0000010: 666f 7820 6a75 6d70 7320 6f76 6572 2074  fox jumps over t
0000020: 6865 206c 617a 7920 646f 672e 0a         he lazy dog..
$ xxd <<< 'The quick brown fox jumps over the lazy dog.' | xxd -r
The quick brown fox jumps over the lazy dog.

```

# Answer
## Perl, ~~122 + 54 = 176~~ 122 + 45 = 167

The forward script:

```
$/=$,;for(<>=~/.{1,16}/gs){$h="";$h.=sprintf"%*s%02x",++$m%2,"",ord for/./gs;
s/[^ -~]/./g;printf"%06x0:%-42s",$n++,$h;say}

```

And the reverse script:

```
/:(.+?)  /,print map{chr hex}$1=~/\w\w/gfor<>

```

(This one is interesting; there are all kinds of obscure bugs that can show up in the reverse script depending on the input, if you're not careful.)
> 3 votes

# Answer
## Javascript, ~~247 + 61 = 308~~ 225 + 63 = 288

*-20 or so thanks to ASCII-only*

Forward:

```
b=>[...Array(b.length+15>>4)].map((_,i)=>(P=j=>i=>i.toString(x=16).padStart(j,0))(7)(i)+"0: "+(p=b.splice(0,x)).map(P(2)).join``.replace(/.{4}/g,"$& ").padEnd(42)+p.map(l=>String.fromCharCode(l>31&l<127?l:46)).join``).join`
`

```

Try it online!

Reverse:

```
d=>d.match(/[^:]{40}/g).join``.match(/\S\S/g).map(t=>+("0x"+t))

```

Try it online!

Might make an explanation at some point.
> 3 votes

# Answer
## C (clang), ~~222 + 108 = 330~~ ~~189 + 105 = 294~~ 186 + 104 = 290 bytes

**Forward** (*-36 thanks to @ceilingcat*):

```
#define P printf(
t,n,s;main(i){for(char z[16];n=read(i=0,z,16);t+=n){P"%07x:",t);for(s=42;i<n;)s-=P" %02x"+i%2,z[i++]);for(i=!P"%*s",s,"");i<n;i++)P"%c",isprint(z[i])?z[i]:46);P"\n");}}

```

Try it online!

**Reverse** (*-4 thanks to @ceilingcat*):

```
b;main(a){for(char z[80];gets(z);)for(a=9;z[a]-32;a+=5)b=strtol(z+a,0,16),b=b>>8?ntohs(b):b,printf(&b);}

```

Try it online!
> 2 votes

# Answer
# 253

# JavaScript (V8), 200 bytes

```
b=>{for(i=0,P=j=>i=>i.toString(16).padStart(j,0);t=b.slice(i,i+16),t+t;i+=16)print(P(7)(i)+': '+t.map(P(2)).join``.replace(/.{4}/g,"$& ").padEnd(42)+String.fromCharCode(...t.map(c=>c<32|c>126?46:c)))}

```

Try it online!

# JavaScript (V8), ~~57~~ 53 bytes

```
d=>d.match(/(?<=:.*)\w\w(?=.{19})/g).map(t=>"0x"+t-0)

```

Try it online!

optimized from Redwolf Programs's answer
> 2 votes

---
Tags: code-golf
---


title: Primes in Different Bases

text:
# Question
Title: Primes in Different Bases
**Challenge:**

You are given a base 10 number. For each base from 10 counting down to base 2:

1. Take the original input number as a base 10 string, and remove any digits of the number which are invalid for the base.
2. Interpret the resulting number string in the that base. If this gives 1 or 0, terminate the whole process.
3. Output or print its largest prime factor, as decimal number.

The output can be an array of the largest prime factors.

**Sample cases:**

Input:

```
987654321

```

Output:

```
379721
10593529
1091
179
1493
293
19
7

```

Alternately:

```
[379721,10593529,1091,179,1493,293,19,7]

```

This prints the largest prime factors of \\$987654321\\$, \\$87654321\_9 = 42374116\_{10}\\$, \\$7654321\_{8} = 2054353\_{10}\\$, and so on until it reaches \\$1\_2\\$, where it stops.

# Answer
## Pyth, 25 bytes

```
sfTm>1PiFdC,.u-N`tYKrT1zK

```

```
                       z   get input as a string
            .u      rT1    cumulative reduce over [10,9,...,2]
              -N`tY        remove one minus the number (10,9,...) from the input
          C,       K    K  pair each step along the chain with corresponding base
   m                       map over [["987654321", 10],...]:
       iFd                   apply the base-conversion (splat over i)
      P                      prime factorization, smallest to largest
    >1                       take [the last element], or [] if empty (1 or 0)
 fT                        remove the []s from 0s or 1s
s                          join the one-element arrays together

```

Try it here.
> 6 votes

# Answer
# MATL, ~~17~~ 15 bytes

```
9:PQ"G@ZAYfXzX>

```

This takes the number as a string with quotes, which is allowed by default.

**Try it online!**

### Explanation

```
9:PQ     % Push array [10, 9, ..., 2]
"        % For each number in that array. These are the bases to be considered
  G      %   Push input. Forces for input to be taken implicitly first time
  @      %   Push current base
  ZA     %   Convert from that base to base 10, discarding non-valid digits
  Yf     %   Prime factors. Gives empty for input 1, and 0 for input 0
  Xz     %   Non-zero values. Gives empty if previous result was 0, or else
         %   leaves it as it was
  X>     %   Maximum of array. For empty input gives empty
         % Implicitly end for each
         % Implicitly display. Empty arrays are not displayed

```
> 4 votes

# Answer
# Pyth - 16 bytes

```
V_S9#ePi~-z`NhNB

```

Try it online here.

~~There are sometimes a few blank lines on inputs without all the digits, lemme know if that's a problem.~~
> 4 votes

# Answer
# Julia, 101 bytes

```
f(s,x=[],b=10)=(t=filter(c->c<=47+b,s))>"1"&&b>1?f(s,[x;maximum(keys(factor(parse(Int,t,b))))],b-1):x

```

This is a recursive function that accepts the input as a string and returns an array.

Ungolfed:

```
function f(s, x=[], b=10)
    # Filter the string down to only the digits valid for base b
    t = filter(c -> c <= 47 + b, s)

    # If the filtered string isn't "1" or "0" and b is a valid base
    if t > "1" && b > 1
        # Call the function again, appending the maximum prime factor
        # of t in base b to the argument x and decrementing the base
        f(s, [x; maximum(keys(factor(parse(Int, t, b))))], b-1)
    else
        # Otherwise return the array
        x
    end
end

```
> 1 votes

# Answer
# Mathematica, 83 bytes

```
FactorInteger[Select[IntegerDigits@#,#<a&]~FromDigits~a][[-1,1]]~Table~{a,10,2,-1}&

```

Anonymous function, returns a list. Not that complicated, to be honest.
> 1 votes

# Answer
# Jelly, 14 bytes

```
D<ƇḅṛɗⱮ⁵ÆfṀ€t0

```

Try it online!

## How it works

```
D<ƇḅṛɗⱮ⁵ÆfṀ€t0 - Main link. Takes an integer n on the left
D              - Cast n to digits, D
     ɗ         - Previous 3 links as a dyad f(D, k):
 <Ƈ            -   Keep elements of D less than k
    ṛ          -   Yield k
   ḅ           -   Convert to base k
       ⁵       - 10
      Ɱ        - Yield the range 1 ≤ k ≤ 10 and map f(D, k) over each
        Æf     - Prime factors
          Ṁ€   - Maximum of each, or 0 if empty list
            t0 - Trim zeros

```
> 1 votes

# Answer
# Ruby, 120 bytes

Recursive function, takes the input as a string.

```
f=->n,b=2{require'prime';i=n.tr([*b.to_s..?9].join,"").to_i(b)
b>10?[]:f[n,b+1]+[*i>1?Prime.prime_division(i).max[0]:p]}

```
> 0 votes

# Answer
## Pyke, 19 bytes, noncompeting

(add splat\_node functon)
```
DTAbPe
;1TtD=T`"":r

```

Try it here!

Takes input in quotes, exits with an error.

Explanation (newline replaced with \n):

```
D                    - Duplicate the first item on the stack (And get it from input first time)
 TAb                 - Convert input to base (whatever's in T, 10 default)
    Pe               - get the highest prime factor of the number
      \n;1           - print it out and get rid of it
          TtD=T      - T -= 1
               `"":  - input = input.replace(str(t), "")
                   r - GOTO start

```
> 0 votes

---
Tags: code-golf, math, primes, base-conversion
---


# Question
Title: nth number with n distinct prime factors
A073329 is a sequence where the \\$n\\$th term is the \\$n\\$th number with exactly \\$n\\$ distinct prime factors. For example, \\$a(3) = 60\\$ as the first \\$3\\$ integers with \\$3\\$ distinct prime factors are \\$30 = 2 \times 3 \times 5\\$, \\$42 = 2\times3\times7\\$ and \\$60 = 2^2 \times 3 \times 5\\$.

You are to take a positive integer \\$n\\$ and output the first \\$n\\$ terms of the sequence. You may assume the input will never exceed the bounds of your language's integers. This is so the shortest code in bytes wins.

The first 10 terms of the sequence are

```
2, 10, 60, 420, 4290, 53130, 903210, 17687670, 406816410, 11125544430

```

# Answer
## Python, 144 chars

```
R=range
P=[x for x in R(2,99)if all(x%i for i in R(2,x))]
for a in R(input()):
 x=n=0
 while n<=a:n+=sum(x%p==0for p in P)==a+1;x+=1
 print x-1

```

It takes about 2 minutes to run to completion for x=8.
> 2 votes

# Answer
**Java, 170 characters in one line**

```
int a(int n) {
    int a = 2, t = a, m = 1, i = 1;
    Set s = new HashSet();
    while (i++ > 0) {
        if (t % i == 0) {
            s.add(i);
            t /= i;
            if (t == 1) {
                if (s.size() == n) {
                    if (n == m) {
                        break;
                    }
                    m++;
                }
                t = ++a;
                s.clear();
            }
            i = 1;
        }
    }
    return a;
}

```

**Update, +77 characters IOL**

```
int[] f(int n) {
    int[] f = new int[n];
    for (int i = 0; i < n; i++) {
        f[i] = a(i+1);
    }
    return f;
}

```
> 2 votes

# Answer
### Java (Ungolfed)

```
public class M {

    public static void main(String[] a) {
        final int N = 100000000;
        int[] p = new int[N];
        for(int f = 2; f * f < N; f++) {
            if(p[f] == 0)
                for(int k = f; k < N; k += f)
                    p[k]++;
        }
        for(int i = 1; i <= 8; i++) {
            int c = 0, j;
            for(j = 1; j < N && c < i; j++)
                if(p[j] == i)
                    c++;
            if(c == i)
                System.out.println(i + " = " + --j);
        }
    }
}

```

Uses a sieve algorithm. It's pretty quick. **(6 Seconds)** Will work accurately for upto `8`, will probably fail for anything higher.
> 2 votes

# Answer
## JavaScript, 149 chars

```
function(n){function f(x){for(r=[],o=x,z=2;z<=o;x%z?++z:(x/=z,r.indexOf(z)+1?0:r.push(z)));return r}for(c=0,i=1;c<n;)f(++i).length==n?c++:0;return i}

```

Feels unresponsive for n \>= 6 so I haven't tested how long it takes (my browser pops up a hung script notification every 10 seconds or so therefore I can't time it accurately and I don't want to completely hang if I check "don't show this again"...)

Edit: To return array is **200 characters (+51)**:

```
function(n){function F(){function f(x){for(r=[],o=x,z=2;z<=o;x%z?++z:(x/=z,r.indexOf(z)+1?0:r.push(z)));return r}for(c=0,i=1;c<n;)F(++i).length==n?c++:0;return i}for(a=[];n>0;n--)a.push(f());return a}

```
> 1 votes

# Answer
# Jelly, 9 bytes

```
Æv=¥ḷ#)Ṫ€

```

Try it online!

## How it works

```
Æv=¥ḷ#)Ṫ€ - Main link. Takes n on the left
      )   - For each integer 1 ≤ k ≤ n, so the following:
   ¥ḷ#    -   Find the first k integers for which the following is true:
Æv        -     The number of distinct prime factors
  =       -     equals k
       Ṫ€ - Return the last element from each list

```
> 1 votes

# Answer
# J, 32 bytes

```
({"0 1~i.@#)(]/.~#@~.@q:)

```

But since I'm answering my own question so late, we'll just leave this answer as a curiosity.
> 0 votes

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


title: No More Jockeys - CodeGolf Version

text:
# Question
Title: No More Jockeys - CodeGolf Version
This challenge is inspired by the game No More Jockeys.

The input is a list of tuples of natural numbers (potentially including 0), in some appropriate input format. Starting with player 0 and alternating with player 1, each player chooses some number which is contained within at least one remaining tuple, and all tuples containing that number will be removed from the list. The first player who has no possible moves loses.

Your challenge is to implement a function to calculate the minimax value of a given input. Return a truthy value if it is player 1 to win given optimal play by both players, and a falsy value if it is player 0 to win. The converse is also acceptable.

This is , so fewest bytes wins.

## Test Cases

```
((), (0, 1, 3), (1,)) -> 0
() -> 1
((0,), (1, 3), (2,)) -> 0
((), (0, 1), (0, 1, 2), (0, 2), (1,)) -> 1
((0,), (0, 1, 3), (0, 3), (2,)) -> 0
((), (0, 1), (0, 2, 3), (1,), (2,), (3,)) -> 1
((0, 1), (1, 2), (2, 3), (3,)) -> 0
((0, 2), (1,), (1, 3), (3,), (4,)) -> 1
((0, 2, 3), (0, 3), (1,), (2,), (2, 3)) -> 0

```

# Answer
> 2 votes
# Jelly, 9 bytes

```
iÐḟⱮẎß€0e

```

Try it online!

My first attempt repeatedly segfaulted, but now that I have a very close translation of hyper-neutrino's Python solution it seems to work fine.

I would be remiss to let this get accepted without an explanation!

```
   Ɱ         For each element of
    Ẏ        the input flattened a level,
 Ðḟ          yield the input without elements which
i            contain the element in question.
     ß€      Recur on each result.
       0e    Is one of those results 0?

```

# Answer
> 6 votes
# Python 3, 62 bytes

```
f=lambda a:0in(f([x for x in a if{r}-{*x}])for r in sum(a,()))

```

Try it online!

# Python 2, 61 bytes

```
f=lambda a:0in(f(filter({y}.__sub__,a))for x in a for y in x)

```

Try it online!

-5 bytes thanks to Unrelated String
-6 bytes thanks to dingledooper
-1 byte if we use Python 2 thanks to dingledooper
-2 bytes thanks to xnor

Outputs `True` for player 0 winning and `False` or `()` for player 1 winning (`()` is an empty tuple in Python, which is a falsey value in the language)

# Answer
> 5 votes
# JavaScript (ES10), 54 bytes

Returns a Boolean value.

```
f=a=>!a.flat().some(v=>f(a.filter(b=>!b.includes(v))))

```

Try it online!

# Answer
> 4 votes
# Haskell, 41 bytes

```
f a=any(not.f.(`filter`a).notElem)$a>>=id

```

Try it online!

*Was* the same length as using nested list comprehensions, until I realized `notElem` exists, and is much shorter than `(not.).elem`. Still feels very golfable...

# Answer
> 3 votes
# , 37 bytes

```
(0=1#.]$:@#~1-~.@;e.&>/])`1:@.(''-:;)

```

Try it online!

Inspired by Arnauld's answer.

---
Tags: code-golf, combinatorics, game
---