title: Transpile ;# into your language

text:
# Question
Title: Transpile ;# into your language
Related to: Make a ;# interpreter and Generate ;# code

## `;#` \- A Whirlwind Guide

This is a simple language with two commands. Its only data structure is an accumulator, which is initialized to 0.

1. **`;`** Increment the accumulator
2. **`#`** Calculate the value of the accumulator modulo 127, and print the corresponding ASCII character. Then, reset the accumulator to 0.

The source code may contain additional characters (printable ASCII + whitespace), but these are treated as comments and have no effect on program execution.

## Challenge

Since most computers do not come with `;#` preinstalled, it would be very useful to have a tool that can convert `;#` code into a different language. In this challenge, you shall write a program to accomplish this.

## Input

Some `;#` source code, taken via argument or STDIN. This source code may contain (comment) characters other than `;` or `#`.

## Output

Code, in the same language as your submission, which, when executed, prints/returns the same string as the original `;#` code. This resultant code may output a trailing newline after the target string, if that is more convenient for your language.

## Notes

One thing to look out for is escape sequences, such as code that prints backslashes or prints quote marks. Also look out for `;#` code that could contain things that look like keywords or commands in your language.

## Additional restrictions

All programs must terminate (I normally consider this a default, but someone asked about it so I'm stating it here).

## Examples

```
input: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#
output (python): print(";#")
input: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#
output (element): \'`

```

# Answer
# brainfuck, 126 bytes

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

```

Try it online!

The output program will fail in the TIO implementation if the `;#` output exceeds 65536 characters. I also made a 130-byte version which outputs `[+]` instead of `<`, avoiding this problem:

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

```

### Explanation

```
+++[->+++++<]>[->++++>+++<<]        initialize tape with 60 and 45
,[                                  for each input byte:
  +<++++++[-<++++>>------<]         subtract 35 (#) from byte
  >[<]<<[                           if byte was #
         >>>>>[--<--.++>]           output + (43) a number of times equal to accumulator
         <+.-<.<<<<                 output . (46) and < (60)
  ]
  >[->>-<<]>>                       subtract 24 from what's left of byte
  [[-]<]                            check difference and clear if nonzero
  >[                                if byte was originally 59 (;)
   >>++++[-->]<[<]                  add 4 to accumulator cell, then subtract 2 if nonzero. Since BF cells are mod 256, this creates an accumulator mod 127.
  ]
,]

```
> 9 votes

# Answer
# Python 2, ~~76~~ 69 bytes

### Code

Input is surrounded by quotes.

```
for y in input('print').split("#")[:-1]:print`chr(y.count(";")%127)`,

```

Try it online!

### Explanation

The first part of the output is essentially done by the input, using `input('print')`. We split the input on hashtags and discard the last element. We print the representation of **ord(y%127)**, where **y** is the number of occurrences of the semicolon. We append the `,` at the end of the print to make sure that this does not print a newline.

This would give the following Python code for the `Hello, World!`-program:

```
print'H' 'e' 'l' 'l' 'o' ',' ' ' 'W' 'o' 'r' 'l' 'd' '!'

```

Which can be tried online.
> 6 votes

# Answer
# Whitespace, 291 bytes

```
NSSTTNNSTNNSTNNSTTNNSSTSNSSNSNSTNTSTTTSSSTSSSTTNTSSTSNSNTSSSSNSSSTTSSSNTSSTNTSSSTNNSNTSNNSSSSSNSNNNSTSSNNSTSTNNSTSTNNSTSNNSTTNNSTSNNSTNNSTSTNNSTTNNSTNNSTNNSNTTNNSSSSTNNSTSSNNSTSNNSTTNNSTSNNSTSSNNSNTSNNSSTNSSSTSTSNTNSSNTNNSSSSNNSTNNSTNNSSNSSSTSSSSSNTNSSNTNNSSSTNNSTSNNSTSNNSSSNSSSTSSTNTNSSNTN

```

Replace S by space, T by tab and N by a newline.

Generating whitespace in whitespace is not the most efficient thing in the world. Generating any kind of dynamic code requires significant bit-twiddling which, in a language without bitwise operations, would cause the code size to explode. Therefore, this program does not attempt to do something smart, instead opting for just translating the source program one to one. It disassembles to the following:

```
early:
    call S
    call S
    call N
start:
    push  0
    dup
    ichr
    get
    push  35
    sub
    dup
    jz    hash
    push  24
    sub
    jz    semi
    jmp   start
hash:
    pop
    call SSS
    call TTT
    call TTT
    call T
    call N
    call T
    call S
    call TTT
    call N
    call S
    call S
    jmp   early
semi:
    call SSS
    call T
    call N
    call T
    call SSS
    jmp   start
N:
    push 10
    pchr
    ret
SSS:
    call S
    call S
S:
    push 32
    pchr
    ret
TTT:
    call T
    call T
T:
    push 9
    pchr
    ret

```

The code generated by the program looks like:

```
push  0
push  1
add
push  1
add
push  1
add
push  1
add
push  1
add
push  1
add
push  1
add
push  1
add
push  1
add
push  1
add
push  1
add
push  127
mod
pchr
push  0
push  1
add
...

```
> 5 votes

# Answer
# , ~~19~~ ~~20~~ 28 bytes

Bugfix, broke if there was no `#` at the end

Bugfix, implemented `mod 127`

```
Í;û127}
éiA0Í#/0
ò/;
x

```

Try it online!

Try Generated Code

Explanation:

```
Í;û127}                            ' Delete runs of 127 `;`s (mod 127)
éi                                 ' Insert an `i` in front of input
  A<C-v><esc>0<esc>                ' Append <esc>0 to input
                   Í#/<C-v><C-v>0  ' Replace all `#` with `<C-v>0`
ò                                  ' Recursively
 /;                                ' Go to the next `;`
<C-a>                              ' Increment the next number come across

```

In V, in insert mode, any ASCII character can be inserted by code by using `<C-v><Code>`. The V code replaces all `#` with `<C-v>0`, where the zero is a pseudo-accumulator per `#`. Each `#` resets the accumulator to 0 so having one per works out fine. Then the code does an increment for each semicolon found, which just increments the next number it finds, which would be the next accumulator. The `0` is appended to the end so that the instruction doesn't fail for `;`s without a following `#`.

Hexdump:

```
00000000: e969 4116 1b30 1bcd 232f 1616 300a f22f  .iA..0..#/..0../
00000010: 3b0a 7801                                ;.x.

```
> 4 votes

# Answer
## JavaScript (ES6), ~~101~~ 100 bytes

```
s=>`_=>'${s.replace(/[^#;]/g,``)}'.replace(/;*(#?)/g,(l,c)=>c&&String.fromCharCode(~-l.length%127))`

```

Given an input string, deletes all the unnecessary characters, then returns the source of the following function:

```
_=>'...'.replace(/;*(#?)/g,(l,c)=>c&&String.fromCharCode(~-l.length%127))

```

Where `...` represents the cleaned `;#` source. Edit: Saved 1 byte thanks to @l4m2.
> 3 votes

# Answer
# 05AB1E, ~~20 19 18~~ 16 bytes

-1 thanks to Adnan
-2 thanks to carusocomputing
-2 thanks to Kevin Cruijssen

```
'#¡¨vy';¢ƵQ%„çJJ

```

Try it online! (includes output of executed 05AB1E code)

```
'#¡              # Split on #
   ¨             # remove the last element
    vy           # For each...
      ';¢        #   count the number of ;s
         ƵQ%     #   Mod by 127
            „çJ  #   Push çJ
               J # Join stack and output implicitly

```
> 3 votes

# Answer
# Python 2, 75 bytes

```
lambda s:"print"+`''.join(chr(x.count(';')%127)for x in s.split('#')[:-1])`

```

Try it online! (includes output from executing the transpiled Python code)

Thanks to ovs for many many bytes!

## Explanation

This program transpiles the #; code by splitting on #s (`s.split('#')[:-1]`), counting the number of semicolons in each chunk mod 127 (`x.count(';')%127for x in ...`), and converting that into the respective ASCII character (`chr(...)`). That list is then concatenated (`''.join(...)`), converted into a Python representation of the string (the backticks) and inserted into a skeleton Python program for printing strings (`"print"+...`).
> 2 votes

# Answer
# Jelly,  ~~25 24 16~~  15 bytes

-1 thanks to caird coinheringaahing! (Use of `p` in place of `;€`)

```
ṣ”#Ṗċ€”;%127p”Ọ

```

A full program printing equivalent Jelly code (as a monadic link it returns a list of lists of mixed types).

The first example is at **Try it online!** which yields this program.

### How?

Counts up the `;`s in each run between `#`s takes each modulo 127 and appends a cast to ordinal instruction, the monadic  atom, after each.

Jelly implicitly pipes each value to STDOUT as it runs through a program like that i.e. `72Ọ101Ọ108Ọ108Ọ111Ọ44Ọ32Ọ119Ọ111Ọ114Ọ108Ọ100Ọ33Ọ` would print `Hello, world!`.

```
ṣ”#Ṗċ€”;%127p”Ọ - Main link: list of characters
 ”#             - literal '#'
ṣ               - split the result at #s
   Ṗ            - pop (remove the last result, list of trailing non-# characters)
      ”;        - literal ';'
    ċ€          - count for €ach
        %127    - modulo 127 (vectorises)
             ”Ọ - literal 'Ọ' (Jelly's cast to ordinal monadic atom)
            p   - Cartesian product - making a list of lists like [[72,'Ọ'],[101,'Ọ'],...]
                - implicit print (this smashes, printing something like: 72Ọ101Ọ...)

```

A note regarding input: Jelly can take string input in Python format (it will first attempt to evaluate input as Python code). The empty program may be input as `""`, and the hash-only programs as `"#"`, `"##"`, etc. Escape sequences are required for input containing backslashes and quotes.
> 2 votes

# Answer
# Haskell, ~~106~~ 102 bytes

```
';'!(x:a)=x+1:a;'#'!a=0:a;_!a=a;h s="main=putStr"++(show$""++(toEnum.(`mod`127)<$>init(foldr(!)[0]s)))

```

Try it online!

**Ungolfed**

```
step ';' (x:acc) = x+1:acc
step '#' acc = 0:acc
step _ acc = acc;

semicolonHash s = toEnum . (`mod` 127) <$> init (foldr step [0] s)

toHaskell s = "main = putStr " ++ (show $ "" ++ semicolonHash s)

```
> 2 votes

# Answer
# Cubically, ~~138~~ 137 bytes

```
+1/1+54@6:5+1/1+5@6/1+52@6:4/1+5@6:1/1+54@6:4/1+5@6:5+2/1+4@6(~-61/1=7&6+5/1+51=7?6{+3/1+5@6}:5+3/1+3=7?6{+52@6:5+1@6-1@6+1@6:5+2/1+4@6})

```

Try it online!

Note: You may need to replace `&6` with `?6&` for it to work on TIO. `&6` is in the language spec, though.

### How it works

```
+1/1+54@6        Output 'R'
:5+1/1+5@6       Output '3'
/1+52@6          Output 'D'
:4/1+5@6         Output '1'
:1/1+54@6        Output 'R'
:4/1+5@6         Output '1'
:5+2/1+4@6       Output '+'
(                Loop indefinitely
  ~                Get next character
  -61/1=7&6        If input is -1 (EOF), exit program
  +5/1+51=7?6{     If input is `;`
    +3/1+5@6         Output '0'
  }                End if
  :5+3/1+3=7?6{   If input is '#'
    +52@6            Output '@'
    :5+1@6           Output '6'
    -1@6             Output '-'
    +1@6             Output '6'
    :5+2/1+4@6       Output '+'
  }                End if
)                End loop

```

Output program:

```
R3D1R1           Set top face to 1
+00...           Add top face to notepad, aka increment notepad
@6               Output notepad as character
-6               Set notepad to 0
...

```
> 2 votes

# Answer
# Brachylog, 33 bytes

```
{";"∧"+₁"|"#"∧"%₁₂₇g~ạw0"}ˢ;"0"↔c

```

Try it online!

I felt too tired to explain this two years ago, but Razetime reminded me.

```
                           ;"0"↔c    Prepend a 0 to
{                        }ˢ          each element of the input
     "+₁"                            mapped to +₁
 ";"∧                                if it's a semicolon,
         |"#"                        if it's a hash
             ∧"%₁₂₇g~ạw0"            %₁₂₇g~ạw0,
                          ˢ          or nothing otherwise.

      +₁                             add 1

              %₁₂₇                   mod 127,
                  g~ạ                convert from codepoint to character,
                     w               print,
                      0              start over from 0

```
> 2 votes

# Answer
# Jelly, 26 bytes

```
”‘x
f”;L%127Ç;“Ọø”
ṣ”#Ç€ṙ-

```

Try it online!

And try that Jelly code here!

```
ṣ”#Ç€ṙ-      Main link, input is a string of ";;;;;;#lala;;;;;;;;;#"
ṣ”#          Split input on char #
   Ç€        Call helper link 1 for each segment
     ṙ-      Rotate returns 1 to the right (SPLIT introduces an empty element which is moved up front)

f”;L%127Ç;“Ọø”  Helper link 1, determines the number of increments
f”;             Throw out all but semicolons
   L%127        Take the count mod 127
        Ç       Call helper 2
         ;“Ọø”  Add a Jelly link that prints characters and splits print statements

”‘x             Helper 2, receives the count of ;'s
”‘              Return the character ‘ (Jelly's increment command
  x             Once for each ; in the input

```

The Jelly output becomes code like `Ọø‘‘‘‘‘‘‘‘‘‘‘‘‘Ọø‘‘‘‘‘‘‘‘‘‘Ọø`, which prints chr(13)+chr(10)
> 1 votes

# Answer
# C, ~~98~~ ~~96~~ ~~99~~ ~~98~~ 97 bytes

<sup>+3 bytes because I forgot C isn't interpreted :(</sup>

```
c,a;f(){printf("f(){puts(\"");for(;~c;c=getchar())c==59?a++:c==35?a=!printf(&a):a;puts("\");}");}

```

---

Running with:

```
echo ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#" | ./a.out

```

Will print:

```
f(){puts("Hello, World!");}

```
> 1 votes

# Answer
# \>\<\>, ~~106~~ ~~81~~ 77 bytes

This is my first golf in \>\<\> (fish)! A pretty interesting language I have to say. A lot of fun!

```
0n01.
>i:1+?!v:";"=?v"#"=?v
^ ;o";"<   .37<
^oo"1+"
^oooooooo'"~"1+%o0' <

```
> 1 votes

# Answer
# PHP, 72 bytes

```
for(;~$c=$argn[$i++];)echo[Z=>'$n++;',B=>'echo~$n=~chr($n%127);'][a^$c];

```
> 1 votes

# Answer
# C# 169 Bytes

Golfed:

```
class P{static int Main(string[] args){var r="Console.Write(";foreach(var y in args[0].Split('#')){r+=(char)(-1+y.Split(';').Length%127);}System.Console.Write(r+");");}}

```

Human readable version:

```
class P
{
    static int Main(string[] args)
    {
        var r="Console.Write(\"";
        foreach (var y in args[0].Split('#'))
        {
            r +=(char)(-1+y.Split(';').Length% 127);
        }
        System.Console.Write(r+"\");");
    }
}

```
> 1 votes

# Answer
# MATL, ~~32~~ 28 bytes

```
35lF4$Yb"@g59=z]xv127\!&D99h

```

Try it online!

Completely different approach based on `strsplit` rather than an automaton-type program.

```
      Yb % strsplit
    4$   %  with 4 inputs, namely:
35       %   Split on '#'
  lF     %   Do not (F) collapse delimiters (l).
         %   And of course the implicit program input.

"@g    ] % Loop over strings, convert each to a normal char array
   59=z  % How many equal to 59 ';'?

xv!127\  % Delete last element, concatenate and flip to horizontal, mod 127
&D       % Convert to MATL representation
  99h    % Append a 'c' to output ASCII.

```
> 1 votes

# Answer
# MathGolf, 17 bytes

```
⌡(¶{gÉ'8=£♣(%$''\

```

Try it online!

## Explanation

```
⌡                      decrement twice
 (                     decrement
                       this transforms ";;;#;;#" -> "888 88 "
  ¶                    split string on spaces
   {                   foreach...
    gÉ                 filter using next 3 characters
      '8               push single character "8"
        =              pop(a, b), push(a==b)
                       this filters out all non-";"
         £             length of array/string with pop
          ♣            push 128
           (           decrement
            %          modulo
             $         pop(a), push ord(a) or char(a) (gets character with code)
              ''       push single character "'"
                \      swap top elements

```

Since any character can be put on the stack (and thus the output) using `'<char>`, this will output a sequence of such code blocks.
> 1 votes

# Answer
# Vyxal , 18 bytes

```
\#€Ṫƛ\;O₇‹%\C+\₴+,

```

Good, but definitely could be improved. Outputs the codepoint, followed by a C to convert to a character, and then a print symbol.

Try it Online!
> 1 votes

# Answer
# Nim, 97 bytes

```
var a=0
for c in stdin.readAll:
 if c==';':a+=1
 if c=='#':echo "stdout.write chr ",a mod 127;a=0

```

Try it online!

Example resulting code
> 1 votes

# Answer
# Thunno 2, 16 bytes

```
';'⁺Ṇ'#"ṇȷ%C¢"WṆ

```

Try it online! or verify the resulting Thunno 2 code

#### Explanation

```
';'⁺Ṇ'#"ṇȷ%C¢"WṆ  '# Implicit input
';'⁺Ṇ              # Transliterate ";" -> "⁺"
   ⁺               #   Increment top of stack
                   #   (which starts at 0)
     '#"ṇȷ%C¢"WṆ  '# Transliterate "#" -> "ṇȷ%C¢"
        ṇȷ         #   Push compressed integer 127
          %        #   And modulo top of stack by that
           C       #   Cast to character using ASCII value
            ¢      #   And print it without a newline
                   # Implicit output

```
> 1 votes

# Answer
# ARBLE, 57 bytes

```
"print%q"%gsub(a,".-#",#char(len(gsub(e,"[^;]",""))%128))

```

## Explained

```
"print%q"%gsub(a,".-#",#char(len(gsub(e,"[^;]",""))%128))
          gsub(a,".-#",                                 )  -- Replace all groups of characters followed by a # in the input with...
                                 gsub(e,"[^;]","")         -- Remove all non-; characters, removing comments
                             len(                 )        -- Effectively count all ; in the group
                        char(                      %128)   -- Modulo 128, convert to a char.
                       #                                   -- As a function. Effectively runs the ;# code.
"print%q"%                                                 -- returns a string consisting of print followed by the string-formatted ;# code.

```

Try it online!
> 1 votes

# Answer
# Actually, 25 bytes

```
'#@s⌠';@c7╙D@%⌡MdX$"♂cΣ"o

```

Try it online! (includes output from executing the transpiled Actually code)

Explanation:

```
'#@s⌠';@c7╙D@%⌡MdX$"♂cΣ"o
'#@s                       split on "#"
    ⌠';@c7╙D@%⌡M           for each chunk:
     ';@c                    count ";"s
         7╙D@%               mod by 127 (2**7-1)
                dX         discard last value
                  $        stringify
                   "♂cΣ"o  append "♂cΣ":
                    ♂c       convert each value to an ASCII character
                      Σ      concatenate

```
> 0 votes

# Answer
# shortC, 48 bytes

```
c,a;AR"AP\"");O;~c;c=G)c==59?a++:c==35?a=!R&a):a

```
> 0 votes

# Answer
# Pyth, ~~25~~ ~~23~~ 24 bytes

```
j\\+"jk["mC%/d\;127Pcw\#

```

*+1 bytes thanks to @FryAmTheEggman*

Try it!

handles characters that have to be escaped by only using 1-char-strings.

Sample outputs:

```
jk[\"

jk[\H\e\l\l\o\,\ \W\o\r\l\d\!

```

Uses my ;# interpreter.
> 0 votes

# Answer
# Fourier, 32 bytes

```
$(I~S{59}{`^`}S{35}{`%127a0`}&i)

```

**Try it on FourIDE!**

This was quite an easy challenge since Fourier is *basically* a superset of ;#:

```
;# command > Fourier equivalent
; > ^ (Increment the accumulator)
# > %127a0 (Modulo accumulator by 127, output corresponding code point and set accumulator to zero)

```
> 0 votes

# Answer
# Ruby, 47+1=48 bytes

```
$_=gsub(/.*?#/){"$><<#{$&.count(?;)%127}.chr;"}

```

+1 byte for `-p`.

Try it online!

-30 bytes thanks to @manatwork!
> 0 votes

# Answer
## CJam, 14 bytes

```
q'#/);';fe=:c`

```

Explanation:

```
q               e# Read input
 '#/            e# Split on '#'
    );          e# Delete last element
      ';fe=     e# Count occurrences of ';' in each
           :c   e# Convert each to character (code point)
             `  e# Escape

```
> 0 votes

# Answer
# APL, 31 bytes

```
{⍕'⎕UCS',⌽127|+/¨';'=⍵⊂⍨'#'=⍵}⌽

```

Output:

```
      ({⍕'⎕UCS',⌽127|+/¨';'=⍵⊂⍨'#'=⍵}⌽) ';;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#'
⎕UCS 59 35
      ⍝ evaluate the output
      ⍎({⍕'⎕UCS',⌽127|+/¨';'=⍵⊂⍨'#'=⍵}⌽) ';;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#'
;#

```

Explanation:

* : reverse the input
* `{`...`}`: pass it to this function:
    + `⍵⊂⍨'#'=⍵`: partition at each `#` in the string (from the beginning, which is why it had to be reversed first)
    + `+/¨';'=`: count the `;`s in each partition
    + `127|`: modulo 127
    + : reverse it again
    + `'⎕UCS',`: prepend the string `⎕UCS`, which is the Unicode function.
    + : string representation
> 0 votes

# Answer
# C, 150 bytes

```
#include<stdio.h>
c;n=0;main(){puts("#include<stdio.h>\nmain(){");while(~(c=getchar()))c-35?c-59?:n++:(printf("putchar(%d);",n%127)&(n=0));puts("}");}

```

Expanded:

```
#include<stdio.h>
c;
n=0;
main(){
        puts("#include<stdio.h>\nmain(){");
        while( ~(
            c=getchar()
        ))
                c-35?
                        c-59?
                                :
                                n++
                        :
                        ( printf("putchar(%d);",n%127)
                        &(n=0))
                ;
        puts("}");
}

```

It's a complete program that (should) terminate, ignore comments and produce always correct output code. I assume EOF=-1

Tested on SystemResque-Cd 4.9.6, compiled with gcc 4.9.4
> 0 votes

# Answer
# braingasm, 40 bytes

```
,[35-z["[127-s[127+.>]]<0*".]24-z[43.],]

```

Gotta say, that's surprisingly short.

```
,[                                    ,]     Read a byte until end of input
  35-                                          Subtract 35.
     z[                     ]                  If the result is zero,
       "[127-s[127+.>]]<0*".                     print the code for `#`.
                             24-               Subtract 24.
                                z[   ]         If the result is zero,
                                  43.            print the code for `;`

```

The generated code for `;` is a `+`, which increments the current cell.

The generated code for `#` contains an akward, manual modulo operation

```
[127-s[127+.>]]<0*
[             ]       While current cell is not zero
 127-                   Subtract 127
     s[      ]          If result is negative
       127+.              Add 127 again and print current cell
            >             Step to next cell to break the loop
               <0*      Step back to first cell and clear it

```
> 0 votes

# Answer
# Braingolf, 55 bytes

```
V#0VR&,l1-MvMR[R.#;e"+1"MM|.##e"@%+1~#"MMMMMM|$_vv]Rv&@

```

Try it online!

Basically replaces `;` with `1+`, `#` with `#~1+%@` and pre-pends the whole thing with a `0` because monadic `+` operator is broken right now.

`1+` adds 1 to the last item in the stack.

`#~1+%@` pushes the char value of `~` (126), adds 1 to make 127, modulus with other item on stack, then pop and print as char.

### Explanation

```
V#0VR&,l1-MvMR                         Implicit input of each char to stack
[R.#;e"+1"MM|.##e"@%+1~#"MMMMMM|$_vv]
Rv&@

V#0                                    Create stack2, push char value of 0
   VR                                  Create stack3, return to stack1
     &,                                Reverse stack
       l1-                             Push length of stack - 1
          MvMR                         Move length to stack2, switch to stack 2
                                       Move length to stack3, switch back to stack1
[R................................vv]  Do-While loop, will run l times
                                       where l is length of input
  .#;                                  Duplicate last item and push char value of semicolon
     e                                 Pop last 2 items, if they are equal..
      "+1"                             ..Push char values of +1 in that order
          MM                           ..Move last 2 items to stack2
            |                          endif
             .##                       Duplicate last item and push char value of hash
                e                      Pop last 2 items, if they are equal..
                 "@%+1~#"              ..Push char values of @%+1~# in that order
                         MMMMMM        ..Move last 6 chars to stack2
                               |       endif
                                $_     Silently pop last item
Rv                                     Switch to stack2
  &@                                   Greedy char print, print every item in stack as char

```
> 0 votes

# Answer
# Perl 5 `-n0`, ~~78~~ 58 bytes

```
say'say"',(map{$_=chr y/;//%127;s/\W/\\$&/r}/[^#]*#/g),'"'

```

Try it online!
> 0 votes

# Answer
# q/kdb+, 42 bytes

**Solution:**

```
{-1_"c"$mod[;127](#:)@/:"#"vs x inter"#;"}

```

**Examples:**

Note that the `,` is used to signify a list (versus atom) as `"\""` is a list of one element, rather than being an atom.

```
q){-1_"c"$mod[;127](#:)@/:"#"vs x inter"#;"}";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#"
";#"
q){-1_"c"$mod[;127](#:)@/:"#"vs x inter"#;"}";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#"
,"\""

```

**Explanation:**

Take input string, remove anything that isnt a `#` or a `;`, split into lists on `#`, count number of elements in each list, perform mod 127 on the result and cast to a string:

```
{-1_"c"$mod[;127]count each"#"vs x inter"#;"} / ungolfed
{                                           } / lambda function
                                 x inter"#;"  / intersection of input and ';#' to clear out any 'comments'
                           "#"vs              / split string on hash
                 count each                   / length of each sub-list
        mod[;127]                             / 127 modulo result (vectorised)
    "c"$                                      / cast back to string
 -1_                                          / drop last character (assuming terminated string)

```

**Notes:**

* Assumes that input is terminated by a `#`, otherwise the last chunk will be erroneously dropped by the `-1_`.
* Could be 10 bytes shorter if input was guaranteed to only contain `;#`.
> 0 votes

# Answer
# Ly, 52 bytes

```
0ui[[";"=[pp"+1"oo2$]p"#"=[pp"(127)%o0"&o2$]]i]";"o;

```

Try it online!
> 0 votes

# Answer
# Common Lisp, ~~165~~ 156 bytes

```
(with-output-to-string(v)(princ"(princ\""v)(do((a 0)(c #\ (read-char()())))((not c))(case c(#\;(incf a))(#\#(princ(code-char a)v)(setf a 0))))(princ"\")"v))

```

Try it online!

For instance, when applied to:

```
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#"

```

produces:

```
(PRINC";#")

```

that prints `;#`
> 0 votes

# Answer
# Ahead, 41 bytes

```
rW"127%o"<
~>jvi:'#=n';=s~
lW~>'@o@~"1+"<

```

Converts `;#` code into its direct Ahead equivalent, so you get long code consisting mostly of `1+`. One byte shorter, but output is very long.

Try it online!

---

# Ahead, 42 bytes

```
roo''%721$<
~> jli:'#=n';=+~
   >"@ooKu"W@

```

Figures out which characters to print and writes a program that will push and print all of them with the `'` function. Generates much shorter output at the cost of 1 byte. This version was surprisingly hard to golf.

Try it online!
> 0 votes

# Answer
# Microscript II, ~~50~~ 45 bytes

```
0`IK#>s{<d59=(`s1+`)35=(128s`%p0`"Kp"p)>}*"h"

```
> 0 votes

# Answer
# Google Sheets, 120

Closing parens already discounted.

* `A1`: input
* `A2`: `#`
* `B2`: `"`
* `A3`: `=JOIN(,ArrayFormula(CHAR(MOD(LEN(SPLIT(A1,A2))-LEN(SUBSTITUTE(SPLIT(A1,A2),";",)),127))))`

Broken down:

```
=JOIN(,                                 Like Concatenate, but shorter
 ArrayFormula(
  CHAR(                                 Convert length to character
   MOD(
    LEN(SPLIT(A1,A2))-
    LEN(SUBSTITUTE(SPLIT(A1,A2),";",)), Subtract commented characters
   127
))))                                    Pile on parens at the end to exploit autocomplete

```
* `A4`: `="="""&SUBSTITUTE(A3,B2,B2&B2)&B2` \- Needs two `"`s to escape, hence the substitution.
> 0 votes

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

```
s=>`_=>String.fromCharCode(${s.match(/.*?#/gs).map(c=>~-c.split`;`.length%127)})`

```

Try it online!

# JavaScript (Node.js), 86 bytes, allowing nop(no `#`)

```
s=>`_=>String.fromCharCode(${s.split`#`.slice(0,-1).map(c=>~-c.split`;`.length%127)})`

```

Try it online!
> 0 votes

# Answer
# 8086 DOS machine code, 47 bytes

Input is from stdin (terminated by a newline), output is directly to the console (cannot be redirected to a file, workaround provided)

```
0CD5:0100  31 DB B4 08 CD 21 3C 0D-74 20 3C 3B 75 06 43 80 1....!<.t <;u.C.
0CD5:0110  FB 7F 74 EC 3C 23 75 EA-B0 B0 CD 29 88 D8 CD 29 ..t.<#u....)...)
0CD5:0120  B0 CD CD 29 B0 29 CD 29-EB D6 B0 C3 CD 29 C3    ...).).).....).

```

Commented assembly:

```
        // nasm syntax with C comments because SE sucks

        // Because I use int 29h, you can't redirect the output with >.
        // Defining REDIRECTABLE will swap out the int 29h with an equivalent
        // int 21h:02h which can be redirected.
        // Unscored.
%ifdef REDIRECTABLE
%macro INT_29H
        push    ax
        push    dx
        mov     dl, al
        mov     ah, 0x02
        int     0x21
        pop     dx
        pop     ax
%endm
%else
%macro INT_29H
        int     0x29
%endm
%endif

        section .text
        [org 0x100]
        global start
start:
.reset:
        // Reset the accumulator
        xor     bx, bx
        // Main loop
.loop:
        // int 29h:08h: read char to AL (no echo)
        mov     ah, 0x08
        int     0x21
        // check for \r, if so, quit.
        cmp     al, 13
        je      .finalize
        // Check for semicolon
        cmp     al, ';'
        jne     .next
.semicolon:
        // Increment accumulator
        inc     bx
        // If we reach 127, reset the accumulator to 0.
        // This is the same as modulo 127 and
        // doesn't require an AAM or DIV setup.
        cmp     bl, 127
        je      .reset
.next:
        // Check for '#', if not, loop again
        cmp     al, '#'
        jne     .loop
.hash:
        // '#': print out code
        // mov al, <hardcoded acc>
        mov     al, 0xB0
        INT_29H
        mov     al, bl
        INT_29H
        // int 0x29
        mov     al, 0xCD
        INT_29H
        mov     al, 0x29
        INT_29H
        // Now reset the accumulator to 0
        jmp     .reset
.finalize:
        // Output ret instruction
        mov     al, 0xC3
        INT_29H
        // And exit
        ret

```

This program will evaluate the program, and emit a program that prints the output byte by byte using `int 29h`.

So for example, the `;#` test case will emit the machine code for this:

```
start:
        mov     al, ';'
        int     0x29
        mov     al, '#'
        int     0x29
        ret

```

I'd like to find a way to do this smaller. Calling `int 29h` that many times is rather annoying, all because I can't do `int 21h:09h` because a `$` might appear in the output.

Additionally, outputting a parser instead seems to be larger.
> 0 votes

# Answer
# GNU AWK, 84 bytes

```
BEGIN{FS=";";RS="#";printf"BEGIN{printf\42"}RT{printf"%c",NF-1%127}END{printf"\42}"}

```

Try it online!

Simply got this interpreter and added AWK's syntax.
> 0 votes

# Answer
# Knight (with `ASCII`), 62 bytes

```
;=a 0;W=xP Wx;=zAx;I?59z=a%+aT127I?35z=a+0O+";O A"aF=xSxF1""O0

```

Try it online!

Interpreter is patched to follow the spec for ASCII and removes trailing newlines in input (a known bug with that version).

With the new `ASCII` function being near standardized, this becomes very easy.

The program is input to standard input followed by a blank line.

```
# initialize acc with 0
; = acc 0
# loop for all non-empty lines in stdin,
# assigning to line
; WHILE (= line PROMPT)
: {
    # Loop through all chars in line
    : WHILE line
    : {
        # Grab the ASCII value of the first char in line, store in chr
        ; = chr ASCII(line)
        # First test for ASCII 59, ";"
        ; IF (? ASCII(";") chr)
        : {
            # acc = (acc + 1) % 127
            : = acc % (+ acc 1) 127
        : }
        # ELSE
        : {
            # check for ASCII 35, "#"
            : IF (? ASCII("#") chr)
            : {
                  # output ";O A" + ASCII value of acc
                 ; OUTPUT(+ ";O A" acc)
                 : = acc 0
            : }
            # ELSE nop
                 : FALSE
       : }
       # Pop front char from line
       : = line SUBSTITUTE(line 0 1 "")
    : }
: }
# ; executes two statements; for the last one,
# just do a NOP.
: OUTPUT(0)

```

Not sure if `&`/`|` makes a difference here.
> 0 votes

# Answer
# Python 3, 81 bytes

```
for c in input("a=0;"):print({";":"a+=1","#":"print(end=chr(a%127));a=0"}.get(c))

```
> 0 votes

---
Tags: code-golf
---


title: Sort musical pitches

text:
# Question
Title: Sort musical pitches
Given an unordered list of musical pitches, write the shortest program/function (scored in bytes) to sort the list from lowest pitch to highest.

Pitches will be given in scientific pitch notation, consisting of a tone name followed by an octave number. Here, the tone name will be a single letter A–G, possibly followed by a single `#` or `b` character (representing sharp and flat, respectively). The octave number will be a single digit 0–9.

From lowest to highest, the order of pitches in this notation may be represented as follows:

```
<--- lower pitch                              higher pitch --->
_______________________________________________________________
Cb0 C0 C#0
       Db0 D0 D#0
              Eb0 E0  E#0
                  Fb0 F0  F#0
                          Gb0 G0 G#0
                                 Ab0 A0 A#0
                                        Bb0 B0  B#0
                                            Cb1 C1  C#1
                                                    Db1 D1 D#1
                                                           etc.

```

In this representation, pitch rises from left to right, so vertically aligned notes (enharmonic pairs) have the same pitch. Each row contains three notes in the order flat, natural, sharp (e.g. Cb0, C0, C#0) and the order of rows within an octave is C, D, E, F, G, A, B. Notice that by a quirk of the notation, the indentation pattern differs for the C and F rows.

Your code may sort enharmonic pitches in any order. For example, given `[D#0, Eb0, D#0]` as input, any of `[D#0, D#0, Eb0]`, `[D#0, Eb0, D#0]`, and `[Eb0, D#0, D#0]` is a valid output.

### Test cases

```
[A2, B2, C2, D2, E2, F2, G2, A3] -> [C2, D2, E2, F2, G2, A2, B2, A3]
[E5, D#5, E5, D#5, E5, B4, D5, C5, A4] -> [A4, B4, C5, D5, D#5, D#5, E5, E5, E5]
[E#6, Fb6, B#6, Cb7, C7] -> [Fb6, E#6, Cb7, B#6, C7] or [Fb6, E#6, Cb7, C7, B#6]

```

# Answer
> 4 votes
# Jelly,  ~~31 30~~  29 bytes

```
FµḢ“¤ı¶“Œ’ḥ;ṪV×12Ʋ;=”#Ḥ’ƊSµ$Þ

```

A monadic Link that accepts a list of lists of characters and yields a sorted version.

**Try it online!**

### How?

```
FµḢ“¤ı¶“Œ’ḥ;ṪV×12Ʋ;=”#Ḥ’ƊSµ$Þ - Link: notes
                           $Þ - sort by: last two links as a monad:
 µ                            -   monadic chain:
F                             -     flatten (this is to get a copy so we don't
                                             alter what we are sorting in place)
                          µ   -   monadic chain:
  Ḣ                           -     head of note (removes it too)
          ḥ                   -     hash with salt & domain:
   “¤ı¶“Œ’                    -       base 250 numbers = [256628,20]
                                        X = CDEFGAB -> 4,6,8,9,11,13,15
                 Ʋ            -     last four links as a monad:
            Ṫ                 -       tail of note (removes it too)
             V                -       evaluate as Jelly code -> integer
               12             -       twelve
              ×               -       multiply
                                        Y = 12 × octave
           ;                  -     concatenate -> [X,Y]
                        Ɗ     -     last three links as a monad - f(v):
                                        (v being one of [], ['#'], or ['b'])
                   =”#        -       equals '#'? (vectorises)
                      Ḥ       -       double
                       ’      -       decrement
                                        O = accidental offsets [], [1], or [-1]
                  ;           -     concatenate -> [X,Y]+O
                         S    -     sum -> note number

```

# Answer
> 3 votes
# Python 3, ~~92~~ 83 bytes

*-9 bytes thanks to G B*

## Golfed code

```
lambda l:sorted(l,key=lambda i:12*int(i[-1])+" D EF G A B".find(i[0])-ord(i[1])/48)

```

Try it online!

## Commented code

```
lambda l: sorted(l,                 # Sort the list
    key=lambda i:                   # Key used to sort the list, takes a single string as input
                                    # Outputs an integer; the lower the integer, the lower the note
        12 * int(i[-1])             # Multiply the octave number by 12
        + " D EF G A B".find(i[0])  # Add the number of the note within that octave;
                                    # C = -1 up to B = 10
        -ord(i[1])/48               # Subtract the ASCII code of the second character;
                                    # Ends up with sharpened notes having higher values than
                                    # no-accidental ones, which have a higher value than flattened ones
)

```

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

```
n=>n.sort((a,b,l=e=>`b${D=e.slice(-1)}#`.search(e[1])+12*D+'C D EF G A B'.search(e[0]))=>l(a)-l(b))

```

Try it online!

# Answer
> 2 votes
# JavaScript (ES6),  ~~87 86~~  85 bytes

*-1 thanks to @l4m2*

```
a=>a.sort((a,b)=>(g=([a,b,c])=>(b|c)*12+' D EF G A B'.search(a)-!!c+2*(b<g))(a)-g(b))

```

Try it online!

### Commented

```
a =>                  // a[] = input array
a.sort((a, b) =>      // for each pair of notes (a, b) to be sorted:
  ( g =               //   g is a helper function taking a note
    ([a, b, c]) =>    //   split into [a, b, c] (c may be undefined)
      (b | c)         //     use whichever of b or c is a digit ...
      * 12            //     ... as the octave
      + ' D EF G A B' //     add the index of the leading letter:
        .search(a)    //       "CDEFGAB" -> [-1,1,3,4,6,8,10]
      - !!c           //     subtract 1 if there's an accidental
      + 2 * (b < g)   //     add 2 if the accidental is '#'
  )(a)                //   invoke g with the 1st note
  - g(b)              //   invoke g with the 2nd note and subtract
)                     // end of sort()

```

# Answer
> 2 votes
# APL+WIN, 83 bytes

Prompts for notes as nested vector

```
m←⊃3↑¨¯1⌽¨s←⎕⋄s[⍋((¯1×m[;3]='b')+m[;3]='#')+(12×(⍎¨m[;1]))+¯1+'C D EF G A B'⍳m[;2]]

```

Try it online! Thanks to Dyalog APL Classic

Here is an improved 68 byte version but it does not work on Dyalog because of ⎕fi

```
s[⍋∊(¯1+'C D EF G A B'⍳↑¨s)+(+/¨((⊂'b#')∊¨s)×¨⊂¯1 1)+12×+/¨⎕fi¨¨s←⎕]

```

# Answer
> 2 votes
# Ruby, 70 bytes

```
->l{l.sort_by{|x|x[-1].ord*12+"C D EF G A B".index(x[0])-x[1].ord/48}}

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 95 bytes

```
\d
$*-===$&
-
12$*=
(.+?)=+
$1$&
#=
==
b=

[CDE]=
$&=
T`L`56d`.=
\d=
$*=$&$*=
O$`.+?(=+).
$1
=

```

Try it online! Takes newline-separated input but link is to test suite that converts from and to comma-separated input. Explanation:

```
\d
$*-===$&
-
12$*=

```

Representing the pitch in unary using `=` signs, multiply the octave by `12` and add `3` (so that I can subtract `2` from it later without it falling to zero).

```
(.+?)=+
$1$&

```

Duplicate the note name.

```
#=
==
b=

```

Adjust the pitch for a sharp or a flat.

```
[CDE]=
$&=
T`L`56d`.=
\d=
$*=$&$*=

```

Adjust the pitch according to the note name.

```
O$`.+?(=+).
$1

```

Sort by the pitch.

```
=

```

Delete all of the `=` signs.

# Answer
> 1 votes
# JavaScript (Node.js), 81 bytes

```
a=>a.sort((a,b)=>(g=([a,b,c])=>(c|b)*7+('0x'+a-5||4)%7-(c?b>g?.6:-.6:0))(a)-g(b))

```

Try it online!

Notice that we needn't care whether difference between each pair of letter is 1/2 or 1, just give them 3/4 works

```
    #C    #D    #E    #F    #G    #A    #B
 C     D     E     F     G     A     B     C
  bD    bE    bF    bG    bA    bB    bC
[][  ][][  ][  ][  ][  ][][  ][][  ][  ][  ]

```

# Answer
> 1 votes
# Scala, 59 bytes

A port of @G B' Ruby answer in Scala.

---

Golfed version. Try it online!

```
_.sortBy(x=>x.last*12+"C D EF G A B".indexOf(x(0))-x(1)/48)

```

Ungolfed version. Try it online!

```
object Main extends App {
  def sortNotes(notes: List[String]): List[String] = {
    notes.sortBy(note => {
      val noteChars = note.toCharArray
      noteChars.last.toInt * 12 + "C D EF G A B".indexOf(noteChars.head) - noteChars(1).toInt / 48
    })
  }

  println(sortNotes(List("Ab1", "B#2", "Cb3", "D#0", "Ab0", "G0")))
  println(sortNotes(List("A2", "B2", "C2", "D2", "E2", "F2", "G2", "A3")))
  println(sortNotes(List("E5", "D#5", "E5", "D#5", "E5", "B4", "D5", "C5", "A4")))
  println(sortNotes(List("E#6", "Fb6", "B#6", "Cb7", "C7")))
}

```

---
Tags: code-golf, array, sorting, music
---