title: Division of not so little numbers

text:
# Question
Title: Division of not so little numbers
Write a program or function that takes in positive integers `a`, `b` and `c`, and prints or returns `a/b` to `c` decimal places, using the operations +-\*/% \[add, subtract, multiply, divide, modulate\] on the positive integers: you can use all that your language allows, but not on floating point numbers. The range of a,b,c would be the range allowed for unsigned integers in your language. The number result will be truncated to the last digit to print (so no `round`).

This means that if your language does not have an integer type (only float), you can participate by using these float numbers as positive integers only. The clue of this exercise it would be to write the function that find the digits in a float point division, using only the operation +-\*/% on \[unsigned\] integers.

### Examples

* `print(1,2,1)` would print `0.5`
* `print(1,2,2)` would print `0.50`
* `print(13,7,27)` would print `1.857142857142857142857142857`
* `print(2,3,1)` would print `0.6`
* `print(4,5,7)` would print `0.8000000`
* `print(4,5,1)` would print `0.8`
* `print(9999,23,1)` would print `434.7`
* `print(12345613,2321,89)` would print if your Language has 32 bit unsigned `5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466`

The shortest code in bytes wins. I'm sorry if this appear not clear... I don't know languages too, not remember words well... It is better to have one link to Ideone.com or some other place for easily try the answer especially for to test some input different from proposed.

# Answer
> 5 votes
# 05AB1E, ~~17 13 11 19~~ 14 bytes

Input in the form `b, a, c`.
Saved 5 bytes thanks to *Grimy*.

```
‰`¹+I°*¹÷¦'.sJ

```

Try it online!

# Answer
> 5 votes
## Haskell, 87 bytes

```
(a#b)c|s<-show$div(a*10^c)b,l<-length s-c,(h,t)<-splitAt l s=['0'|l<1]++h++['.'|c>0]++t

```

Usage example: `(13#7)27` -\> `"1.857142857142857142857142857"`.

23 bytes to handle the `c==0` case and using a leading zero instead of things like `.5`.

How it works: multiply `a` with `10^c`, divide by `b`, turn into a string, split where the `.` must be inserted, join both parts with a `.` in-between and fix the edge cases.

# Answer
> 4 votes
# Perl 6,  ~~58 57 55~~  48 bytes

```
{(($^a.FatRat/$^b*10**$^c).Int.FatRat/10**$c).base(10,$c)}

```

```
{(Int($^a.FatRat/$^b*10**$^c).FatRat/10**$c).base(10,$c)}

```

```
{base Int($^a.FatRat/$^b*10**$^c).FatRat/10**$c: 10,$c}

```

```
{base ($^a*10**$^c div$^b).FatRat/10**$c: 10,$c}

```

What is fairly annoying is that it could be shortened to just `{($^a.FatRat/$^b).base(10,$^c)}` if it was allowed to round to the nearest value.

## Explanation:

```
# bare block lambda with 3 placeholder parameters ｢$^a｣, ｢$^b｣ and ｢$^c｣
{
  (
    (

      # create an Int containing all of the digits we care about
      $^a * 10 ** $^c div $^b

    ).FatRat / 10**$c  # turn it into a Rational

  ).base( 10, $c )     # force it to display ｢$c｣ digits after the decimal point
}

```

# Answer
> 3 votes
# PHP, 187 Bytes

works with strings for the numerator which can be int values greater then `PHP_INT_MAX`

```
list(,$n,$d,$c)=$argv;$a=str_split($n);while($a){$n.=array_shift($a);if($n>=$d||$r)$n-=$d*$r[]=$n/$d^0;}if(!$r)$r[]=0;if($c)$r[]=".";while($c--){$n*=10;$n-=$d*$r[]=$n/$d^0;}echo join($r);

```

I have no other chance then 13/7 is shorten to 1.8571428571429 and I reach so not the test case with 27 decimal places

This way 36 Bytes is not allowed

```
<?=bcdiv(($z=$argv)[1],$z[2],$z[3]);

```

# Answer
> 3 votes
# Perl, 55 bytes

Includes +3 for `-p`

Give a and b on one line on STDIN, c on the next

```
division.pl
1 26
38
^D

```

`division.pl`:

```
#!/usr/bin/perl -p
eval'$\.=($_/$&|0)."."x!$\;$_=$_%$&.0;'x(/ .*/+<>)}{

```

the `$_/$&` is a bit arguable. I Actually ***want*** an integer division there but perl doesn't have that without loading special modules. So it's temporarily a non-integer which I then immediately truncate (using `|0`) so I end up with the integer an integer division would give. It could be rewritten as `($_-$_%$&)/$&` in order to not even temporarily have a non-integer value (it would internally still be a float though)

# Answer
> 3 votes
# JavaScript (ES6), ~~55~~ 50 bytes

```
f=(a,b,c,d=".")=>~c?(a/b|0)+d+f(a%b*10,b,c-1,""):d

```

`(a/b|0)` performs float division but immediately casts to an integer. Please let me know if this is not allowed.

# Answer
> 2 votes
# Pyth - ~~21~~ ~~19~~ ~~18~~ ~~16~~ 14 bytes

Will be looking over the input format, that can prolly save a bunch.

```
j\.c`/*E^TQE]_

```

Test Suite. (P.S. the 27 one doesn't finish online, so I did 10 instead).

# Answer
> 2 votes
## JavaScript (ES6),  ~~64~~  ~~62~~ 59 bytes

*Saved 2 bytes thanks to ETHproductions.*

The included division always results in an integer.

```
f=(a,b,n,s)=>~n?f((q=(a-a%b)/b,a%b*10),b,n-1,s?s+q:q+'.'):s

console.log(f(13,7,27))
```

# Answer
> 2 votes
## Racket 203 bytes

```
(let*((s(~r(/ a b)#:precision c))(sl(string-split s "."))(s2(list-ref sl 1))(n(string-length s2)))
(if(< n c)(begin(for((i(- c n)))(set! s2(string-append s2 "0")))(string-append(list-ref sl 0)"."s2))s))

```

Ungolfed:

```
(define (f a b c)
  (let* ((s (~r(/ a b)#:precision c))
         (sl (string-split s "."))
         (s2 (list-ref sl 1))
         (n (string-length s2)))
    (if (< n c)
        (begin
          (for ((i (- c n)))
            (set! s2 (string-append s2 "0")))
          (string-append (list-ref sl 0) "." s2))
        s )))

```

Usage:

```
(f 7 5 3)
(f 1 2 1)
(f 1 2 2)
(f 13 7 27)

```

Output:

```
"1.400"
"0.5"
"0.50"
"1.857142857142857142857142857"

```

Other method (not valid answer here):

```
(real->decimal-string(/ a b)c)

```

# Answer
> 2 votes
# Java 7, 105 bytes

```
import java.math.*;String c(int...a){return new BigDecimal(a[0]).divide(new BigDecimal(a[1]),a[2],3)+"";}

```

**Ungolfed & test code:**

Try it here.

```
import java.math.*;
class M{
  static String c(int... a){
    return new BigDecimal(a[0]).divide(new BigDecimal(a[1]), a[2], 3)+"";
  }

  public static void main(String[] a){
    System.out.println(c(1, 2, 1));
    System.out.println(c(1, 2, 2));
    System.out.println(c(13, 7, 27));
    System.out.println(c(2, 3, 1));
    System.out.println(c(4, 5, 7));
    System.out.println(c(4, 5, 0));
    System.out.println(c(9999, 23, 0));
    System.out.println(c(12345613, 2321, 89));
  }
}

```

**Output:**

```
0.5
0.50
1.857142857142857142857142857
0.6
0.8000000
0
434
5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466

```

# Answer
> 2 votes
# Ruby, 67 bytes

```
->(a,b,c){('0'+(a*10**c/b).to_s).gsub(/^0*(.+)(.{#{c}})$/,'\1.\2')}

```

if I make it a function to execute the test cases above

```
def print(a,b,c); ('0'+(a*10**c/b).to_s).gsub(/^0*(.+)(.{#{c}})$/, '\1.\2'); end
 => :print
print(1,2,1)   # would print 0.5
 => "0.5"
print(1,2,2)   # would print 0.50
 => "0.50"
print(13,7,27) # would print 1.857142857142857142857142857
 => "1.857142857142857142857142857"
print(2,3,1)   # would print 0.6
 => "0.6"
print(4,5,7)   # would print 0.8000000
 => "0.8000000"
print(4,5,1)   # would print 0.8
 => "0.8"
print(9999,23,1) # would print 434.7
 => "434.7"
print(12345613,2321,89) # would print if your Language has 32 bit unsigned 5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466
 => "5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466"
"('0'+(a*10**c/b).to_s).gsub(/^0*(.+)(.{#{c}})$/, '\1.\2')".length
 => 52

```

# Answer
> 1 votes
# q, 196 bytes

```
w:{((x 0)div 10;1+x 1)}/[{0<x 0};(a;0)]1;{s:x 0;m:x 2;r:(10*x 1)+$[m<0;{x*10}/[-1*m;a];{x div 10}/[m;a]]mod 10;d:1#.Q.s r div b;($[m=-1;s,".",d;$[s~,:'["0"];d;s,d]];r mod b;m-1)}/[c+w;("";0;w-1)]0

```

To run: set a, b, c first.

# Answer
> 1 votes
# Rust, 114 bytes

```
fn print(mut a:u32,b:u32,c:u32){let mut p=||{print!("{}",a/b);a=a%b*10};p();if c>0{print!(".")}for _ in 0..c{p()}}

```

**test code:**

```
fn main() {
    print(1, 2, 1);    println!(""); // should print 0.5
    print(1, 2, 2);    println!(""); // should print 0.50
    print(13, 7, 27);  println!(""); // should print 1.857142857142857142857142857
    print(2, 3, 1);    println!(""); // should print 0.6
    print(4, 5, 7);    println!(""); // should print 0.8000000
    print(4, 5, 0);    println!(""); // should print 0
    print(9999, 23, 0);println!(""); // should print 434
    print(12345613,2321,89); println!("\n");  // 5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466
}

```

# Answer
> 1 votes
# PHP, 89 bytes

```
list(,$a,$b,$c)=$argv;for($o=intdiv($a,$b).'.';$c--;)$o.=intdiv($a=10*($a%$b),$b);echo$o;

```

intdiv() is introduced in php 7 so it requires that. php 7.1 would allow me to change the list() to \[\] and so would save 4 bytes.

use like:

```
php -r "list(,$a,$b,$c)=$argv;for($o=intdiv($a,$b).'.';$c--;)$o.=intdiv($a=10*($a%$b),$b);echo$o;" 1 2 1

```

# Answer
> 1 votes
# C#, 126 bytes

```
(a,b,c)=>{var v=a*BigInteger.Parse("1"+new string('0',c))/b+"";return v.PadLeft(c+1,'0').Insert(Math.Max(1,v.Length-c),".");};

```

Full program with test cases:

```
using System;
using System.Numerics;

namespace DivisionOfNotSoLittleNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<BigInteger,BigInteger,int,string>f= (a,b,c)=>{var v=a*BigInteger.Parse("1"+new string('0',c))/b+"";return v.PadLeft(c+1,'0').Insert(Math.Max(1,v.Length-c),".");};

            //test cases:
            Console.WriteLine(f(1,2,1));    //0.5
            Console.WriteLine(f(1,2,2));    //0.50
            Console.WriteLine(f(13,7,27));  //1.857142857142857142857142857
            Console.WriteLine(f(2,3,1));    //0.6
            Console.WriteLine(f(4,5,7));    //0.8000000
            Console.WriteLine(f(4,5,1));    //0.8
            Console.WriteLine(f(9999,23,1));    //434.7
            Console.WriteLine(f(12345613,2321,89)); //5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466
            Console.WriteLine(f(2,3,1));    //0.6
            Console.WriteLine(f(4,5,2));    //0.80
        }
    }
}

```

Integer division is implemented. Numbers of any size can be used, due to the `BigInteger` data type (the import `System.Numerics` is required). The digit-count parameter `c` is restricted to 2^31-1, however it should provide more than enough digits.

# Answer
> 1 votes
# Groovy (~~78~~ ~~77~~ 42 Bytes)

```
{a,b,n->Eval.me(a+'.0g').divide(b, n, 1)}

```

## Explanation

`Eval.me(a+'.0g');` \- Convert from integer input to BigDecimal input. In groovy BigDecimal notation is double notation with an appended G or g. I could've also used the constructor `new BigDecimal(it)` but this saved a byte.
`.divide(b, n, 1)` \- Divide by b with n precision, rounding mode half-up.

Try it here: https://groovyconsole.appspot.com/script/5177545091710976

# Answer
> 1 votes
## Batch, 122 bytes

```
@set/as=%1/%2,r=%1%%%2
@set s=%s%.
@for /l %%a in (1,1,%3)do @set/ad=r*10/%2,r=r*10%%%2&call set s=%%s%%%%d%%
@echo %s%

```

# Answer
> 1 votes
# Mathematica, 50 bytes

```
StringInsert[ToString@Floor[10^# #2/#3],".",-#-1]&

```

Unnamed function of three arguments (which are ordered `c`, `a`, `b` to save a byte somewhere), which returns a string. It multiplies `a/b` by `10^c`, takes the greatest integer function, then converts to a string and inserts a decimal point at the appropriate spot. Too bad the function names aren't shorter.

# Answer
> 1 votes
**Python 3, 62 Bytes**

```
a,b,c=map(int,input().split());print("{:.{1}f}".format(a/b,c))

```

Try It Here

**\*Note**: *repl.it* uses an older ver of *Python 3*, which requires all field indices to be specified, meaning `"{:.{1}f}"` will be `"{0:.{1}f}"` instead, making it *63 bytes* in *repl.it*

**How to use**

Enter all three values with spaces in-between. i.e. An input of `1 2 1` would give a result of `0.5`

**Explanation**

`input().split()`: Gets user input and splits it into a list with a separator of (space)

`a,b,c = map(int,XX)`: Maps the variables into the values specified by the user with an int type

`"{:.{1}f}".format(a/b,c)`: Formats a string to display the division result and substitutes `{1}` with `c` to set the decimal place of the displayed string

`print(XX)`: prints the string supplied

# Answer
> 1 votes
# Stax, 13 bytes

```
ä·oαì█↕▬AS¥é▼

```

Run and debug it

Arguments are accepted in `c a b` order.

# Answer
> 1 votes
# Python 3, 58 bytes

```
lambda a,b,c:(lambda s:s[:-c]+"."+s[-c:])(str(a*10**c//b))

```

Try it online!

This is precise to the specified number of decimals as long as `a * 10 ** c` isn't too large.

I tried Python 2 to shorten the `str(...)` to ``...`` but Python 2 inserts an `L` at the end if it's too large so checking for that would take way more bytes than it's worth.

# Answer
> 0 votes
# C, 67 bytes

```
h(a,b,i){int j=!i;for(;printf(j++?"%u":"%u.",a/b),i--;a=10*(a%b));}

```

Try it online!

Some previous version I think had a bug in read memory out of assigned to the program...Thanks to ceilingcat and for all...

---
Tags: code-golf, math, number, arithmetic, division
---


title: Golfing Strings

text:
# Question
Title: Golfing Strings
I have always failed to give an answer for challenges which require string compression, the main reason being that I don't know to use string compression tools *as effectively as I should*.

For this reason, I have posted this question. Unlike my other tips questions, this is not language specific meaning that if you can think of any tips in your own language, then you may post it (providing that you specify the language). General tips are also appreciated.

So, how can I use string compression tools to their maximum effectiveness?

# Answer
> 9 votes
# Base conversion (CJam)

An easy way to encode ASCII strings that do not start with a null byte is to convert from base 128 to integer, then to base 256:

```
128b256b:c              e# Prints encoded string.
128b256b:c`"256b128b:c" e# Prints encoded string with decoder.

```

This uses 7 bits to encode each ASCII character.

If the original string consists only of, e.g., lowercase letters, and does no start with an **a**, we can start by mapping `"a...z"` to `[0 ... 25]`, then proceed as above:

```
'afm26b256b:c               e# Prints encoded string.
'afm26b256b:c`"256b26b'af+" e# Prints encoded string with decoder.

```

Finally, if the original string has only a few unique characters (common in ASCII art), it is usually better to specify the alphabet explicitly.

For example:

```
" +-/\|"f#6b256b:c                       e# Prints encoded string.
" +-/\|"f#6b256b:c`"256b6b"" +-/\|"`"f=" e# Prints encoded string with decoder.

```

As a rule of thumb, you want the first character of the original string to be the *second* character of the alphabet, the next distinct character of the original string to be the first character of the alphabet, the next distinct character of the original string to be the third character of the alphabet, the next distinct character of the original string to be the fourth character of the alphabet, etc.

The encoder of last example works as follows:

```
" +-/\|"f# e# Replace each character by its index in that string.
6b256b     e# Convert from base 6 (length of the alphabet) to base 256.
:c         e# Cast each digit to character.

```

The decoder of last example works as follows:

```
256b6b     e# Convert from base 256 to base 6.
" +-/\|"f= e# Replace each digit by the corresponding character of the alphabet.

```

# Answer
> 9 votes
Larger Kolmogorov complexity questions with some structure but no simple formula (e.g. song lyrics) will typically benefit from a grammar-based approach. In essence, you extract repeated substrings and encode them somehow. This is what Lempel-Ziv does, using a fairly restricted class of grammars; if you use more general grammars then you have to figure out how to encode the rules. E.g. one approach here is "offset encoding", where you offset each source byte by the number of rules (`n`), assign bytes `1` to `n` to the rules, use the `0` byte to separate rules, and repeatedly replace byte `i` with the evaluated rule `i`. Finally you undo the offset by subtracting `n` from each byte.

I have actually written a Java program which implements various approaches:

> Most of the approaches follow a two-phase process. In the first phase the string is converted into a grammar which generates it; in the second phase, the grammar is converted into a GolfScript program. The first phase implementations are largely based on Charikar, Lehman, Liu, Panigrahy, Prabhakaran, Sahai, & Shelat (2005) The smallest grammar problem, Information Theory, IEEE Transactions on, 51(7), 2554-2576.

It also includes a Lempel-Ziv approach, a base encoding approach, and a runlength-encoding approach, and identifies the one which gives the shortest program.

# Answer
> 2 votes
# Stax

In the Stax code golfing language, there's a helpful little tool called the *string literal compressor*. I don't know how it works, exactly, but there is another where I *do* know how it works. It converts strings into numbers, then into Base 256. It's CP437, with 0x00 and 0xFF converted for copying. It's PackedStax. You could convert your strings with the string literal compressor then Pack it, for some good compression.

Using this process the string "This string is thirty-two bytes" can be converted to v\*"A\]-|W4\]}3"% (the compressed string is usually surrounded by backticks to tell the difference between a normal string in Stax) and finally to üvìë!\[┴╩qJu←▓α for a compression / reduction of 18 bytes, more than half.

---
Tags: code-golf, string, kolmogorov-complexity, tips, compression
---


# Question
Title: Generate ladder of integers using the least number of unique characters (in C++)
I am new to the sport of code golf. I am trying to generate a ladder of integers using the least number of unique characters in C++.

Let's say we are given an integer 4.

We will generate the following ladder:

1
1 2
1 2 3
1 2 3 4

In short, my program will read a positive integer from stdin and print this ladder to the output. I am trying to do so with the **least number of unique characters** possible.

My program is as follows:

```
#include<iostream>

int i;
int ii;
int iii;
int iiii;

main() {
    std::cin >> i;
    for(ii++; ii <= i; ii++) {
        int iii = iiii;
        for(iii++; iii <= ii; iii++) {
            std::cout << iii << " ";
        }
        std::cout << std::endl;
    }
}

```

Here's the checker that I used to check the number of unique characters in my program:

```
#include <cstdio>
#include <cstring>
using namespace std;
int check[300],diffcnt=0,cnt=0,t;
char c;
double score;
int main(){

    memset(check,0,sizeof(check));
    FILE *in=fopen("ans.cpp","r");
    while(fscanf(in,"%c",&c)!=EOF){
        cnt++;
        if(!check[c]){
            check[c]=1;
            if(c=='\r'||c=='\n') continue;
            diffcnt++;
        }
    }
    if(diffcnt<25) printf("100\n");
    else if(diffcnt<30){
        printf("%.3lf\n",20.0*100.0/cnt+20.0*(29-diffcnt));
    }
    else{
        score=20.0;
        for(int x=95;x<cnt;x++) score*=0.9;
        printf("%.3lf\n",score);
    }
    printf("Unique Characters: %d\n", diffcnt);
    printf("Total Characters: %d\n", cnt);
    return 0;
}

```

Preferably I wish to use **less than** 25 unique characters to complete this program (excluding newline characters but including whitespace). Currently, my program uses 27. I am not sure how to optimize it further.

Could someone please advise me on how to optimize it further (in terms of the number of unique characters used)? Please note that only C++ can be used.

# Answer
> 12 votes
I believe I managed to remove the = character from your code, although it now is significantly slower

```
#include<iostream>

int i;
int ii;
int iii;
int iiii;

int main() {
    std::cin >> i;
    i++;
    for(ii++; ii < i;) {
    for(;iii>iiii;iii++);
    for(;iii<iiii;iii++);
    ii++;
        for(iii++; iii < ii; iii++) {
            std::cout << iii << " ";
        }
        std::cout << std::endl;
    }
}

```

Its not pretty, but by abusing integer overflow we can get back to 0 without using =

Also we had to change the guards a little. Unfortunately because of the include I couldn't get rid of all new line characters (although its close) so that may be the next avenue for investigation.

Edit: Run out of time for now, but if you include and use strstream and various other libraries, I think you may be able to remove the " character too, again using integers to arrive at the correct character for space and passing it into the strstream

# Answer
> 11 votes
I finally got 24 unique characters by combining the answers of @ExpiredData and @someone. Also, using the short data type instead of int helped to speed up my program because it takes a shorter time to overflow a short data type.

My code is as follows.

```
%:include<iostream>

short i;
short ii;
short iii;
short iiii;
char iiiii;

main() <%
    std::cin >> i;
    iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;
    iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;
    iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;
    iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;
    i++;
    for(ii++; ii < i; ii++) <%
        for(;iii;iii++);
        for(iii++; iii < ii; iii++)
            std::cout << iii << iiiii;
        std::cout << iii << std::endl;
    %>
%>

```

# Answer
> 9 votes
# 23 unique characters using Digraphs. (25 without). No UB.

**Use C++11 braced initializer syntax** to list-initialize an integer to zero with `int var{};` avoiding `=` and `0`. (Or in your case, avoiding global `iiii`). This gives you a source of zeros other than global variables (which are statically initialized to zero, unlike locals).

Current compilers accept this syntax by default, without having to enable any special options.

(The integer wraparound trick is fun, and ok for golfing with optimization disabled, but signed overflow is undefined behaviour in ISO C++. Enabling optimization will turn those wraparound loops into infinite loops, unless you compile with gcc/clang `-fwrapv` to give signed integer overflow well-defined behaviour: 2's complement wraparound.

Fun fact: ISO C++ `std::atomic<int>` has well-defined 2's complement wrap-around! `int32_t` is required to be 2's complement if defined at all, but the overflow behaviour is undefined so it can still be a typedef for `int` or `long` on any machine where one of those types is 32 bits, no padding, and 2's complement.)

---

Not useful for this specific case:

You can also initialize a new variable as a copy of an existing one, with either braces or (with a non-empty initializer), parens for direct initialization.
`int a(b)` or `int a{b}` are equivalent to `int a = b;`

But `int b();` declares a function instead of a variable initialized to zero.

Also, you can get a zero with `int()` or `char()`, i.e. zero-initialization of an anonymous object.

---

**We can replace your `<=` compares with `<` compares by a simple logic transformation**: do the loop-counter increment right after the compare, instead of at the bottom of the loop. IMO this is simpler than the alternatives people have proposed, like using `++` in the first part of a `for()` to make a 0 into a 1.

```
    // comments aren't intended as part of the final golfed version
    int n;
    std::cin >> n;      // end condition

    for(int r{}; r < n;) {      // r = rows from 0 .. n-1
        ++r;
        for(int i{}; i < r;) {
            ++i;
            std::cout << i << ' ';
        }
        std::cout << std::endl;
    }

```

We could golf that down to `for(int r{}; r++ < n;)` but IMO that's less easy for humans to read. We're not optimizing for total byte count.

---

**If we were already using `h`, we could save the `'` or `"` for a space.**

Assuming an ASCII or UTF-8 environment, space is a `char` with value 32. We can create that in a variable easily enough, then `cout << c;`

```
    char c{};
    c++; c++;            // c=2
    char cc(c+c+c+c);    // cc=8
    char s(cc+cc+cc+cc); // s=32 = ' ' = space in ASCII/UTF-8

```

And other values can obviously be created from a sequence of `++` and doubling, based on the bits of their binary representation. Effectively shifting a 0 (nothing) or 1 (++) into the LSB before doubling into a new variable.

---

This version uses `h` instead of `'` or `"`.

It's much faster than either of the existing versions (not relying on a long loop), and is **free of Undefined Behaviour**. It compiles with no warnings with `g++ -O3 -Wall -Wextra -Wpedantic` and with `clang++`. `-std=c++11` is optional. It is legal and portable ISO C++11 :)

It also doesn't rely on global variables. And I made it more human-readable with variable names that have a meaning.

**Unique-byte count: 25**, *excluding the comments which I stripped with `g++ -E`*. And excluding space and newline like your counter. I used `sed 's/\(.\)/\1\n/g' ladder-nocomments.cpp | sort | uniq -ic` from this askubuntu to count occurrences of each character, and piped that into `wc` to count how many unique characters I had.

```
#include<iostream>

int main() {
    char c{};
    c++; c++;            // c=2
    char cc(c+c+c+c);    // cc=8
    char s(cc+cc+cc+cc); // s=32 = ' ' = space in ASCII/UTF-8

    int n;
    std::cin >> n;      // end condition

    for(int r{}; r < n;) {      // r = rows counting from 0
        ++r;
        for(int i{}; i < r;) {
            ++i;
            std::cout << i << s;
        }
        std::cout << std::endl;
    }
}

```

The only 2 `f` characters are from `for`. We could use `while` loops instead if we had a use for `w`.

We could possibly rewrite the loops into an assembly-language style of `i < r || goto some_label;` to write a conditional jump at the bottom of the loop, or whatever. (But using `or` instead of `||`). Nope, that doesn't work. `goto` is a *statement* like `if` and can't be a sub-component of an expression like it can in Perl. Otherwise we could have used it to remove the `(` and `)` characters.

We could trade `f` for `g` with `if(stuff) goto label;` instead of `for`, and both loops always run at least 1 iteration so we'd only need one loop-branch at the bottom, like a normal asm `do{}while` loop structure. Assuming the user inputs an integer \> 0...

---

## Digraphs and Trigraphs

Fortunately, trigraphs have been removed as of ISO C++17 so we don't have to use `??>` instead of `}` if we're unique-golfing for the most recent C++ revision.

But only trigraphs specifically: **ISO C++17 still has digraphs like `:>` for `]` and `%>` for `}`**. So at the cost of using `%`, we can avoid both `{` and `}`, and use `%:` for `#` for a net saving of 2 fewer unique characters.

And C++ has operator keywords like `not` for the `!` operator, or `bitor` for the `|` operator. With `xor_eq` for `^=`, you could zero a variable with `i xor_eq i`, but it has multiple characters you weren't using.

Current `g++` already ignores trigraphs by default even without `-std=gnu++17`; you have to use `-trigraphs` to enable them, or `-std=c++11` or something for strict conformance to an ISO standard that does include them.

**23 unique bytes:**

```
%:include<iostream>

int main() <%
    int n;
    std::cin >> n;

    for(int r<% %>; r < n;) <%
        ++r;
        for(int i<%%>; i < r;) <%
            ++i;
            std::cout << i << ' ';
        %>
        std::cout << std::endl;
    %>
%>

```

**Try it online!**

The final version uses a `'` single-quote instead of `h` or `"` for the space separator. I didn't want to digraph the `char c{}` stuff so I deleted it. Printing a char is more efficient than printing a string, so I used that.

**Histogram:**

```
$ sed 's/\(.\)/\1\n/g' ladder-nocomments.cpp | sort | uniq -ic  | tee /dev/tty | wc -l
     15         // newline
     95         // space
     11 %
      2 '
      3 (
      3 )
      4 +
      9 :
     10 ;
     14 <
      8 >
      2 a
      4 c
      6 d
      3 e
      2 f
     12 i
      2 l
      2 m
     11 n
      5 o
      7 r
      5 s
     11 t
      3 u
25   // total lines, including space and newline

```

---

### The space separator (still unsolved)

In a now-deleted answer, Johan Du Toit proposed using an alternate separator, specifically `std::ends`. That's a NUL character, `char(0)`, and prints as zero-width on most terminals. So the output would look like `1234`, not `1 2 3 4`. Or worse, separated by garbage on anything that didn't silently collapse `'\0'`.

If you can use an arbitrary separator, when the digit `0` is easy to create with `cout << some_zeroed_var`. But nobody wants `10203040`, that's even worse than no separator.

I was trying to think of a way to **create a `std::string` holding a `" "`** without using `char` or a string literal. Maybe appending something to it? Maybe with a digraph for `[]` to set the first byte to a value of `32`, after creating one with length 1 via one of the constructors?

Johan also suggested the `std::ios` fill() member function which returns the current fill character. The default for a stream is set by `std::basic_ios::init()`, and is `' '`.

**`std::cout << i << std::cout.fill();`** replaces `<< ' ';` but **uses `.` instead of `'`**.

With `-`, we can take a pointer to `cout` and use `->fill()` to call the member function:
`std::cout << (bitand std::cout)->fill()`. Or not, we weren't using `b` either so we might as well have used `&` instead of its lexical equivalent, `bitand`.

**Calling a member function without `.` or `->`**

Put it inside a class, and define `operator char() { fill(); }`

```
// not digraphed
struct ss : std::ostream {  // default = private inheritance
//      ss() { init(); }  // ostream's constructor calls this for us
        operator char() { return fill(); }
}

```

Then `ss s{}` before the loop, and `std::cout << i << s;` inside the loop. Great, it compiles and works properly, **but we had to use `p` and `h` for `operator char()`,** for a net loss of 1. At least we avoided `b` to make member functions `public` by using `struct` instead of `class`. (And we could override the inheritance with `protected` in case that ever helps).

# Answer
> 7 votes
# C++ (gcc) x86\_64 Linux only, ~~9295 8900 8712 6812 5590~~ 5218 bytes, 18 unique characters

```
int m[]={11111111111111111+1111111111111111+1111111111111+1111111111111+111111111+111111111+11111111+11111111+11111111+111111+11+11+11+11+11+11+11+1+1,11111111111+11111111111+11111111111+1111111111+111111111+111111111+111111111+111111+1111+1111+111+111+111+111+11+11+11+11+11+11+11+11+11+1+1+1,111111111111111111+11111111111111+11111111111+111111111+11111111+11111111+111111+111111+111111+111111+1111+111+111+111+111+111,111111111111111+111111111111111+111111111111111+111111111111111+11111111111111+111111111111+111111111+11111111+11111111+11111+1111+1111+111+111+11+11+1+1+1+1,11111111111111111+1111111111111111+1111111111111111+1111111111111111+111111111+111111111+11111111+111111+11111+11111+11111+1111+1111+1111+11+11+11+11+11+11+11,1111111111111111+111111111111111+111111111111+11111111111+1111111111+1111111111+11111111+111111+111111+11111+11+11+11+1+1+1+1+1+1+1+1,11111111111111111+1111111111111111+11111111111+11111111111+11111111+11111111+11111111+1111+1111+11+11+11+11+11+11+11+11+11+1+1+1,111111111111+11111111111+1111111111+1111111111+1111111111+1111111111+1111111111+1111111111+11111111+11111+11111+11111+11111+11111+11111+1+1,111111111111111+11111111111111+11111111111+11111111111+1111111111+1111111+1111111+11111+111+111+111+111+111+111+111+111+11+11+1+1+1+1+1+1,11111111111+1111111111+111111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+11+1+1+1+1+1+1+1,111111111111111111+1111111111111111+1111111111111111+111111111111111+111111111+11111111+11111+11111+11111+11111+11111+11111+111+111+111+111+111+111+11+11+1+1+1,11==1,1111111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+11+11+11+1+1+1,1111111111111+111111111111+11111111111+1111111111+111111111+111111111+11111111+111111+111111+111111+11111+1111+111+111+1+1,111111111111+111111111111+11111111111+11111111111+11111111111+11111111111+111111111+111111111+11111111+111111+1111+1111+111+111+111,111111111111+11111111111+1111111111+1111111111+111111111+1111111+111+111+1+1+1+1,11111111111111111+1111111111111111+1111111111111111+1111111111+1111111111+111111111+1111111+1111111+1111111+1111111+1111111+1111+1111+1111+111+111+11+1+1+1+1+1,111111111111111+1111111111111+1111111111111+11111111111+1111111111+11111111+11111111+1111+1111+1111+111+111+111+111+11+11,111111111+111111111+11111111+11111111+11111111+1111111+1111111+111111+11111+1111+1111+1111+1111+111+111+11+11+11+11+11+1+1+1+1+1+1+1+1,11111111111111+111111111111+111111111111+11111111111+111111111+111111+111111+111111+1111+1111+1111+1+1+1+1+1+1+1+1,111111111111111111+1111111111111+1111111111111+111111111111+111111111+111111111+111111111+11111111+1111111+111111+111+11+11+11+11+1+1+1,11111111111111111+111111111111111+1111111111+111111111+111111111+11111111+1111+1111+1111+111+111+111+11+11+11+11+11+11+11+11+11+11,111111111111111+1111111111111+1111111111+111111111+11111111+1111111+1111111+111111+11111+11111+11111+1111+111+111+111+111+11+11+11+1+1+1+1+1,1111111111111111+111111111111111+111111111111111+11111111+11111111+1111111+1111111+1111111+1111+1111+1111+1111+1111+111+11+11+11+1+1+1+1+1+1+1+1+1+1,111111111111111+1111111111111+111111111111+111111111111+111111111111+11111111111+1111111111+1111111111+111111111+111111+111111+111111+111111+1111+11+1+1,111111111111111+11111111111111+111111111111+111111111111+1111111111+1111111111+111111111+11111111+1111+1111+1111+111+111+111+111+111+11+11+11+11+11+11+11+11+1+1+1+1,11111111111111111+1111111111111111+11111111111+11111111+1111111+1111111+111111+11111+11111+1111+1111+111+111+111+111+111+111+111+111+11+11+1+1+1+1+1+1+1+1,11111111111111111+11111111111111+1111111111+1111111+111111+11111+11111+11111+1111+111+111+111+111+111+111+11+11+11+11+11+11+11+11+11,11111111111111111+1111111111111+1111111111111+1111111111111+1111111111+1111111+11111+11111+11111+1111+111+111+111+1+1+1+1+1+1+1,1111111111111+1111111111+11111111+11111111+11111111+11111+1111+111+111+11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1,1111111111111111+11111111111+11111111111+11111111111+111111111+111111111+111111111+11111+11111+11111+11111+11111+11111+11111+11111+11111+111+111+11,11111111111111+1111111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+11111+1111+1111+111+111+111+111+111+111+1+1+1+1+1+1,111111111111111+1111111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+1111111+111111+11111+11111+11111+1111+111+111+111+11+11+11+11+11,1111111111+111111111+1111111+1111111+111111+111111+11111+11111+11111+11111+11111+11111+1111+1111+1111+11+11+11+11+11+11+11+11+11+1+1+1,11111111111111111+11111111111111111+1111111111111111+1111111111111111+1111111111111+11111111111+111111111+111111+111111+111111+1+1+1+1+1+1+1,1111111111+111111111+111111111+11111111+1111111+1111111+1111111+111111+11111+11111+11111+11111+11111+111+111+111+11+11+11+1,111111111111111111+11111111111111111+111111111111111+111111111111111+111111111111111+11111111111+11111111111+11111111+11111+11111+11111+11111+11111+11+11+11+1+1+1,111111111111+11111111111+1111111111+111111111+111111111+111111+111111+111111+111111+11111+11111+11+11+11+11+11+1,111111111+11111+11111+111+11+1+1+1+1+1+1+1+1+1};main(){((int(*)())m)();}

```

Try it online!

This uses the character set  `()*+,1;=[]aimnt{}` and is based on ideas from this CGCC answer. A machine language program is expressed as an array of 32 bit ints, each of which is represented as a sum of `1+11+111...`. It turns out that it may be more efficient to encode `x` as `y` such that `y%(1<<32)==x`. The encoded machine language program is the following

```
0x0000000000000000:  55                         push    rbp
0x0000000000000001:  31 ED                      xor     ebp, ebp
0x0000000000000003:  53                         push    rbx
0x0000000000000004:  48 83 EC 18                sub     rsp, 0x18
0x0000000000000008:  48 8D 74 24 0C             lea     rsi, [rsp + 0xc]
0x000000000000000d:  31 C0                      xor     eax, eax
0x000000000000000f:  31 FF                      xor     edi, edi
0x0000000000000011:  6A 01                      push    1
0x0000000000000013:  5A                         pop     rdx
0x0000000000000014:  0F 05                      syscall
0x0000000000000016:  89 C3                      mov     ebx, eax
0x0000000000000018:  85 C0                      test    eax, eax
0x000000000000001a:  74 0C                      je      0x28
0x000000000000001c:  6B ED 0A                   imul    ebp, ebp, 0xa
0x000000000000001f:  03 6C 24 0C                add     ebp, dword ptr [rsp + 0xc]
0x0000000000000023:  83 ED 30                   sub     ebp, 0x30
0x0000000000000026:  EB E0                      jmp     8
0x0000000000000028:  C7 44 24 0C 00 00 00 00    mov     dword ptr [rsp + 0xc], 0
0x0000000000000030:  FF C3                      inc     ebx
0x0000000000000032:  8B 44 24 0C                mov     eax, dword ptr [rsp + 0xc]
0x0000000000000036:  8D 78 01                   lea     edi, [rax + 1]
0x0000000000000039:  89 7C 24 0C                mov     dword ptr [rsp + 0xc], edi
0x000000000000003d:  E8 27 00 00 00             call    0x69
0x0000000000000042:  6A 20                      push    0x20
0x0000000000000044:  48 89 E6                   mov     rsi, rsp
0x0000000000000047:  52                         push    rdx
0x0000000000000048:  58                         pop     rax
0x0000000000000049:  50                         push    rax
0x000000000000004a:  5F                         pop     rdi
0x000000000000004b:  0F 05                      syscall
0x000000000000004d:  5E                         pop     rsi
0x000000000000004e:  39 5C 24 0C                cmp     dword ptr [rsp + 0xc], ebx
0x0000000000000052:  7C DE                      jl      0x32
0x0000000000000054:  6A 0A                      push    0xa
0x0000000000000056:  48 89 E6                   mov     rsi, rsp
0x0000000000000059:  52                         push    rdx
0x000000000000005a:  58                         pop     rax
0x000000000000005b:  0F 05                      syscall
0x000000000000005d:  5E                         pop     rsi
0x000000000000005e:  39 DD                      cmp     ebp, ebx
0x0000000000000060:  7F C6                      jg      0x28
0x0000000000000062:  48 83 C4 18                add     rsp, 0x18
0x0000000000000066:  5B                         pop     rbx
0x0000000000000067:  5D                         pop     rbp
0x0000000000000068:  C3                         ret
0x0000000000000069:  85 FF                      test    edi, edi
0x000000000000006b:  74 2C                      je      0x99
0x000000000000006d:  89 F8                      mov     eax, edi
0x000000000000006f:  6A 0A                      push    0xa
0x0000000000000071:  59                         pop     rcx
0x0000000000000072:  48 83 EC 18                sub     rsp, 0x18
0x0000000000000076:  99                         cdq
0x0000000000000077:  F7 F9                      idiv    ecx
0x0000000000000079:  89 C7                      mov     edi, eax
0x000000000000007b:  8D 42 30                   lea     eax, [rdx + 0x30]
0x000000000000007e:  89 44 24 0C                mov     dword ptr [rsp + 0xc], eax
0x0000000000000082:  E8 E2 FF FF FF             call    0x69
0x0000000000000087:  48 8D 74 24 0C             lea     rsi, [rsp + 0xc]
0x000000000000008c:  6A 01                      push    1
0x000000000000008e:  58                         pop     rax
0x000000000000008f:  50                         push    rax
0x0000000000000090:  5F                         pop     rdi
0x0000000000000091:  50                         push    rax
0x0000000000000092:  5A                         pop     rdx
0x0000000000000093:  0F 05                      syscall
0x0000000000000095:  48 83 C4 18                add     rsp, 0x18
0x0000000000000099:  C3                         ret

```

...which is based on the following C code.

```
void print(int x){
  if( x ) {
    int y=x%10+'0';
    print(x/10);
    write(1,&y,1);
  }
}
void f() {
  int i=0,j=0,k;
  for( ;read(0,&k,1);i=i*10+k-'0' );
  do {
    for( j++,k=0; print( ++k ), write(1," ",1), k<j; );
    write(1,"\n",1);
  } while(j<i );
}

```

Edit: Now accepts input from `stdin` instead of `argv[1]`. Thanks to @ASCII-only and @PeterCordes for their suggestions!

Edit4: ~~Slightly~~ Significantly improved encoding.

# Answer
> 6 votes
# 21 unique characters + 1 unremovable newline

```
%:include<iostream>
int(n)(int(i))<%
    if(--i)if(n(i))<%%>
    if(i)if(std::cout<<i<<std::addressof(std::cout)->fill())<%%>
%>
int(l)(int(i))<%
    if(n(-(--i)))<%%>
%>
int(m)(int(i))<%
    if(--i)if(m(i))<%%>
    if(i)if(l(-i))<%%>
    if(i)if(std::cout<<std::endl)<%%>
%>
int(c)(int(i))<%
    if(m(-(--i)))<%%>
%>
int(main)(int(i))<%
    if(std::cin>>i)<%%>
    if(c(-i))<%%>
%>

```

Whitespaces aren't required except for the first newline. Compiled in g++ 7.3.0.

Used characters: `%:include<ostram>()f-`.

Improvements to other answers:

1. Removed semicolons by changing `for` loops to `if` and recursion.
2. Got the space character by `std::addressof(std::cout)->fill()`, aka `std::cout.fill()`.

# Answer
> 2 votes
# ~~21~~ 20 unique characters excluding whitespaces

All whitespaces could be changed into newlines.

```
%:include<iostream>
%:include<list>
int n;
const int co<%%>;
const int ci<%not co%>;
const int cmu<%-ci-ci-ci-ci%>;
const char ctd<%-cmu-cmu-cmu-cmu-cmu-cmu-cmu-cmu%>;
const int cia<%-ctd-ctd-ctd-ctd-ctd-cmu%>;
const int ciu<%cia- -ci- -ci%>;

struct<%struct<%struct<%struct<%struct<%struct<%struct<%
int c<:ctd-ci:>;
%>d<:ctd:>;int c<:ctd-ci:>;%>d<:ctd:>;int c<:ctd-ci:>;
%>d<:ctd:>;int c<:ctd-ci:>;%>d<:ctd:>;int c<:ctd-ci:>;
%>d<:ctd:>;int c<:ctd-ci:>;%>d<:-cmu:>;int c<:-ci-cmu:>;
%>e<:co:><:ctd:><:ctd:><:ctd:><:ctd:><:ctd:><:ctd:>;

int i<:co:>;
auto ia<%e%>;
auto iu<%e%>;
int l<%std::cin>>n and co%>;

struct s<%
    int c<%std::cout<<i<:ciu:>- --i<:cia:><<ctd and n%>;
%>;
struct o<%
    int c<%--ia and n%>;
%>;
struct t<%
    std::list<s>c<%- --l%>;
    std::list<o>r<%-l%>;
    int m<%std::cout<<std::endl and n%>;
%>;
std::list<t>a<%n%>;
int main;

```

Exits with segfault. Used characters: `%:include<ostram>;-h`.

It works in this specific compiler version on a 64 bit Linux:

```
g++-5 (Ubuntu 5.5.0-12ubuntu1) 5.5.0 20171010

```

With the parameter:

```
-std=c++17

```

Even then, I'm not sure it would always work. It may also depends on a lot of other things. `cia` and `ciu` are the memory offsets divided by 4 between `ia` `iu` and `i`. (`int` is 32 bit in this version.) You may have to change the numbers to match the actual offset. The addresses would be much more predictable if they are all contained in a struct. Unfortunately non-static `auto` isn't allowed in a struct.

`e` is a 0-elements array of an element type with a size of (2<sup>32</sup>-1) ×2<sup>32</sup> bytes. If the corresponding pointer type of `e` is decremented, the higher half of the pointer would be decremented by (2<sup>32</sup>-1), which is equivalent to incrementing by one. This could reset the decremented counter without using the equality sign.

A more reasonable version that should work more reliably, but uses one more character `=`:

```
%:include<iostream>
%:include<list>
int n;
int ci<%not n%>;
int cmu<%-ci-ci-ci-ci%>;
char ctd<%-cmu-cmu-cmu-cmu-cmu-cmu-cmu-cmu%>;
int i;
int l<%std::cin>>n and n-n%>;

struct s<%
    int c<%std::cout<<- --i<<ctd and n%>;
%>;
struct t<%
    std::list<s>c<%- --l%>;
    int r<%i=n-n%>;
    int m<%std::cout<<std::endl and n%>;
%>;
std::list<t>a<%n%>;
int main;

```

Even this doesn't work in the latest version of g++ because it doesn't seem to allow defining `main` in an arbitrary type anymore.

These two programs don't use parentheses. But then semicolons don't seem to be avoidable.

# Answer
> 1 votes
22 Unique characters excluding whitespaces. Separates the numbers with a NUL character which displays correctly on Windows.

```
%:include<iostream>
int main(int n)<%
    std::cin>>n;
    for(int r<%%>;r++<n;)<%
        for(int i<%%>;i<r;)
            std::cout<<++i<<std::ends;
        std::cout<<std::endl;
    %>
%>

```

Try it online

Histogram:

```
[%] 0x25 = 9
[:] 0x3A = 11
[)] 0x29 = 3
[i] 0x69 = 11
[n] 0x6E = 12
[c] 0x63 = 4
[l] 0x6C = 2
[u] 0x75 = 3
[d] 0x64 = 8
[e] 0x65 = 4
[<] 0x3C = 13
[o] 0x6F = 5
[s] 0x73 = 7
[t] 0x74 = 12
[r] 0x72 = 6
[a] 0x61 = 2
[m] 0x6D = 2
[>] 0x3E = 7
[(] 0x28 = 3
[;] 0x3B = 7
[f] 0x66 = 2
[+] 0x2B = 4
Unique Characters: 22
Total Characters: 189

```

---
Tags: code-challenge, tips, c++
---


title: Sort of numbers

text:
# Question
Title: Sort of numbers
Within the recesses of Unicode characters, there exists a Unicode block of (currently) 63 characters named "Number Forms", which consists of characters that have numerical values such as the roman numeral Ⅻ, vulgar fractions like ⅑ or ↉, or weird ones like ↊ (10) or ↈ (100000).

Your task is to write a program or function that, when given a list of assigned Unicode characters within this block, sorts the list by the numerical values of each character.

A (sortable) list of characters and values can be found on the Wikipedia Page.

To be self contained though, here's a list of the codepoints and their values:

```
Hex     Char   Value
0x00BC: ¼   = 1/4 or 0.25
0x00BD: ½   = 1/2 or 0.5
0x00BE: ¾   = 3/4 or 0.75
0x2150: ⅐   = 1/7 or 0.142857
0x2151: ⅑   = 1/9 or 0.111111
0x2152: ⅒   = 1/10 or 0.1
0x2153: ⅓   = 1/3 or 0.333333
0x2154: ⅔   = 2/3 or 0.666667
0x2155: ⅕   = 1/5 or 0.2
0x2156: ⅖   = 2/5 or 0.4
0x2157: ⅗   = 3/5 or 0.6
0x2158: ⅘   = 4/5 or 0.8
0x2159: ⅙   = 1/6 or 0.166667
0x215A: ⅚   = 5/6 or 0.833333
0x215B: ⅛   = 1/8 or 0.125
0x215C: ⅜   = 3/8 or 0.375
0x215D: ⅝   = 5/8 or 0.625
0x215E: ⅞   = 7/8 or 0.875
0x215F: ⅟   = 1
0x2160: Ⅰ   = 1
0x2161: Ⅱ   = 2
0x2162: Ⅲ   = 3
0x2163: Ⅳ   = 4
0x2164: Ⅴ   = 5
0x2165: Ⅵ   = 6
0x2166: Ⅶ   = 7
0x2167: Ⅷ   = 8
0x2168: Ⅸ   = 9
0x2169: Ⅹ   = 10
0x216A: Ⅺ   = 11
0x216B: Ⅻ   = 12
0x216C: Ⅼ   = 50
0x216D: Ⅽ   = 100
0x216E: Ⅾ   = 500
0x216F: Ⅿ   = 1000
0x2170: ⅰ   = 1
0x2171: ⅱ   = 2
0x2172: ⅲ   = 3
0x2173: ⅳ   = 4
0x2174: ⅴ   = 5
0x2175: ⅵ   = 6
0x2176: ⅶ   = 7
0x2177: ⅷ   = 8
0x2178: ⅸ   = 9
0x2179: ⅹ   = 10
0x217A: ⅺ   = 11
0x217B: ⅻ   = 12
0x217C: ⅼ   = 50
0x217D: ⅽ   = 100
0x217E: ⅾ   = 500
0x217F: ⅿ   = 1000
0x2180: ↀ   = 1000
0x2181: ↁ   = 5000
0x2182: ↂ   = 10000
0x2183: Ↄ   = 100
0x2184: ↄ   = 100
0x2185: ↅ   = 6
0x2186: ↆ   = 50
0x2187: ↇ   = 50000
0x2188: ↈ   = 100000
0x2189: ↉   = 0
0x218A: ↊   = 10
0x218B: ↋   = 11

```

### Test cases:

```
['½','ↆ','ↂ','⅒','Ⅽ','⅑','ⅷ'] -> ['⅒','⅑','½','ⅷ','ↆ','Ⅽ','ↂ']

['¼','↋','↉','ↅ','⅐','⅟','Ⅻ','ⅺ'] -> ['↉','⅐','¼','⅟','ↅ','↋','ⅺ','Ⅻ']

['¼','½','¾','⅐','⅑','⅒','⅓','⅔','⅕','⅖','⅗','⅘','⅙','⅚','⅛','⅜','⅝','⅞','⅟'] -> ['⅒','⅑','⅛','⅐','⅙','⅕','¼','⅓','⅜','⅖','½','⅗','⅝','⅔','¾','⅘','⅚','⅞','⅟']

'⅞ⅾ↊ↄⅨⅮⅺↁⅸⅰⅩⅱⅶ¾ⅧↅↃ↋ↆ⅔ⅼⅲ⅘⅒ⅽⅦ⅕ⅤⅭⅳↂⅪⅬⅯↇⅠⅷ⅛Ⅵ½ⅵ¼ⅻ⅐Ⅱ⅜⅗⅝⅚Ⅳ⅓ⅴ↉ⅿⅫⅹↀↈ⅙⅑Ⅲ⅖⅟' -> '↉⅒⅑⅛⅐⅙⅕¼⅓⅜⅖½⅗⅝⅔¾⅘⅚⅞⅟ⅠⅰⅡⅱⅢⅲⅣⅳⅤⅴⅥⅵↅⅦⅶⅧⅷⅨⅸⅩⅹ↊Ⅺⅺ↋ⅫⅻⅬⅼↆⅭⅽↄↃⅮⅾⅯⅿↀↁↂↇↈ'

['Ↄ','ↄ','↊','↋'] -> ['↊','↋','ↄ','Ↄ']

```

Note that four of the symbols (the ones used in the last case) are not unicode numbers, though they still have a numerical value, so make sure to check before just posting a built-in.

### Rules:

* If any more characters are assigned to this block in the future, you won't need to update your code to support them.
* Order of characters with identical values doesn't matter.
* IO is flexible.
    + Output must be as the characters though, not the numerical values
* Standard Loopholes are forbidden.
* I'm not banning built-ins that can fetch the numerical value of a character, but I encourage also adding a non-builtin answer if possible.
* This is , so shortest answer in bytes for each languages wins! Good luck!

# Answer
> 6 votes
# Python 3, ~~216~~ 213 bytes

<sup>-3 bytes thanks to TFeld</sup>

```
lambda l:sorted(l,key='⅒⅑⅐⅙⅕¼⅓⅖½⅗⅔¾⅘⅚⅟ⅠⅰⅡⅱⅢⅲⅣⅳⅤⅴⅥⅵↅⅦⅶⅧⅷⅨⅸⅩⅹ↊Ⅺⅺ↋ⅫⅻⅬⅼↆⅭⅽↃↄ⅛⅜Ⅾⅾ⅝⅞Ⅿⅿↀↁↂↇↈ'.find)

```

Try it online!

### With built-in that fetch the numerical value, 111 bytes

```
lambda l:sorted(l,key=lambda c:[10,11,100,100,0]['↊↋Ↄↄ'.find(c)]or numeric(c))
from unicodedata import*

```

Try it online!

# Answer
> 4 votes
# 05AB1E (legacy), ~~192~~ ~~74~~ ~~63~~ 61 bytes

```
Σ•Bšā¿ÑáζΔÕæ₅"®GÙ₂®°ƶío"§óÏ4¸bćÔ!₃ùZFúÐìŸ
,λ₂Ï¦P(Ì•65в₂+sÇт%k

```

-118 bytes by using characters of 05AB1E's code page only, so we don't need to use UTF-8 encoding.
-11 bytes thanks to *@Adnan*.
-2 bytes thanks to *@Grimy*.

Try it online or verify all test cases.

**Explanation:**

```
Σ            # Sort the input by:
 •Bšā¿ÑáζΔÕæ₅"®GÙ₂®°ƶío"§óÏ4¸bćÔ!₃ùZFúÐìŸ
 ,λ₂Ï¦P(Ì•65в₂+
             #  List of ASCII values modulo-100 of the characters we want to sort
 sÇ          #  Get the ASCII value of the current input-character
   т%        #  Take modulo 100 of this ASCII value
 k           #  And get the index in the list of ASCII values, as sorting order

```

So what is `•Bšā¿ÑáζΔÕæ₅"®GÙ₂®°ƶío"§óÏ4¸bćÔ!₃ùZFúÐìŸ\n,λ₂Ï¦P(Ì•65в₂+`?

Based on the order of the characters modulo-100 we get the following 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]

```

These are generated by the following program:

```
"↉⅒⅑⅛⅐⅙⅕¼⅓⅜⅖½⅗⅝⅔¾⅘⅚⅞⅟ⅠⅰⅡⅱⅢⅲⅣⅳⅤⅴⅥⅵↅⅦⅶⅧⅷⅨⅸⅩⅹ↊Ⅺⅺ↋ⅫⅻⅬⅼↆⅭⅽↃↄⅮⅾⅯⅿↀↁↂↇↈ"Çт%

```

Try it online.

`•Bšā¿ÑáζΔÕæ₅"®GÙ₂®°ƶío"§óÏ4¸bćÔ!₃ùZFúÐìŸ\n,λ₂Ï¦P(Ì•65в₂+` is a shorter variation of this list by taking the compressed number `1485725021600091112740267145165274006958935956446028449609419704394607952161907963838640094709317691369972842282463`, then converting it to Base-65, and then adding 26 to each.

Try it online and verify that the lists are the same.

# Answer
> 4 votes
# Perl 6, 57 bytes

```
*.sort: {%(<Ↄ 100 ↄ 100 ↊ 10 ↋ 11>){$_}//.unival}

```

Try it online!

Just looks up the four exceptional characters in a hash, or falls back to the built-in `unival` method.

# Answer
> 3 votes
# Japt, 72 bytes

```
ñ@`'%!x("y#) z$&*+,<-=.>/?0@1aq2b3c4d5ev6fw7g8hr9iop:j;klmn¡`u bXcuL

```

Try it or run all test cases

---

## Explanation

```
ñ@                 :Sort by passing each X through a function
  `...`            :  A compressed string, which itself contains a bunch of unprintables (See below for codepoints of original string)
       u           :  Uppercase
         b         :  Index of
          Xc       :   Charcode of X
            uL     :   Mod 100 and get character at that codepoint

```

### Codepoints

```
30,29,39,28,37,33,120,31,40,34,121,35,41,32,122,36,38,42,43,44,60,45,61,46,62,47,63,48,64,49,97,113,50,98,51,99,52,100,53,101,118,54,102,119,55,103,56,104,114,57,105,111,112,58,106,59,107,108,109,110,115,116

```

---

## Original Solution, ~~90~~ ~~89~~ 88 bytes

```
ñ!b`(&" )#$*!%'+,-=.>/?0@1a2br3c4d5e6fw7gx8h9:jpq;k<lmÍ/`®iv u nLõd)dÃi6'¼ iA'½ iE'¾

```

Try it or run all test cases

---

### Explanation

```
   `...`                                :A compressed string, which itself contains a bunch of unprintables (See below for codepoints of original string)
        ®                               :Map
         iv                             :  Prepend "v"
            u                           :  Convert to uppercase
               Lõ                       :  Range [1,100]
                 d                      :  Characters at those codepoints
              n   )                     :  Convert from that base to base-10
                   d                    :  Get the character at that codepoint
                    Ã                   :End map
                     i6'¼               :Insert "¼" at (0-based) index 6
                          iA'½          :Insert "½" at index 10
                               iE'¾     :Insert "¾" at index 14
ñ                                       :Sort the input array
 !b                                     :  By finding the index of the current element in the string above

```

**Codepoints**

```
31,30,40,29,38,34,32,41,35,36,42,33,37,39,43,44,45,61,46,62,47,63,48,64,49,97,50,98,114,51,99,52,100,53,101,54,102,119,55,103,120,56,104,57,105,115,58,106,112,113,59,107,60,108,109,110,111,116,117

```

# Answer
> 3 votes
# Retina, ~~1~~93 bytes (UTF-8)

```
2{O`.
T`¼-¾⅐-↋\LI ^]Q@TU\\[ZYWSPNK\HFDB?=;975X\VR\OMJG\ECA><:86432\-)#1%0,*&.(!"$/+'`Ro

```

Try it online! Explanation: Sorts the characters in code point order, then maps between the numeric characters and ASCII characters so that the numeric characters with the lowest value map the the ASCII characters with the lowest code point and vice versa. Then repeats the exercise, so that the characters are now sorted in order of this ASCII mapping, which corresponds to the desired numeric order, before they are transformed back. Edit: Saved 100 (!) bytes by specifying the order of the ASCII characters rather than the numeric characters.

# Answer
> 3 votes
# Jelly, 55 bytes

```
O%70‘“$Żz*ṀḢD⁹VṢaʠƝ lẹkƝʋ9⁽ƭXmż4#⁺3ç%|ọṢLxƈ⁽}ÞƇ2’Œ?¤iµÞ

```

A monadic link accepting a list of characters which yields a list of characters.

**Try it online!**

### How?

Much simpler than it looks since `“$Żz*ṀḢD⁹VṢaʠƝ lẹkƝʋ9⁽ƭXmż4#⁺3ç%|ọṢLxƈ⁽}ÞƇ2’` is just a large number in base 250 using Jelly's code-page as the digits, I shall use `“...’` in its place.

```
O%70‘“...’Œ?¤iµÞ - Link: list of characters
               Þ - sort by:
              µ  -   the monadic function (i.e. f(character)):
O                -     get the ordinal value of the character
 %70             -     modulo by 70 (get the remainder after dividing by 70)
                 -       - giving integers in [0,69] excluding [52,58]
    ‘            -     increment (below code pattern can't have anything but '↉' map to 0)
            ¤    -     nilad followed by link(s) as a nilad:
     “...’       -       literal 7826363328008670802853323905140295872014816612737076282224746687856347808481112431487214423845098801
          Œ?     -       get the permutation of natural numbers [1,N] with minimal N such
                 -         that this permutation would reside at the given index in a
                 -         sorted list of all permutations of those same numbers
                 -         -> [46,52,53,54,55,56,57,58,61,60,70,59,68,64,49,62,1,65,50,66,2,63,51,67,69,3,4,5,21,6,22,7,23,8,24,9,25,10,26,42,11,27,12,28,13,29,14,30,47,15,31,48,16,32,17,33,43,18,34,40,41,19,35,20,36,37,38,39,44,45]
             i   -     first index of (the ordinal mod 70 plus 1) in that list

```

---

### Aside

Somewhat ironically the nearest to a "use a built-in approach" I could muster was 85 bytes, this uses a compressed string:

```
from unicodedata import*; copy_to( atoms['
'], numeric( atoms['
'].call()))

```

which is split on newlines and joined with s to give the Python code:

```
from unicodedata import*; copy_to( atoms['⁸'], numeric( atoms['⁸'].call()))

```

which is executable within Jelly's interpreter - it will place the Unicode character's numeric value into the left argument nilad,  for later use.

# Answer
> 3 votes
# 05AB1E, ~~56~~ ~~53~~ ~~51~~ ~~50~~ ~~49~~ 48 bytes

```
ΣÇ©1ö•Ω‘~Èr–Õî5®Î¼ÓÂ∍_OûR•42в•мjāl†£•₂°*S>ÅΓ®Íè+

```

Try it online!

At the core of this solution is a compressed list mapping unicode code points to a sorting key. Characters that correspond to the same number are mapped to the same key, so we only need 40 different keys.

70 is the smallest number by which we can modulo all input codepoints and get distinct results. Since indexing in 05AB1E wraps around, we don’t need to explicitly `70%`, just make sure the list is length 70.

Notice that there are long stretches of consecutive code points with consecutive keys. Thus, encoding (key - codepoint) rather than simply (key) gives long stretches of identical numbers, which can be run-length encoded. However, the range of code points is very large (damn those 0xBC .. 0xBE), which would be an issue. So instead of (key - codepoint), we encode (key - sum\_of\_digits(codepoint)), which unfortunately limits the stretch length to 10, but does quite well at reducing the range of encoded values. (Other functions are of course possible, like codepoint % constant, but sum of digits gives the best results).

Additionally, it turns out rotating the list by 2 plays well with run-length encoding, so we subtract 2 from the codepoint before indexing.

```
•Ω‘~Èr–Õî5®Î¼ÓÂ∍_OûR•42в    # compressed list [25, 34, 27, 36, 30, 38, 29, 35, 41, 0, 28, 16, 19, 31, 7, 4, 11, 17, 22, 13, 16, 17, 20, 8, 19, 4, 18, 21]
•мjāl†£•                    # compressed integer 79980000101007
        ₂°*                 # times 10**26
           S                # split to a list of digits
            >               # add 1 to each
             ÅΓ             # run-length decode, using the first list as elements and the second list as lengths

Σ                           # sort by
 Ç©1ö                       # sum of digits of the codepoint
           +                # plus
     ...  è                 # the element of the run-length decoded list
        ®Í                  # with index (codepoint - 2) % 70

```

# Answer
> 2 votes
# JavaScript (SpiderMonkey), 117 bytes

```
a=>a.sort((a,b)=>(g=c=>';<=>GHIJCDEF?@AB/37~15:;8-9+6.24,*)0N(DEH@GMJKLH'[(c.charCodeAt()&127^44)%92%76%60])(a)>g(b))

```

Try it online!

# Answer
> 1 votes
# T-SQL, 207 bytes

```
SELECT*FROM t ORDER BY
CHARINDEX(c,N'⅒⅑⅛⅐⅙⅕¼⅓⅜⅖½⅗⅝⅔¾⅘⅚⅞⅟ⅠⅰⅡⅱⅢⅲⅣⅳⅤⅴⅥ
              ⅵↅⅦⅶⅧⅷⅨⅸⅩⅹ↊Ⅺⅺ↋ⅫⅻⅬⅼↆⅭⅽↃↄⅮⅾⅯⅿↀↁↂↇↈ'COLLATE Thai_BIN)

```

Return in the middle of the string is for readability only. I think I got the byte count correct (3 of the numeric characters are 1-byte, the remainder are 2-bytes), character count is 148.

I pre-sorted the string in ascending order, leaving out  (which returns 0) as suggested by other answers.

Any binary collation will work, I used `Thai_BIN` since it has the shortest name. (A collation in SQL prescribes how character sorting/comparison is done, I need binary so each character only matches itself.)

Per our IO standards, input is taken via pre-existing table **t** with `NCHAR(1)` field **c**.

If you define the input table itself using a binary collation, you can leave that out to save 16 bytes:

```
CREATE TABLE t(c NCHAR(1) COLLATE Thai_BIN)

```

# Answer
> 1 votes
# Ruby, 77 bytes

Changes all the characters to letters that represent the numerical values and sorts by that.

```
->a{a.sort_by{|e|e.tr'¼-¾⅐-↋','HLPECBIOGKMQFRDJNSaa-pa-ppqrnnfmstAjk'}}

```

Try it online!

# Answer
> 1 votes
# Perl 6, ~~13~~ 52 bytes

```
*.sort:{%(<Ↄ 99 ↄ 99 ↊ 10 ↋ 11>){$_}//.EVAL}

```

Try it online!

---
Tags: code-golf, sorting, unicode
---


title: Densely packed decimal (DPD) to decimal

text:
# Question
Title: Densely packed decimal (DPD) to decimal
> For nandgame fans: Please try out DPD to decimal in logic gates too!

## Background

Densely packed decimal (DPD) is a way to efficiently store decimal digits in binary. It stores three decimal digits (000 to 999) in 10 bits, which is much more efficient than naive BCD (which stores one digit in 4 bits).

### Notations

* The lowercase letters `a` to `i` are the bits that are copied to the decimal representation.
* `0` and `1` are the exact bits in the input or output bit patterns.
* `x` bits are ignored in the conversion.

### Conversion table

The following is the conversion table from 10 bits of DPD to three decimal digits. Each decimal digit is represented as 4-bit binary (BCD). Both sides are written left to right from the most significant digit to the least.

```
Bits                 =>  Decimal         (Digit range)
a b c d e f 0 g h i  =>  0abc 0def 0ghi  (0-7) (0-7) (0-7)
a b c d e f 1 0 0 i  =>  0abc 0def 100i  (0–7) (0–7) (8–9)
a b c g h f 1 0 1 i  =>  0abc 100f 0ghi  (0–7) (8–9) (0–7)
g h c d e f 1 1 0 i  =>  100c 0def 0ghi  (8–9) (0–7) (0–7)
g h c 0 0 f 1 1 1 i  =>  100c 100f 0ghi  (8–9) (8–9) (0–7)
d e c 0 1 f 1 1 1 i  =>  100c 0def 100i  (8–9) (0–7) (8–9)
a b c 1 0 f 1 1 1 i  =>  0abc 100f 100i  (0–7) (8–9) (8–9)
x x c 1 1 f 1 1 1 i  =>  100c 100f 100i  (8–9) (8–9) (8–9)

```

## Task

Convert 10 bits of DPD to 3 digits of decimal.

## Test cases

```
DPD           Decimal
0000000101    005
0001100011    063
0001111001    079
0000011010    090
0001011110    098
1010111010    592
0011001101    941
1100111111    879
1110001110    986
0011111111    999
1111111111    999  * Output is same regardless of the `x` bits

```

## Input

The default input format is a list of 10 bits. The bits should follow the exact order above, or the reverse of it. You may choose to use an equivalent string or integer representation instead. Unlike my other challenges, **reordering or using nested structures is not allowed**.

For the input `[1, 1, 0, 0, 0, 1, 0, 1, 0, 0]`, the following formats are allowed:

* List of bits: `[1, 1, 0, 0, 0, 1, 0, 1, 0, 0]`
* String: `"1100010100"`
* Binary integer: `788` or `0b1100010100`
* Decimal integer: `1100010100`
* Reversed: `[0, 0, 1, 0, 1, 0, 0, 0, 1, 1]` and reversed in any other formats above

The following formats are NOT allowed:

* Arbitrary reordering of bits: `[0, 0, 0, 0, 0, 1, 1, 1, 0, 1]`
* Nested structures: `[[1, 1, 0], [0, 0, 1], [0, 1, 0, 0]]` or `[0b110, 0b001, 0b0100]`

## Output

The default output format is a list of 3 decimal digits. Each digit should be represented as 0 to 9, either an integer or a character. As in input, you can choose string or integer representation. If you choose integer representation, leading zeroes can be omitted.

## Scoring & winning criterion

Standard rules apply. The shortest program or function in bytes for each language wins.

# Answer
# JavaScript (ES6), 112 bytes

*All credit for this shorter version goes to @nwellnhof.*

Takes input as an integer. Returns an array of three decimal digits.

```
n=>[(x=n>>4,y=x>>3,q=n/2&55,p=q%8)>5&&q-39?8|y&1:y,(p&5^5?x&6:q-23?8:y&6)|x&1,(p<5?p*2:p<6?x&6:p%q<7?y&6:8)|n&1]

```

Try it online!

---

# JavaScript (ES6), ~~118~~ 117 bytes

Takes input as an integer. Returns an array of three decimal digits.

```
n=>[(x=n>>4&7,y=n>>7,p=n/2&7)>5&&p<7|x/2^2?8|y&1:y,(p<7?p-5?x:8:x/2^1?8:y&6)|x&1,(p<5?p*2:p<6?x&6:p<7|x<2?y&6:8)|n&1]

```

Try it online!

## How?

Instead of trying to apply the 'official' algorithm, this code is based on some kind of reverse-engineering of the patterns that can be found in the expected results.

Given the input integer \\$n\\$, we compute:

$$\begin{align}&x=\left\lfloor\frac{n}{16}\right\rfloor \bmod 8\\ &y=\left\lfloor\frac{n}{128}\right\rfloor\\ &p=\left\lfloor\frac{n}{2}\right\rfloor \bmod 8\end{align} $$

### Example: first digit (hundreds)

```
x     | 0                | 1                | 2                | 3
n & 1 | 0101010101010101 | 0101010101010101 | 0101010101010101 | 0101010101010101
p     | 0011223344556677 | 0011223344556677 | 0011223344556677 | 0011223344556677
------+------------------+------------------+------------------+-----------------
y = 0 | 0000000000008888 | 0000000000008888 | 0000000000008888 | 0000000000008888
y = 1 | 1111111111119999 | 1111111111119999 | 1111111111119999 | 1111111111119999
y = 2 | 2222222222228888 | 2222222222228888 | 2222222222228888 | 2222222222228888
y = 3 | 3333333333339999 | 3333333333339999 | 3333333333339999 | 3333333333339999
y = 4 | 4444444444448888 | 4444444444448888 | 4444444444448888 | 4444444444448888
y = 5 | 5555555555559999 | 5555555555559999 | 5555555555559999 | 5555555555559999
y = 6 | 6666666666668888 | 6666666666668888 | 6666666666668888 | 6666666666668888
y = 7 | 7777777777779999 | 7777777777779999 | 7777777777779999 | 7777777777779999

x     | 4                | 5                | 6                | 7
n & 1 | 0101010101010101 | 0101010101010101 | 0101010101010101 | 0101010101010101
p     | 0011223344556677 | 0011223344556677 | 0011223344556677 | 0011223344556677
------+------------------+------------------+------------------+-----------------
y = 0 | 0000000000008800 | 0000000000008800 | 0000000000008888 | 0000000000008888
y = 1 | 1111111111119911 | 1111111111119911 | 1111111111119999 | 1111111111119999
y = 2 | 2222222222228822 | 2222222222228822 | 2222222222228888 | 2222222222228888
y = 3 | 3333333333339933 | 3333333333339933 | 3333333333339999 | 3333333333339999
y = 4 | 4444444444448844 | 4444444444448844 | 4444444444448888 | 4444444444448888
y = 5 | 5555555555559955 | 5555555555559955 | 5555555555559999 | 5555555555559999
y = 6 | 6666666666668866 | 6666666666668866 | 6666666666668888 | 6666666666668888
y = 7 | 7777777777779977 | 7777777777779977 | 7777777777779999 | 7777777777779999

```

Algorithm:

* If \\$p\<6\\$, we have \\$d=y\\$
* If \\$p=6\\$, we have \\$d=8+(y\bmod2)\\$
* If \\$p=7\text{ AND }(x\<4\text{ OR }x\>5)\\$, we have \\$d=8+(y\bmod2)\\$
* If \\$p=7\text{ AND }(x=4\text{ OR }x=5)\\$, we have \\$d=y\\$

As JS code:

```
p > 5 && p < 7 | x / 2 ^ 2 ? 8 | y & 1 : y

```
> 12 votes

# Answer
# JavaScript (Node.js), ~~126~~ ~~119~~ ~~117~~ ~~112~~ 111 bytes

```
(a,b,c,d,e,f,g,h,i,j)=>[(g&h&i+(b+=a*4+b,e+=d*4+e)!=5?8:b)+c,(g&i?h+e-3?8:b:e)+f,(g?h<i?e:h>i*e?b:8:h*4+i*2)+j]

```

Try it online!

**-5 bytes thanks @tsh** (and 2 by myself) So `l` can make more effort than I expected.

**-2 more bytes using @tsh's technique!**

**-5 bytes thanks @Arnauld**

**-1 byte thanks @Neil**

Input as a list of 10 bits (as 10 arguments), output as a list of 3 digits.
> 10 votes

# Answer
# Python 3, ~~229 ... 97~~ 96 bytes

```
lambda a:[[a&6,a>>4&6,a>>7&6,8][b"  eW7B]Oys"[~a&8or~a&6or~6|a>>4]%x&3]|a>>x%9&1for x in[7,4,9]]

```

Try it online!

*-4 bytes by @xnor*

*-6 bytes by @nwellnhof*

Formatted:

```
h = lambda a:[
    [a&6, a>>4&6, a>>7&6, 8][              List to take high bits from
        b"  eW7B]Oys"[                     10 char string; where to get high bits for
                                             indicator values 1-8. 0th,1st chars not used.
            ~a&8 or ~a&6 or ~6|a>>4]       Compute indicator (by @nwellnhof)
        %x&3]                              High bits of each digit
    | a >> x%9 & 1                         bitwise OR with low bit of each digit
    for x in [7,4,9]]

```

### Explanation

Because I originally wanted to implement this in Jelly, I take a different approach from most answers here, which is simple and perhaps suited to a golfing language. Though the golfed function takes an integer, let the input as a bit list be `[a0,a1,...,a9]`. Then we can derive three values from the input

* The low bits `[a2,a5,a9]`: These will always be the low bits of `[d0,d1,d2]` respectively.
* The high bits `[2*a0a1,2*a3a4,2*a7a8,8]`: The high bits of each digit will be one of these.
* The indicator bits, `[a3,a4,a5,a7,a8]`, determining how to get the high bits of each digit. We compute the indicator (between 1 and 8) as follows:
    + If a5 == 0, the indicator is 8 (originally 0, but using 8 instead saves a byte)
    + If a3 nand a4, the indicator is 6 - 2\*a3a4
    + Otherwise the indicator is 2\*a7a8 + 1 (actually calculated as a negative number).

Then the nth digit can be elegantly computed as `high_bits[arr[indicator][n]] | low_bits[n]` by the table below, which is compressed into a string.

```
arr = [
    [0,1,2],
    [3,1,2],
    [1,3,2],
    [2,1,3],
    [2,3,3],
    [3,2,3],
    [3,3,2],
    [3,3,3]
]

```
> 10 votes

# Answer
# C (gcc), ~~138~~ 129 bytes

```
f(w){int t=w/2&55,s=t%8,v=w/16,u=v/8;w=((s<6|t==39?u:8|u%2)*10+v%2+(s&5^5?v&6:t-23?8:u&6))*10+w%2+(s<5?s*2:s<6?v&6:s%t<7?u&6:8);}

```

Try it online!

First extracts some bits into variables `s` and `t`, so that the eight rows of the conversion table can be identified by:

```
1.  s < 4              u v w¹
2.  s = 4              u v 8¹
3.  s = 5              u 8 v
4.  s = 6              8 v u
5.  s = 7, t =  7      8 8 u
6.  s = 7, t = 23      8 u 8
7.  s = 7, t = 39      u 8 8
8.  s = 7, t = 55      8 8 8

¹ Can be computed with s*2

```

Then sets up `u` and `v` with divisions (right shifts), so that `u`, `v` and the input `w` contain the lower three BCD bits in positions 0-2. The rest is bit shuffling depending on `s` and `t`. Two notable tricks are:

```
s&5^5  // Rows 1, 2 and 4.
s%t<7  // Rows 1-5.

```

A port of Shieru Asakoto's Javascript solution is only **124 bytes**:

```
f(a,b,c,d,e,f,g,h,i,j){a=(((g&h&i+(b+=a*4+b,e+=d*4+e)!=5?8:b)+c)*10+(g&i?h+e-3?8:b:e)+f)*10+(g?h-i|h&!e?h?b:e:8:h*4+i*2)+j;}

```

Try it online!
> 8 votes

# Answer
# Ruby, ~~153 ... 119~~ 117 bytes

```
->n{n+=n&896;a,b,c=n&1536,n&96,n&14;"%x"%n+=c<9?0:2036+[b/16-b-1918,r=a>>8,[r+126,a/16-26,a-1978,38][b/32]-a][c/2-5]}

```

Try it online!

### How it works:

```
->n{n+=n&896;

```

This is the starting point: convert to BCD by shifting 3 bits to the left, which works for most of the patterns.

```
a,b,c=n&1536,n&96,n&14;

```

Get the middle bits of each nibble (and one extra bit of the third nibble, but mask the least significant bit).

```
"%x"%n+=c<9?0

```

If the third digit is less than 10 (less than 9 because we never cared for the LSB anyway), we're set: this is plain BCD, we can output the hex without changing anything

```
:2036+[b/16-b-1918,r=a>>8,[r+126,a/16-26,a-1978,38][b/32]-a][c/2-5]}

```

Otherwise do some black magic by shifting bits around and adding magic numbers until we get the result we want.
> 6 votes

# Answer
# Jelly, ~~51~~ ~~48~~ ~~40~~ 39 bytes

```
&\‘f4;s3ɓạ4ḅ-œ?µ/Ḥ
“MY-€-Y¤©¡‘Dịs3Ḅç+ƭ/

```

Try it online!

### Algorithm

With the exception of list indices, all integers in this section are written in binary.

Given input \\$\alpha\beta\gamma\delta\varepsilon\zeta\eta\theta\iota\kappa\\$, we first construct the arrays \\$\[\eta\eta, \theta\iota, \delta\varepsilon\]\\$, \\$\[\alpha\beta, \delta\varepsilon, \theta\iota\]\\$, and \\$\[\gamma, \zeta, \kappa\]\\$.

1. If \\$\eta\eta = 00\\$, all three output digits are low (\\$0000\\$ to \\$0111\\$).
2. If \\$\eta\eta = 11\\$ but \\$\theta\iota \< 11\\$, exactly one output digit is high (\\$1000\\$ or \\$1001\\$).
3. If \\$\eta\eta = \theta\iota = 11\\$ but \\$\delta\varepsilon \< 11\\$, exactly two output digits are high.
4. If \\$\eta\eta = \theta\iota = \delta\varepsilon = 11\\$, all three output digits are high.

If we count the number of leading \\$11\\$'s \\$\[\eta\eta, \theta\iota, \delta\varepsilon\]\\$, create an array of a matching number of \\$100\\$'s, concatenate it with \\$\[\alpha\beta, \delta\varepsilon, \theta\iota\]\\$, and split the result into subarrays of length three, we get the following results in each case.

1. \\$\[\[\alpha\beta, \delta\varepsilon, \theta\iota\]\]\\$
2. \\$\[\[100, \alpha\beta, \delta\varepsilon\], \[\theta\iota\]\]\\$
3. \\$\[\[100, 100, \alpha\beta\], \[\delta\varepsilon, \theta\iota\]\] = \[\[100, 100, \alpha\beta\], \[\delta\varepsilon, 11\]\]\\$
4. \\$\[\[100, 100, 100\], \[\alpha\beta, \delta\varepsilon, \theta\iota\]\] = \[\[100, 100, 100\], \[\alpha\beta, 11, 11\]\]\\$

In the first and last case, we just have to zip the first array with \\$\[\gamma, \zeta, \kappa\]\\$, yielding \\$\[\alpha\beta\gamma, \delta\varepsilon\zeta, \theta\iota\kappa\]\\$ in the first case and \\$\[100\gamma, 100\zeta, 100\kappa\]\\$ in the last.

The remaining two cases are similar, but the arrays \\$\[100, \alpha\beta, \delta\varepsilon\]\\$ and \\$\[100, 100, \alpha\beta\]\\$ have to be reordered, according on the values of \\$\[\theta\iota\]\\$ and possibly \\$\delta\varepsilon\\$.

In the second case, the six permutations of \\$\[100, \alpha\beta, \delta\varepsilon\]\\$ are \\$\[100, \alpha\beta, \delta\varepsilon\]\\$, \\$\[100, \delta\varepsilon, \alpha\beta\]\\$, \\$\[\alpha\beta, 100, \delta\varepsilon\]\\$, \\$\[\alpha\beta, \delta\varepsilon, 100\]\\$, \\$\[\delta\varepsilon, 100, \alpha\beta\]\\$, and \\$\[\delta\varepsilon, \alpha\beta, 100\]\\$.

By computing \\$100-\theta\iota\\$, we map \\$00\\$, \\$01\\$, and \\$10\\$ to four, three and two, selecting the permutations \\$\[\alpha\beta, \delta\varepsilon, 100\]\\$, \\$\[\alpha\beta, 100, \delta\varepsilon\]\\$, and \\$\[100, \delta\varepsilon, \alpha\beta\]\\$.

After zipping the result with \\$\[\gamma, \zeta, \kappa\]\\$, we get \\$\[\alpha\beta\gamma, \delta\varepsilon\zeta, 100\kappa\]\\$, \\$\[\alpha\beta\gamma, 100\zeta, \delta\varepsilon\kappa\]\\$, or \\$\[100\gamma, \delta\varepsilon\zeta, \alpha\beta\kappa\]\\$.

In the third case, the permutations (with duplicates) of \\$\[100, 100, \alpha\beta\]\\$ are \\$\[100, 100, \alpha\beta\]\\$, \\$\[100, \alpha\beta, 100 \]\\$, \\$\[100, 100, \alpha\beta\]\\$, \\$\[100, \alpha\beta, 100 \]\\$, \\$\[\alpha\beta, 100, 100\]\\$ and \\$\[\alpha\beta, 100, 100\]\\$.

By computing \\$(100 - \theta\iota) - (100 - \delta\varepsilon) = \delta\varepsilon - \theta\iota = \delta\varepsilon - 11\\$, we map \\$00\\$, \\$01\\$, and \\$10\\$ to three, four, and five modulo six, selecting the permutations \\$\[100, 100, \alpha\beta\]\\$, \\$\[100, \alpha\beta, 100 \]\\$, and \\$\[\alpha\beta, 100, 100\]\\$.

After zipping the result with \\$\[\gamma, \zeta, \kappa\]\\$, we get \\$\[100\gamma, 100\zeta, \alpha\beta\kappa\]\\$, \\$\[100\gamma, \alpha\beta\zeta, 100\kappa\]\\$, or \\$\[\alpha\beta\gamma, 100\zeta, 100\kappa\]\\$.

### Code

```
“MY-€-Y¤©¡‘Dịs3Ḅç+ƭ/  Main link. Argument: A (array of 10 bits)

“MY-€-Y¤©¡‘           Array literal; yield [77, 89, 45, 12, 45, 89, 3, 6, 0].
           D          Decimal; yield
                      [[7,7], [8,9], [4,5], [1,2], [4,5], [8,9], [3], [6], [0]].
            ị         Retrieve the elements of A at those indices.
                      Indexing is 1-based and modular, so 1 is the first index, while
                      0 is the last.
             s3       Split the results 2D array of bits into chunks of length 3.
               Ḅ      Convert the 9 arrays of bits from binary to integer.
                ç+ƭ/  Reduce the resulting array (length 3) once by the helper link,
                      then by addition.

&\‘f4;s3ɓạ4ḅ-œ?µ/Ḥ    Helper link. Arguments: B, C (arrays of three integers each)

&\                    Cumulatively reduce B by bitwise AND.
  ‘                   Increment the results by 1.
   f4                 Filter; keep only integers equal to 4.
     ;                Concatenate the result with C.
      s3              Split the result into (one or two) chunks of length 3.
        ɓ      µ/     Reduce the array of chunks by the following chain.
         ạ4               Take the absolute difference of the integers in the right
                          chunk and the integer 4.
           ḅ-             Convert the resulting array from base -1 to integer, i.e.,
                          map [x] to n = x and [x, y] to n = y - x.
             œ?           Take the n-th permutation of the left chunk.
                 Ḥ    Unhalve; multiply the resulting integers by 2.

```
> 6 votes

# Answer
# Retina 0.8.2, ~~191~~ 181 bytes

```
(...)(...)
:$1,$2;
..(.),11(.);111
100$1,100$2;100
(10|(..)(.,)01)(.);111
100$3$2$4;100
(..)(.),(00.);111
100$2,1$3;0$1
(..)((.{5});110|(.);101)
100$3$4;$1
1
01
+`10
011
.0+(1*)
$.1

```

Try it online! Link includes test cases. Edit: Saved 10 byte by not padding digits to 4 bits except where necessary. Explanation:

```
(...)(...)
:$1,$2;

```

Insert separators so that each digit can be converted to decimal separately. This effectively handles the first two cases in the conversion table.

```
..(.),11(.);111
100$1,100$2;100

```

Handle the last (eighth) case in the conversion table.

```
(10|(..)(.,)01)(.);111
100$3$2$4;100

```

Handle the sixth and seventh cases in the conversion table.

```
(..)(.),(00.);111
100$2,1$3;0$1

```

Handle the fifth case in the conversion table.

```
(..)((.{5});110|(.);101)
100$3$4;$1

```

Handle the third and fourth cases in the conversion table.

```
1
01
+`10
011
.0+(1*)
$.1

```

Perform binary to decimal conversion.
> 5 votes

# Answer
# Python 2, 157 bytes

```
lambda a,b,c,d,e,f,g,h,i,j:[c+[a*4+b*2,8][g*h*~(d*~e*i)],f+[d*4+e*2,8,a*4+b*2][g*i+(d<e)*g*i*h],j+[h*4+i*2,[8,[a*4+b*2,d*4+e*2][h<i]][h^i or(h&i-(d|e))]][g]]

```

Try it online!
> 2 votes

# Answer
# Clean, ~~238~~ ... 189 bytes

*-2 bytes thanks to Neil*

```
import StdEnv
$a b c d e f g h i j=100*(c+2*b+4*a)+10*(f+2*e+4*d)+j+2*i+4*h-2*(h*(99*b+198*a-394)+i*(9*e+18*d+h*(e+2*d-4+(b+2*a-4)*(1-10*e-100*d+110*e*d))-35)-4)*g+0^(e+d)*(2*b+4*a-8*i*h*g)

```

Try it online!

Takes a 'list' of 10 bits in the form of 10 arguments, using a direct formula to compute the result.
> 2 votes

# Answer
# Perl 5, 195 bytes

```
sub f{$n=shift;@p=((map{($n>>$_&3)*2}(8,5,1)),8);for(16390,28935,29005,227791,29108,225788,226803,228863){return 2*$n&256|$n&17|$p[$_>>4&3]<<8|$p[$_/4&3]<<4|$p[$_&3]if($_>>12&$n/2)==($_>>6&63);}}

```

Try it online

I know 195 bytes is far too much for this contest, but I had no idea how to further compress the Perl code. Suggestions?

## Explanation of the code

In a more readable version, the code intention should become apparent:

```
sub dpd {
  my $n = shift;
  my $v=2*($n&128)|$n&17;
  my @p=((map{($n>>$_&3)*2}(8,5,1)),8);
  for (16390,28935,29005,227791,29108,225788,226803,228863) {
    return $v |$p[$_>>4&3]<<8|$p[$_>>2&3]<<4|$p[$_&3]
      if(($_>>12&$n/2)==($_>>6&63));
  }
}

```

In the rules for DPD encoding, each line is encoded into a 18 bit value, segmentation into (6,6,(2,2,2)) bits.

* The first 6 bits are an appropriate bit mask for the bits 1 (=h) to 6 (=d) of the input (bit 4 = f is redundant, but it simplifies the evaluation code to have it included).
* The next 6 bits are the value bits for this bit mask. The values are checked on all places where the bit mask has a 1 value.
* The following 3\*2 bits contain the indices for the array `@p` for the 3-bit sequences which are to spliced into bits 11-9, 7-5 and 3-1 of the result.
* The array `@p` is constructed from bits 9-8, 6-5, 3-2 of the input, and the number `8` as fourth member
* The bits at position 7,4 and 0 of the input are transferred directly into bits 8,4 and 0 of the result.

For example, the first number in the list, `16390`, which is `100000000000110` as a bit field, carries the following information:

```
000100 : bit mask says: only consider bit 3 of the input
000000 : bit values say: bit 3 should be 0
00     : use '0ab' as higher bits of first digit
01     : use '0de' as higher bits of second digit
10     : use '0gh' as higher bits of third digit

```
> 1 votes

# Answer
# 05AB1E, 84 bytes

Port of KimOyhus' answer to 05AB1E.

```
•4’7þ2Ô€iΘEuĆΣk4Ð€:ΘΛs‡CaΔʒì₁3¶rdiMß¡þи иø-˜)Â∍DY—WûQ@—Mā}Γ¤ÒÙ]p•44в2ôvÐyèP≠«}4ôC3.£

```

Try it online!

Rough explanation:

```
•yadayada•44в2ô   # encoded list of nand gates
v                 # for each gate
 ÐyèP≠            # compute the output of the gate
      «           # append it to the input
       }          # end of the loop
4ô                # split the list of bits in groups of 4
  C               # convert each from binary to decimal
   3.£            # keep the last 3 numbers
                  # implicit output

```
> 1 votes

# Answer
# 05AB1E, ~~104~~ ~~103~~ 101 bytes

```
•3γã•S£©4èUXтÌ‹XSPVY®2èDˆTQ*~i0®нëт}®1èY¯`*i0®нëY_Xт>Ê*i0¯`ëт]®3èY¯`_*X110Q~i0®нëXт›iYiтë0¯`ëX]®θJ4ôC

```

Definitely not the right language for this kind of challenge, but ah well..
Input as string, output as list of three digits.

Try it online or verify all test cases.

**Explanation:**

We have the following eight scenarios to consider:

```
     1st 2nd 3rd 4th 5th 6th                          1st digit    2nd digit    3rd digit
1.   ab  c   de  f   0gh i   →   0abc 0def 0ghi   →   '0'+1st 2nd  '0'+3rd 4th  5th     6th
2.   ab  c   de  f   100 i   →   0abc 0def 100i   →   '0'+1st 2nd  '0'+3rd 4th  5th     6th
3.   ab  c   gh  f   101 i   →   0abc 100f 0ghi   →   '0'+1st 2nd  '100'   4th  '0'+3rd 6th
4.   gh  c   de  f   110 i   →   100c 0def 0ghi   →   '100'   2nd  '0'+3rd 4th  '0'+1st 6th
5.   gh  c   00  f   111 i   →   100c 100f 0ghi   →   '100'   2nd  '100'   4th  '0'+1st 6th
6.   de  c   01  f   111 i   →   100c 0def 100i   →   '100'   2nd  '0'+1st 4th  '100'   6th
7.   ab  c   10  f   111 i   →   0abc 100f 100i   →   '0'+1st 2nd  '100'   4th  '100'   6th
8.   xx  c   11  f   111 i   →   100c 100f 100i   →   '100'   2nd  '100'   4th  '100'   6th

```

I first split the (implicit) input into chunks of size `[2,1,2,1,3,1]` and store that list in the register:

```
•3γã•     # Push compressed integer 212131
     S    # Convert it to a list of digits
      £   # Split the (implicit) input in chunks of that size
       ©  # Store it in the register (without popping)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•3γã•` is `212131`

Now we're first going to built the 0s and 1s for the first digit of the output. Scenarios 1,2,3,7 use `'0'+1st+2nd`; and scenarios 4,5,6,8 use `'100'+2nd`:

```
4è                  # Take the 5th item of the list
  U                 # Pop and store it in variable `X`
XтÌ‹                #  Check if `X` is below 102
                ~   # OR
   XSP              #  `X` is equal to 111
      VY            #  And store that result in variable `Y`
               *    #  and
        ®2è         #  Get the 3rd item from the list of the register
           Dˆ       #  Push it to the global array
             TQ     #  And check if it's equal to 10
i                   # If the combined check above is truthy (exactly 1):
 0                  #  Push 0 to the stack
 ®н                 #  Push the 1st item of the list to the stack
ë                   # Else:
 т                  #  Push 100 to the stack
}                   # Close the if-else
®1è                 # And push the 2nd item of the list to the stack

```

Then we're going to built the 0s and 1s for the second digit of the output. Scenarios 1,2,4 use `'0'+3rd+4th`; scenarios 3,5,7,8 use `'100'+4th`; and scenario 6 uses `'0'+1st+4th`:

```
Y                # Push `Y` (check if `X` equals 111)
   *             # and
 ¯`              # Push the item from the global array (3rd item of the list)
i                # If both checks above are truthy (exactly 1):
 0               #  Push 0 to the stack
 ®н              #  Push the 1st item of the list to the stack
ë                # Else:
 Y_              #  Push inverted `Y` (check if `X` does NOT equal 111)
       *         #  and
   Xт>Ê          #  Check if `X` (5th item of the list) does NOT equal 101
 i               #  If both checks above are truthy (exactly 1):
  0              #   Push 0 to the stack
  ¯`             #   Push the item from the global array (3rd item of the list)
 ë               #  Else:
  т              #   Push 100 to the stack
]                # Close both if-else cases
®3è              # And push the 4th item of the list to the stack

```

Then we're going to built the 0s and 1s for the third digit of the output. Scenarios 1,2 use `5th+6th`; scenario 3 uses `'0'+3rd+6th`; scenarios 4,5 use `'0'+1st+6th`; and scenarios 6,7,8 use `'100'+6th`:

```
Y           #  Push `Y` (check if `X` equals 111)
    *       #  and
 ¯`_        #  Check if the item from the global array (3rd item of the list) is exactly 0
         ~  # OR
    X110Q   #  Check if `X` (5th item of the list) equals 110
i           # If the combined check above is truthy (exactly 1):
 0          #  Push 0 to the stack
 ®н         #  Push the 1st item of the list to the stack
ë           # Else:
 Xт›i       #  If `X` (5th item of the list) is larger than 100 (so 101/110/111):
     Yi     #   If `Y` (if `X` equals 111):
       т    #    Push 100 to the stack
      ë     #   Else:
       0    #    Push 0 to the stack
       ¯`   #    Push the item from the global array (3rd item of the list)
    ë       #  Else:
     X      #   Push `X` (5th item of the list) to the stack
]           # Close all if-else cases
®θ          # And push the last (6th) item of the list to the stack

```

Now we have all 0s and 1s on the stack, so we can convert it to the three output digits:

```
J     # Join the entire stack together
 4ô   # Split it into parts of size 4
   C  # Convert each part from binary to an integer (and output implicitly)

```
> 0 votes

---
Tags: code-golf, binary, conversion
---


# Question
Title: Convert a number into "bracket" numerals
"Bracket" numerals are a type of 'numerals' I made up once, and thought would be a nice challenge here. Basically, you convert the input number into base 6, and then transliterate the `012345` respectively with `()[]{}`, so every `0` becomes `(`, every `1` becomes `)`, etc.
You don't have to use `()[]{}` per se. As long as you specify what characters you use, you can use any other characters (except for digits, otherwise *just* converting to base-6 would have been enough!)

Since this is tagged , the score is in bytes, where the least amount of bytes wins.

A few examples: 6 = `)(`. 100200 = `[(})}[(`. 44790 = `}{][)(`.

Here is some lengthy JavaScript code which accomplishes what I described above. Since it's a snippet (using variable `x`) instead of a function or full program, it isn't valid however:

```
var [x,q,w] = [0,0,0];q = x.toString('6');w = q.replace(/0/g, '(');q = w.replace(/1/g, ')');w = q.replace(/2/g, '[');q = w.replace(/3/g, ']');w = q.replace(/4/g, '{');q = w.replace(/5/g, '}');console.log(q);

```

Yes, that is 207 bytes. You probably can do better! I will accept an answer on June 1st, 2019, but you can continue to post answers afterwards of course.

Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. So you aren't allowed to have a `var x` like I did in my example JavaScript snippet.
Default Loopholes are forbidden.

# Answer
> 3 votes
# Japt, 4 bytes

Uses `[objec`.

```
s6îM

```

Try it

## Alternative 4 bytes

Uses the (unprintable) characters at codepoints `1-6`.

```
s6õd

```

Try it

Or, if that's not allowed:

### 5 bytes

Using `!"#$%&`.

```
s6õdH

```

Try it

Or, also (using `wander`):

```
s`æ`â

```

Try it

If I can figure out a 6 letter word that Shoco can compress to a single character then that last one can be golfed to 3 bytes.

# Answer
> 1 votes
# 05AB1E, ~~11~~ ~~10~~ ~~5~~ 4 bytes

All three programs below will return a list of characters instead of a joined string.

```
žOÅв

```

Uses `aeiouy` instead of `()[]{}` for `0123456` respectively.

Try it online.

---

Answers which actually use `()[]{}`:

**~~11 10~~ 8 bytes**:

```
žu„<>мÅв

```

Try it online

**8 bytes alternative by *@Grimy***:

```
…([{º{Åв

```

Try it online.

**Explanation:**

```
žO        # Push string builtin "aeiouy"
  Åв      # Convert the (implicit) input to this custom base-"aeiouy"
          # (which is output implicitly as result)

žu        # Push string builtin "()<>[]{}"
  „<>м    # Remove the "<>" from this string: "()[]{}"
      Åв  # Convert the (implicit) input to this custom base-"()[]{}"
          # (which is output implicitly as result)

…([{      # Push string "([{"
    º     # Mirror it vertically to "([{}])"
     {    # Sort the characters in the string: "()[]{}"
      Åв  # Convert the (implicit) input to this custom base-"()[]{}"
          # (which is output implicitly as result)

```

# Answer
> 1 votes
# JavaScript (ES6),  ~~36~~  34 bytes

*Saved 2 bytes thanks to @Shaggy*

Character set: `[`,`o`,`b`,`j`,`e` and `c`.

```
f=n=>(n>5?f(n/6|0):'')+({}+0)[n%6]

```

Try it online!

# Answer
> 1 votes
# Bash, ~~65~~ ~~63~~ 60 bytes

Using STDIN and not command line arguments:

```
while read n;do echo "obase=6;$n"|bc|tr 012345 '()[]{}';done

```

Try it online!

# Answer
> 1 votes
# Charcoal, 8 bytes

```
⍘Ｎ()[]{}

```

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

```
 Ｎ          Input as a number
⍘           Base convert using specified characters
  ()[]{}    Literal string of required characters

```

5 bytes using the letters `a-f` (or `A-F` also works):

```
⍘Ｎ…β⁶

```

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

```
 Ｎ      Input as a number
⍘       Base convert using
  … ⁶   First six characters of
   β    Lowercase alphabet

```

# Answer
> 0 votes
# Wolfram Language (Mathematica), 64 bytes

```
#~IntegerDigits~6/.Table[k->StringTake["()[]{}",{k+1}],{k,0,5}]&

```

Try it online!

# Answer
> 0 votes
# PHP, 53 bytes

```
<?=strtr(base_convert($argn,10,6),'012345','()[]{}');

```

Try it online!

I'll be honest, I still don't understand the bonus, but here's a PHP version.

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 47 bytes

```
n=>m=>{do m[0]+="()[]{}"[n%6];while((n/=6)>0);}

```

Try it online!

# Answer
> 0 votes
# Jelly, 3 bytes

```
ṃØỵ

```

Try it online!

Uses ‘aeiouy’ for ‘01235’.

# Answer
> 0 votes
# APL (Dyalog Extended), 13 bytes

```
'()[]{}'⊇⍨6∘⊤

```

Try it online!

Pretty straightforward tacit function. Test cases used are 15 randomly selected integers between 0 and 999.

Uses `⎕IO←0`.

Thanks to @Adám for 2 bytes

### How:

```
'()[]{}'⊇⍨6∘⊤ ⍝ Tacit function
          6∘⊤ ⍝ Convert input to base 6
        ⊇     ⍝ Index the right argument with the indices in the left argument
         ⍨    ⍝ With arguments swapped
'()[]{}'      ⍝ Character vector

```

# Answer
> 0 votes
# Ruby, 28 bytes

Uses `abcdef` in place of `012345`.

```
->x{x.to_s(6).tr'0-5','a-f'}

```

Try it online!

---
Tags: code-golf, number, base-conversion
---