title: Mutate my DNA sequence

text:
# Question
Title: Mutate my DNA sequence
When translating DNA into proteins, the ribosomes read the sequence of DNA nucleotides 3 by 3. Each set of 3 nucleotides is called a codon, and each codon encodes for an amino acid, with some redundancies. Here's the conversion table used by most organisms (table is read left, top, right):

Humans and most other organisms use just a single amino acid as a "start" codon: Methionine, a.k.a. Met, M, or ATG. This means that any DNA sequence coding for a protein starts with ATG, which will be recognised by the translation machinery.

However, three different codons are used to stop the translation: TAA, TAG and TGA. If the replication machinery encounters any of these, it will stop, and the translated protein will be released into the cell.

Therefore, one of the most dangerous mutations that can occur is one that will cause an **early termination** of protein translation. For example, if we take this DNA sequence:

`ATGGCCTTCATATCGGCGGACAGCGAATCTGGTGATTAA`

Split into codons:

`ATG GCC TTC ATA TCG GCG GAC AGC GAA TCT GGT GAT TAA`

Once translated, will give:

`met ala phe ile ser ala asp ser glu ser gly asp STOP`

But if we replace C at 14th position into an A, then the protein sequence will be

`met ala phe ile STOP`

This **substitution** would be written in genomics as `14C>A`.

I could also perform other substitutions (25G\>T for example) that would cause early termination, but 14C\>A is the first one in the sequence, and so would produce the shortest protein after translation.

## Challenge

Given a string of nucleotides coding for a protein (first codon is ATG, last is a STOP), find the first substitution that would cause an early termination of protein translation, resulting in the shortest possible protein. This is code golf, so fewest bytes wins!

## Rules and specifications

(these will be updated if anyone asks relevant questions about what's allowed)

* DNA sequence is stored in a character string as consecutive block capitals, no spaces or punctuation in it, and contains only ACGT. If you want to store it into binary (A:00/C:01/G:10/T:11) or as integers (A:1/C:2/G:3/T:4), that's fine (you don't need to follow these encodings).
* Declaration of the codon to amino acid conversion table is part of the golfing challenge. You must choose which parts you deem relevant. Most softwares use hashes / dictionaries to store it.
* Code should return the substitution formatted under the preferred nomenclature: 14C\>A (position, original nucleotide, "\>", new nucleotide), but any format that includes those three elements is accepted.
* If there are no possible early termination sites, function should return any easily recognisable error value (raise an error, FALSE, -1, etc) or return nothing.

## Test cases

```
ATGCACTGTTGGGGAGGCAGCTGTAACTCAAAGCCTTAG
-> 9T>A

ATGGTAGAACGGAGCAGCTGGTCATGTGTGGGCCCACCGGCCCCAGGCTCCTGTCTCCCCCCAGGTGTGTGGTCATGCCAGGCATGCCCTTAG
-> 7G>T

ATGGAACATCAATCTCAGGCACCTGGCCCAGGTCATTAA
-> 4G>T

ATGTGCCAAGTGCATTCTTGTGTGCTTGCATCTCATGGAACGCCATTTCCCCAGACATCCCTGTGGCTGGCTCCTGATGCCCGAGGCCCATGA
-> 6C>A

ATGCTTTTCCATGTTCTTTGGCCGCAGCAAGGCCGCTCTCACTGCAAAGTTAACTCTGATGCGTGA
-> 20G>A

ATGGTAGAGTAA
-> 7G>T

ATGGTTCCACGGTAA
-> ERROR

```

# Answer
> 3 votes
# 05AB1E, ~~29~~ 27 bytes

```
vNU4E¨NXǝ3ô•`|Ž•₅вåàiX>yN)q

```

Input as `2341` for `ACGT` respectively.
Output in the format and order `[position, original nucleotide, new nucleotide]`. Will output the input itself if there are no possible early termination sites. (Could be 1 byte less by removing the `>` if 0-based positions were allowed.)

Try it online or verify all test cases or verify all test cases with a conversion back to `ACGT`.

**Explanation:**

```
v             # Loop over each of the digits of the (implicit) input-string
 NU           #  Store the current loop-index in variable `X`
   4E         #  Inner loop in the range [1,4]:
     ¨        #   Remove the last digit of the (implicit) input-string
              #   (this is to ensure it doesn't find the trailing STOP all inputs will have)
      NXǝ     #   Insert the current digit of the inner loop at position `X` in the string
         3ô   #   Split the string into parts of size 3
   •`|Ž•      #   Push compressed integer 7964812
        ₅     #   Push builtin integer 255
         в    #   Convert the larger integer to base-255 as list: [122,124,142]
   å          #   Check for each of these three values if it's in the list
    ài        #   If any is truthy:
      X       #    Push the current index of the outer loop we stored in `X`
       >      #    And increase it by 1 to make the 0-based index 1-based
        y     #    Push the current digit of the outer loop
         N    #    Push the current digit of the inner loop
          )   #    Wrap all three values into a list
           q  #    And terminate the program
              #    (after which this list is output implicitly as result)
              # (and if no value is found after the nested loop,
              #  output the (implicit) input as output implicitly instead)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•`|Ž•` is `7964812` and `•`|Ž•₅в` is `[122,124,142]`.

# Answer
> 10 votes
# JavaScript (ES6),  ~~124 ... 93~~  92 bytes

Output format: `XiY`, with `X` = original nucleotide, `i` = position, `Y` = new nucleotide.

```
s=>s[i=([,,x,y]=s.match(/(.A[AG]|.GA|T(.[AG]|(A|G).))(...)*$/)).index+!!x+!!y]+-~i+'AT'[+!x]

```

Try it online!

### Regular expression

```
r = /(.A[AG]|.GA|T(.[AG]|(A|G).))(...)*$/
     (          |               )           // 1st capturing group
      .A[AG]|.GA                            // match ★AA, ★AG or ★GA
                 T(.[AG]|(A|G).)            // 'T' + 2nd & 3rd capturing groups:
                                            // match T★A, T★G, TA★ or TG★
                                 (...)*$    // make sure that the number of trailing
                                            // nucleotides is a multiple of 3

```

To summarize, this will match 21 codons that can be mutated to generate a *STOP*. By testing the 2nd and 3rd capturing groups, we can classify them into 3 categories describing the position of the nucleotide that needs to be altered.

```
 2nd group | 3rd group | position | matching codons
-----------+-----------+----------+-------------------------------------------------------
  not set  |  not set  |    1st   | (TAA) (TAG) (TGA) CAA CAG CGA AAA AAG AGA GAA GAG GGA
    set    |  not set  |    2nd   | TTA TTG TCA TCG TGG
    set    |    set    |    3rd   | TAT TAC TGT TGC

```

### Commented

```
s =>               // s = input DNA sequence
  s[               // append the original nucleotide ...
    i =            //   ... which is at position i (0-based)
    ( [,, x, y] =  //   x = 2nd capturing group, y = 3rd capturing group
        s.match(r) //   apply the regular expression to s
    ).index        //   get the position of the matching codon
    + !!x + !!y    //   add 2 if x and y are set, 1 if only x is set, 0 if x is not set
  ]                //
  + -~i            // append the 1-indexed position
  + 'AT'[+!x]      // append the new nucleotide: 'T' if x is not set, 'A' otherwise

```

# Answer
> 6 votes
# Perl 5, ~~73~~ 72 bytes

-1 byte using anchor at the end instead of the start

```
/(?|(.)(A[AG]|GA)|T(.)[AG]|T[AG](.))(...)*$/;$_="$+[1]$1>".($-[1]%3?A:T)

```

TIO

```
/^(...)*?(?|(.)(A[AG]|GA)|T(.)[AG]|T[AG](.))/;$_="$+[2]$2>".($-[2]%3?A:T)

```

Try it online!

# Answer
> 5 votes
# Jelly, 30 bytes

```
os3ḅ4f“EGM‘Ḋ
JṬ€×Ɱ4ZẎçƇ⁸ḢĖżW€Ṁ

```

A monadic Link accepting a list of integers (in `[1,2,3,4]` mapping to `ACGT` respectively) which yields a list of lists of integers, `[[position, new nucleotide], original nucleotide]`.

(A valid sequence with start, and stop but no possible substitution that would cause early termination will output `[[4]]`)

**Try it online!**
...Or see this version which performs both a translation from the `ACGT` input format, and a translation to the `{position}{original nucleotide}>{new nucleotide}` output format.

### How?

```
os3ḅ4f“EGM‘Ḋ      - helper Link: [0,...,0,new nucleotide], N; DNA integer list, A
o                 - (N) logical OR (A) (vectorises)
 s3               - split into chunks of three
   ḅ4             - convert from base four to integer
      “EGM‘       - code-page index list = [69,71,77]
     f            - filter keep (i.e. only keep stops)
           Ḋ      - dequeue (so if only a single stop was found and hence no early
                             stops we'll have an empty list which is falsey)

JṬ€×Ɱ4ZẎçƇ⁸ḢĖżW€Ṁ - Main Link: DNA integer list, A
J                 - range of length (of A) -> [1,2,...]
 Ṭ€               - untruth each -> [[1],[0,1],[0,0,1],...]
   ×Ɱ4            - map across [1,2,3,4[ performing multiplication
      Z           - transpose
       Ẏ          - tighten -> [[1],[2],[3],[4],[0,1],[0,2],[0,3],[0,4],[0,0,1],...]
                  - (call that X)
          ⁸       - use chain's left argument, A, as the right argument
         Ƈ        - filter keep those (x in X) for which this is truthy:
        ç         -   call the helper link as a dyad f(x, A)
           Ḣ      - head (which will be the shortest)
            Ė     - enumerate (that)
              W€  - wrap each (integer a in A) in a list
             ż    - zip left and right together
                Ṁ - get the maximum

```

# Answer
> 5 votes
# Python 3, 88 bytes

```
f=lambda i,j,k,*l,n=1:(j+k<4)*(n,i,5)+(i-k>2)*(n+1,j,1)or(i-j>2)*(n+2,k,1)or f(*l,n=n+3)

```

Try it online!

Solution without regex. Uses `1235` for `AGCT`, respectively. Takes each base as a separate argument. Will suggest `A` for any instance of `T*A, T*G, TA*, TG*`. Outputs as `(position, original base, new base)`. Returns an (invalid) 6-element tuple when there is no early termination site.

### Explanation

```
f=lambda i,j,k,*l,n=1:
  (j+k<4)         # If the last two bases are 1+1 (AA), 1+2 (AG) or 2+1 (AG)
    *(n,i,5)      #   Return (position, 1st base, 5 (T))
  +(i-k>2)        # If the 1st base is 5 (T) and the 3rd base 1 (A) or 2 (G)
    *(n+1,j,1)    #   Return (position, 2nd base, 1 (A))
  or(i-j>2)       # If the 1st base is 5 (T) and the 2nd base 1 (A) or 2 (G)
    *(n+2,k,1)    #   Return (position, 3rd base, 1 (A))
  or f(*l,n=n+3)  # Else process the next three bases

```

# Answer
> 4 votes
# C# (Visual C# Interactive Compiler), 138 bytes

```
x=>{for(int i=0;;i++)foreach(var k in"AGT")if("TAG TAA TGA".Contains(x.Remove(i,1).Insert(i,k+"").Substring(i-i%3,3)))return(i+1,x[i],k);}

```

Try it online!

# Answer
> 3 votes
# Python 2, ~~138~~ ~~133~~ ~~144~~ 142 bytes

```
f=lambda s,i=0:next((`i-~j`+s[j]+'TAA'[j]for j in[0,1,2]if re.match('.TTA.[[[AAAGGG]]].'[j::3]+'|.GA',s[:3])),s[6:]and f(s[3:],i+3))
import re

```

Try it online!

Returns `nXY` instead of `nX>Y`, or the empty string if there is no valid substitution.

# Answer
> 3 votes
# K (oK), 91 bytes

```
{,/(1+t),(x@t:(&u)+3*-3!p),(u:r@p)#'t@3!p:*&1=+/'r:0N 3#,//~(t:3 3#"TAATAGTGA")=\:/:0N 3#x}

```

Try it online!

I'm sure my solution can be significally golfed (I used too many named varialbes)

# Answer
> 3 votes
# Brainf\***, ~~696~~ ~~624~~ 397 Bytes

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

```

Uses the actual bytes 1, 2, 3, 4 to code for A, G, C, T respectively and outputs the position as a byte as well, so you only get the position modulo 256. Outputs position + two zero bytes if there is no possible mutation.

Try it online!

# How?

```
# X 1 Y 1 Z 1 C L L F
>>>>>>,,, #first codon is always ATG
++>>>+[
    - #zero exit flag
    <<,<<+<<+<<+> #input X into L1 for a trick later|set switch flags|seek to Y
    ,>>, #memory is now 0 1 Y 1 Z 1 4 X 0 0
    >>>[>+<<<<<<<<+>>>>>>>-]>[-<+>] #copy L1 onto cell0
            #memory is now X 1 Y 1 Z 1 4 X 0 0
    <<<<<<<< #begin switch on X
    -[-[-[-

    #case T:
        >- > #begin switch on Y
        -[-[-[-
        #case TT:
            >->[-]>->+++>>>+<<<<<] #TT not possible|zero out switch flags|inc exit flag|increase counter
        #case TC:
            >[- > #switch Z
            -[-[[-]>->+++>>+<<<<<] #cases TCT TCC not possible
             ] #TCG ~ TAG (fall through)
            >[- >+>->+<<<] #TCA ~ TAA
            ]<]
        #case TG:
            >[- >
            -[-[-[-
            >->++>>+<<<<] #TGT ~ TGA
            >[- >++>->+<<<]<] #TGC ~ TGA
            >[- >+>-->+<<<]<] #TGG ~ TAG
            >[-] #TGA is correct STOP
            ]<]
        #case TA:
            >[- >
            -[-[-[-
            >->++>>+<<<<] #TAT ~ TAA
            >[- >++>->+<<<]<] #TAC~TAA
             ] #TAG is correct STOP (fall through)
            >[-] #TAA is correct STOP
            ]
        <]
    #case C:
        ] (fall through)
      #we can fall through because we already put the letter into L1
    #case G:
        ] (fall through)
    #case A:
        >[- >
        -[-[
        #cases _C & _T not possible
            >->[-]>->+++>>>+<<<<<]
        #case _G:
            >[- >
            -[[-]>->+++>>>+<<<<<] #cases _GC/_GT/_GG are not possible
            >[->>>++++<<<] #_GA ~ TGA
            ]<]
        #case _A:
            >[- >
            -[-[[-]>->+++>>>+<<<<<] #cases _AC/_AT not possible
             ] #AAG ~ TAG (fall through)
            >[->>>++++<<<] #_AA ~ TAA
            ]
        ]

    #pointer is on cell5
    #if exit flag is zero then exit loop:
    >>>>
]
<<<.>.>. #print position and letters

```

It loads one codon at a time and uses a series of switch statements to look for all the possible codons that could mutate into a STOP. Further golfing ideas I have are:

* ~~For C\__, G\__, A\__ codons, the switch statements are almost identical. There has to be a way to collapse them~~ Done.
* ~~Is there a way to fall through cases in BF? Some of the cases are identical~~ There is! Just replace the entire case with `]`.
* There's probly a more optimal arrangement of the memory cells

The last bullet won't save too much; I'm happy with shaving 300 bytes for now.

# Answer
> 2 votes
# Retina 0.8.2, 68 bytes

```
((...)*?((.)(?=AA|AG|GA)|T(.(?=G)|G.)))(?<=(.)).*
$.1$6>$#4$*T$#5$*A

```

Try it online! Link includes test cases. Explanation:

```
(

```

Capture the string up to and including the mutation so that we can take the length.

```
 (...)*?

```

Capture as few codons as necessary.

```
 (

```

Choose either:

```
  (.)(?=AA|AG|GA)

```

a nucleotide followed by `AA`, `AG` or `GA` (using the count of captures of capture group 4 to identify the necessary mutation)

```
 |

```

or

```
  T(.(?=G)|G.)

```

a nucleotide either side of a `G`, both following a `T` (using the count of captures of capture group 5 to identify the necessary mutation)

```
 )

```

End of choice.

```
)

```

End the first capture at the nucleotide to be mutated.

```
(?<=(.))

```

Look behind to see the nucleotide to be mutated (trying to capture it inside the group turns out to be nontrivial).

```
.*

```

Also delete the rest of the input.

```
$.1

```

Output the position of the nucleotide to be mutated.

```
$6>

```

Output the nucleotide to be mutated plus a `>`.

```
$#4$*T

```

If the first alternative matched then mutate the nucleotide to a `T`.

```
$#5$*A

```

If the second alternative matched then mutate the nucleotide to an `A`.

# Answer
> 2 votes
# Red, 187 bytes

Thanks to @Jitse for finding a bug!

```
func[s][k: 0 until[v: take/part s 3 foreach t["TAA""TAG""TGA"][u: collect[repeat i 3[if(m: v/:i)<> n: t/:i[keep/only reduce[k + i m">"n]]]
]if 1 = length? u[print u exit]]k: k + 3 s =""]]

```

Try it online!

Using Red's `parse`:

# Red, 211 bytes

```
func[s][u: func[c][print[index? p p/1">"c]]t:"T"a:"A"c:"C"g:"G"parse
s[any[[[p:[a | g | c]"AA"|"AG"|"GA"](u"T")|[t p:[t | c | g][a | g]](u"A")|[t
p:[a | t | c]a](u"G")|["TG"p:[g | t | c]](u"A")](exit)| 3 skip]]]

```

Try it online!

# Answer
> 2 votes
# K (ngn/k), 56 bytes

```
{(1+;x;a)@'*<(*&~^5 6 9?4/+0N 3#)'i@[x;;:;]'a:1&3!i:!#x}

```

Try it online!

encodes `"TAGC"` as `0 1 2 3` respectively

returns `1 1 0` on error

important observation: there's no point trying to replace a nucleotide with anything other than `T` (when first in the codon) or `A` (when second or third)

`{` `}` function with argument `x`

`i:!#x` the list `0 1` ... `length(x)-1`, assigned to `i`

`a:1&3!i` mod 3 and min with 1: `0 1 1 0 1 1` ... `0 1 1`, assigned to `a`

`@[x;;:;]` a projection - tetradic `@` (a.k.a. "amend") with 2 missing arguments. this is a function that when given args `u` and `v`, creates a copy of `x` and replaces its `u`-th element with `v`

`i@[x;;:;]'a` call the projection with corresponding elements from `i` and `a`

`(` `)'` each

`0N 3#` reshape to a 3 columns wide matrix

`4/+` decode from base 4. for a codon `u v w` this is `(16*u)+(4*v)+w`

`*&~^5 6 9?` find the index of the first codon that decodes to 5 (`TAA`) or 6 (`TAG`) or 9 (`TGA`)

`*<` from the length(`x`) such possible first codons, find the index `p` of the one that terminates earliest

`(1+;x;a)@'` make a list of `(1+p;x[p];a[p])`

---
Tags: code-golf, string, bioinformatics
---


title: Rational Number RNG

text:
# Question
Title: Rational Number RNG
# The Objective

Build a random number generator whose range is \\$\left\[0,1\right) \cap \mathbb{Q} .\\$

This is, build a random number generator that can produce any value that's:

1. at least \\$0 \\,;\\$
2. not \\$1\\$ or greater; and
3. expressible as the ratio of two integers.

---

# What's the fuss?

This RNG is weird. Its range is nowhere *connected*, but is *dense* in the interval!

---

# The probability mass function

We define an ordering for all values that the RNG can return, such that each return value \\$ x\\$ can be associated with an index \\$ i .\\$ Then, the probability of returning \\$x\_i\\$ should be \\$P\left(x\_i\right) = {\left(\frac{1}{2}\right)}^{i} .\\$ Since $$ \sum\limits\_{i=1}^{\infty}{{\left(\frac{1}{2}\right)}^{i}} = 1 \\,, $$ this yields a total probability of \\$1 ,\\$ where the numbers earlier in the ordering are significantly more likely than numbers later in the ordering.

The ordering is:

1. Start with the first value, \\$ \frac{0}{1}.\\$
2. Increment the numerator.
3. If the numerator equals the denominator, then:

* reset the numerator to \\$ 0 ;\\$ and
    * increment the denominator.
4. Add the value to the ordering *if* it's not equivalent to a value already in the ordering.

* For example, \\$\frac{2}{4}\\$ is constructed after \\$\frac{1}{2} ,\\$ so it's *not* added to the ordering.
5. Go back to Step (2).

For example, the first few values and their corresponding probabilities are: $$ \begin{array}{r|c|c|c|c|c|c|c|c|c|c} \textbf{Index}~\left(i\right) & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & \cdots \\\hline \textbf{Value}~\left(x\right) & \frac{0}{1} & \frac{1}{2} & \frac{1}{3} & \frac{2}{3} & \frac{1}{4} & \frac{3}{4} & \frac{1}{5} & \frac{2}{5} & \frac{3}{5} & \frac{4}{5} & \cdots \\\hline \textbf{Probability}~\left(P\right) & \frac{1}{ 2} & \frac{1}{ 4} & \frac{1}{ 8} & \frac{1}{ 16} & \frac{1}{ 32} & \frac{1}{ 64} & \frac{1}{ 128} & \frac{1}{ 256} & \frac{1}{ 512} & \frac{1}{1024} & \cdots \end{array} \_{\large{.}} $$

---

# Rules

1. There is no input. The RNG outputs a number upon invocation.
2. You must use rational number arithmetic. In particular, `X` must be represented as a rational number. If your language doesn't natively support it, use a pair of integers. For example, in Haskell, `Rational` is a valid type.
3. As long as the numerator and the denominator are distinguishable, the output format doesn't matter.
4. As this is a code-golf, the shortest code in bytes wins.

# Answer
# APL (Dyalog Unicode), 27 bytes

```
i⊃⍸1=∘.(>×∨)⍨⍳2+i←1+⍣{?2}¯1

```

Try it online!

Thanks to @ngn for this function. Since this is not strictly *my* answer, I'll keep the older answer below this one. Uses `⎕IO←0`.

The function returns a pair in the form `denominator numerator`.

### How:

```
i⊃⍸1=∘.(>×∨)⍨⍳2+i←1+⍣{?2}¯1 ⍝ Dfn
                         ¯1 ⍝ Literal -1
                     {?2}   ⍝ Roll. Since IO is 0, this will roll either 0 or 1
                    ⍣       ⍝ Power. Repeats the function to the left until the right argument is 0.
                  1+        ⍝ 1 plus. The whole expression above will result in 1+1+1+...-1;
                            ⍝ each iteration has a 50% chance of being the last one.
                i←          ⍝ Assign the result to i
             ⍳2+            ⍝ Generate the vector [0..2+i]
            ⍨               ⍝ Use it as both arguments (⍺ and ⍵) to the fork:
     ∘.(>×∨)                ⍝ For each element of the left argument (⍺), apply: (⍺ > ⍵) × (⍺ ∨ ⍵);
                            ⍝ This will result in a matrix of 0s (if ⍵>⍺) and the GCDs between ⍺ and ⍵.
   1=                       ⍝ Check which elements are 1 (where ⍺ is coprime with ⍵)
  ⍸                         ⍝ Find the coordinates (which will be denominator and numerator) of truthy values
i⊃                          ⍝ pick the i-th element.

```

---

Old answer:

# APL (Dyalog Unicode), 55 bytes

```
{(?0)<2÷⍨∨/⍵:∇∊((⊂0,2⊃⍵+1),⊂1 0+⍵)[1+(⊃⍵)<¯1+2⊃⍵]⋄⍵}0 1

```

Try it online!

Statistics

Terribly inefficient port of @Arnauld's answer, so go upvote him.
> 8 votes

# Answer
# JavaScript (ES6), 81 bytes

Returns \\$p/q\\$ as `[p,q]`.

```
f=(p=0,q=1)=>Math.random()<(g=(a,b)=>b?g(b,a%b):a)(p,q)/2?f(++p-q?p:!++q,q):[p,q]

```

Try it online!

Or Try some statistics!

### How?

We recursively build the fractions \\$p/q\\$ in the relevant order, but without any explicit deduplication, until a random number picked in \\$\[0,1\[\\$ is greater than or equal to \\$gcd(p,q)/2\\$.

If \\$p\\$ and \\$q\\$ are not coprime, we have \\$gcd(p,q)/2\ge1\\$, which always triggers the recursive call. This is the expected behavior because the corresponding fraction must be discarded.

If \\$p\\$ and \\$q\\$ are coprime, we have \\$gcd(p,q)/2=1/2\\$, which is the desired probability of triggering the next call.

### Commented

```
f = (                 // f is a recursive function taking:
  p = 0,              //   p = numerator, starting at 0
  q = 1               //   q = denominator, starting at 1
) =>                  //
  Math.random() <     // pick a random number in [0,1[
  (g = (a, b) =>      // g is a recursive function computing the gcd of 2 integers
    b ?               //   if b is not equal to 0:
      g(b, a % b)     //     recursive call with (b, a mod b)
    :                 //   else:
      a               //     return a
  )(p, q) / 2 ?       // if our random number is less than gcd(p, q) / 2:
    f(                //   do a recursive call:
      ++p - q ? p     //     increment p if p < q - 1
              : !++q, //     otherwise: set p to 0 and increment q
      q               //
    )                 //   end of recursive call
  :                   // else:
    [p, q]            //   stop recursion and return [p, q]

```
> 20 votes

# Answer
# Ruby, ~~74~~ 67 bytes

Probably not the golfiest solution for Ruby, but it was the first thing that sprung to mind. Increment the counter `$.` (starts at 0) each time `rand` is at least 0.5 to determine the index, then determine the list of rationals and output the right one.

-7 bytes from histocrat.

```
d,*a=1r
$.+=1until rand<0.5
a|=(0...d+=1).map{|n|n/d}until p *a[$.]

```

Try it online!
> 10 votes

# Answer
# Julia, ~~61~~ ~~49~~ 71 bytes

```
p>q=rand()<.5 ? (p<q-1 ? (while gcd(p+=1,q)!=1 end;p>q) : 1>q+1) : p//q

```

In un-golfed form, this reads

```
function f(p,q)                      # define the function
    if rand() < 0.5                  # flip a coin.
        if p < (q - 1)               # if the coin gives heads, check if p < (q - 1)
            while gcd(p+1, q) != 1   # if the greatest common divisor or p+1 and q is not equal to 1
                p = p + 1            # we increment p, because otherwise we'd get a fraction we already saw.
            end
            return f(p, q)           # recursively call f(p, q) (where p has been incremented)
        else
            return f(1, q+1)         # if p is not greater than q - 1, we recursively call f(1, q+1)
        end
    else
        return p//q                  # If the coin flip gives tails, we return the Rational number p//q
    end
end

```

Now let's check to make sure we did this right:

```
julia> using UnicodePlots; data = [0>1 for _ in 1:10_000_000]; histogram(data)
                ┌                                        ┐
   [0.0 , 0.05) ┤▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 5000106
   [0.05, 0.1 ) ┤ 0
   [0.1 , 0.15) ┤ 1168
   [0.15, 0.2 ) ┤▇ 82600
   [0.2 , 0.25) ┤ 0
   [0.25, 0.3 ) ┤▇▇ 313684
   [0.3 , 0.35) ┤▇▇▇▇▇▇▇▇ 1250427
   [0.35, 0.4 ) ┤ 39124
   [0.4 , 0.45) ┤ 310
   [0.45, 0.5 ) ┤ 0
   [0.5 , 0.55) ┤▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 2498798
   [0.55, 0.6 ) ┤ 168
   [0.6 , 0.65) ┤ 19403
   [0.65, 0.7 ) ┤▇▇▇▇ 625484
   [0.7 , 0.75) ┤ 77
   [0.75, 0.8 ) ┤▇ 166131
   [0.8 , 0.85) ┤ 2473
   [0.85, 0.9 ) ┤ 47
                └                                        ┘
                                Frequency

julia> for frac in [(0//1), (1//2), (1//3), (2//3), (1//4), (3//4), (1//5), (2//5), (3//5), (4//5), (1//6), (5//6)]
           freq = count(x -> x == frac, data)/length(data)
           println("P($(frac)) ≈ $freq")
       end
P(0//1) ≈ 0.5000106
P(1//2) ≈ 0.2498798
P(1//3) ≈ 0.1250427
P(2//3) ≈ 0.0625484
P(1//4) ≈ 0.0313065
P(3//4) ≈ 0.0156477
P(1//5) ≈ 0.0077772
P(2//5) ≈ 0.0039116
P(3//5) ≈ 0.0019398
P(4//5) ≈ 0.0009654
P(1//6) ≈ 0.0004828
P(5//6) ≈ 0.0002473

```

Notice that `P(5//6) ≈ 0.5 * P(1//6)` as required since `2//6`, `3//6`, and `4//6` are reducible fractions.

Try it online!
> 9 votes

# Answer
# PHP, 139 bytes

```
for($r=rand()/(getrandmax()+1),$b=$p=1;$r<1/$p*=2;)for($f=0;!$f;)for(++$a-$b?:++$b&&$a=1,$f=$i=1;++$i<=$a;$f&=0<$b%$i+$a%$i);echo+$a."/$b";

```

Try it online!
> 3 votes

# Answer
# , 41 bytes

```
[:({[:~.@,(i.%x:)"0@i.@+&2)>:^:(?@2)^:_@0

```

Try it online!

At a high-level, I stole ValueInk's idea for first flipping a coin until it comes up heads, and using that number to index into the ordered list of rationals.
> 3 votes

# Answer
# MATL, 31 bytes

```
`rEk}@EU:2M&\v1M/t1<fw6#uX&@)Z)

```

Output is numerator, then denominator. Try it online!

Or check relative frequencies in 1000 realizations (header and footer added; one more byte necessary in main code; TIO running time about 30 seconds). Format is: `num den freq`, each row corresponding to a number. Note that relative frequencies are increasingly imprecise down the table, because the corresponding numbers occur less often.

Here is a set of relative frequencies obtained from 100000 realizations (offline compiler):

```
0       1 0.49828
1       2 0.25022
1       3 0.12643
2       3  0.0611
1       4 0.03128
3       4 0.01657
1       5 0.00814
2       5 0.00383
3       5 0.00206
4       5 0.00099
1       6 0.00047
5       6 0.00024
1       7  0.0002
2       7   6e-05
3       7   6e-05
4       7   5e-05
5       7   2e-05

```
> 3 votes

# Answer
# WDC 65816 machine code, 77 bytes

Hexdump:

```
00000000: 6407 6405 e607 3b85 09e2 31a2 039a 6869  d.d...;...1...hi
00000010: b248 6300 ca10 fac2 30a5 091b a501 102c  .Hc.....0......,
00000020: e605 a505 c507 d006 6405 e605 80d6 a607  ........d.......
00000030: 8609 c509 f00f 9004 e509 80f4 488a 38e3  ............H.8.
00000040: 01aa 6880 ebc9 0100 d0d6 80ba 60         ..h.........`

```

Assembly:

```
    STZ $07
    STZ $05
earlier_loop:
    INC $07
loop:
    TSC
    STA $09
    SEP #$31
    LDX #$03
    TXS
    PLA
    ADC #$B2
rngloop:
    PHA
    ADC $00,s
    DEX
    BPL rngloop
    REP #$30
    LDA $09
    TCS
    LDA $01
    BPL done
after_rng:
    INC $05
    LDA $05
    CMP $07
    BNE someplace
    STZ $05
    INC $05
    BRA earlier_loop
someplace:
    LDX $07
gcd:
    STX $09
    CMP $09
    BEQ gcd_end
    BCC gcd_else
    SBC $09
    BRA gcd
gcd_else:
    PHA
    TXA
    SEC
    SBC $01,s
    TAX
    PLA
    BRA gcd
gcd_end:
    CMP #$0001
    BNE after_rng
    BRA loop
done:
    RTS

```

## I/O:

* RNG seed in $01-$04 (32 bits, anything but 0)
* output is in $05 (numerator), $07 (denom.)
* overwrites $00, $09
* assumes 16-bit accumulator on entry
* messes with the stack so best called with all interrupts disabled

This was more difficult than I first expected. I misread the challenge description and skipped the part about repeats not being counted. The 65816 doesn't have any built-in RNG or floating point math, and it doesn't even have integer multiply/divide. I used the RNG algorithm from cc65, a 6502 C compiler, and adapted it a bit (made it smaller). Then I used the z80 GCD algorithm from Rosetta Code and translated it into 65816 assembly.

Here's a sample of outputs after running for some number of iterations:

```
0/1: 0x60e4 = 24804
1/2: 0x3122 = 12578
1/3: 0x187c = 6268
2/3: 0x0c7d = 3197
1/4: 0x05bd = 1469
3/4: 0x0313 = 787

```

As you can see, each next fraction is about half as likely as the previous one. There isn't a good online 65816 "IDE", but I'm working on making one. For now, if you want to test this, you can write a small bit of wrapper code which logs outputs of the subroutine into a table in RAM and view that table with a debugging SNES emulator (I recommend bsnes-plus).

Big thanks to @p4plus2 and @Alcaro for help with optimizing the code.
> 3 votes

# Answer
# Javascript ES6, 98 chars

```
g=(x,y)=>y?g(y,x%y):x
for(x=y=1;y;++x)for(y=0;y<x;++y)if(Math.random()<.5==g(x,y))y=alert(y+"/"+x)

```

### Demo with `console.log` instead of `alert`:

```
g=(x,y)=>y?g(y,x%y):x
for(x=y=1;y;++x)for(y=0;y<x;++y)if(Math.random()<.5==g(x,y))y=console.log(y+"/"+x)
```

### Probability check:

```
g=(x,y)=>y?g(y,x%y):x
f=()=>{for(x=y=1;y;++x)for(y=0;y<x;++y)if(Math.random()<.5==g(x,y))return y+"/"+x}
r={}
for(q=0;q<32768;++q)r[x=f()]=~~r[x]+1
console.log(Object.keys(r).sort((x,y)=>r[y]-r[x]).map(x=>x+" "+r[x]).join`
`)
```

```
.as-console-wrapper.as-console-wrapper{max-height:100vh}
```
> 1 votes

# Answer
# ink, 137 bytes

```
=r
~temp e=0
-(d)~e++
~temp n=-1
-(l)~n++
{e-n:{RANDOM(0,c(e,n)<2):{n}/{e}->->}->l}->d
==function c(a,b)
{b:
~return c(b,a%b)
}
~return a

```

Try it online!

Okay, strap in, this was an adventure.

My first attempts at solving this with a full program rather than a function (well, it's a stitch rather than a function, but the point still stands) failed horribly. The logic was sound, but for some reason I was getting `1/3` more than twice as often as `1/2`, and that pattern held for more than 2000 test runs - that wasn't the only place where it failed, but it was the most noticable.
So I broke the code down into parts. I ungolfed it, I added debug messages, it didn't work. I ported the core logic to python, as faithfully as I possibly could, and it worked fine. To simplify the testing process, I changed a minor detail to allow me to call my code multiple times during a single run of a program (used a separate variable rather than a readcount for some logic, because readcounts can't be reset). I ran my code a few hundred times as part of a single program, rather than running the program a few hundred times.
And suddenly it worked.

So I figured the problem was related to the readcount I was using - those have been known to act up at times. So I went back to having my code be a full program, but kept the new variable. And it went back to not working.

So I figured, okay, maybe the RNG isn't uniform over the course of multiple runs of a program, but tends towards uniformity if called repeatedly in a single program. That sounded vaguely reasonable - well it kinda didn't, but I was getting desperate. So I wrote two small programs to test my hypothesis - one that generated 100 random values (which I ran once), and one which generated a single random value (which I ran 100 times). And they both gave me about 50 `0`s and 50 `1`s.

At my wits' end at this point, I had no idea what was going on, and frankly I still have no idea where to even begin when it comes to figuring it out.
So I'm posting a stitch. It would be 18 bytes shorter if I could have it be a full program (code is here), but even though the logic would be entirely identical, that appears to not work as it should, and any change I try to make only serves to break it in a different way. Only the gods know why, and they surely envy my ignorance.

With that rant out of the way, there are some neat tricks in the code, so let's look at it.

The basic idea is that after each number is generated, we have a 50% chance of outputting it, and a 50% chance of continuing to the next number - this strategy wasn't obvious to me at first, but looking at it it becomes obvious that each output will be half as likely as the one before, twice as likely as the next one, and equally as likely as the all the subsequent values combined - which is exactly what we want.

Now that `RANDOM` call doesn't obviously look like a 50/50 thing. Well, let's look a bit deeper. You'll notice that its second parameter is actually a boolean expression - meaning it will only ever be `0` or `1`. If it's `1`, `RANDOM` will output either `0` or `1` with equal probability, meaning we have a 50% chance of outputting the current numerator and denominator (it happens if `RANDOM` would generate a non-zero value), while if it's `0` we effectively skip a number.
So what is that `c` function then? Well, if you look further down, you'll find it's Euclid's algorithm for finding the greatest common divisor of two numbers. If that's greater than `1`, we won't want to output the number - there's another representation of that number with a strictly smaller numerator and denominator, so we've already skipped that number. But if it is `1`, it's a number we may want to output, so we check if the GCD is `1`, plug the result of the comparison into the `RANDOM` call, and call it a day.
conveniently enough, anything is a divisor of `0`, so if the numerator is `0` we will skip the number if the denominator isn't `1`. Which happens to be exactly what we want.
> 1 votes

# Answer
# 05AB1E, ~~29~~ 28 bytes

```
®1‚[0L+Ð5°D<Ýs/Ωs¿;@#`αi>®0ǝ

```

Inspired by *@Arnauld*'s approach.

Try it online or see the counts of 100 outputs (it's a bit too slow to do more than 100 in TIO.. \>.\>).

**Explanation:**

NOTE: 05AB1E doesn't have a builtin to get a decimal in the range \\$\[0,1)\\$, so instead I create a list in the range \\$\[0,1)\\$ in increments of \\$0.00001\\$ manually, and get a random value from this list.

```
®1‚           # Push -1 and 1, and pair them: [-1,1]
   [          # Start an infinite loop:
    0L+       #  Increase only the first value by 1 (by adding [1,0])
       Ð      #  Triplicate this pair
    5°        #  Push 10 to the power 5: 10,000
      D<      #  Duplicate it, and decrease the copy by 1 to 9,999
        Ý     #  Create a list in the range [0,9999]
         s/   #  Swap to get the duplicated 10,000, and divide each item by it:
              #   [0, 0.00001, 0.00002, 0.00003, ..., 0.99997, 0.99998, 0.99999]
           Ω  #  Pop and push a random item from this list
    s         #  Swap to get one of the pairs at the top again
     ¿        #  Get the greatest common divisor (gcd) of the values in this pair
      ;       #  Halve it
    @         #  If the random value is larger than or equal to this:
     #        #   Stop the infinite loop
    `αi       #  If the absolute difference between the two values in the pair is exactly 1:
       >      #   Increase both values in the pair by 1
        ®0ǝ   #   And then replace the first value with -1
              # (after the loop, output the pair at the top of the stack implicitly)

```
> 1 votes

---
Tags: code-golf, random, rational-numbers
---


title: Busy beaver of sorts

text:
# Question
Title: Busy beaver of sorts
I'm surprised this hasn't been done yet, but here we go.

Create a program which prints some number of 1s (ideally as large as possible) before halting.

The rules are simple:

Your program is bounded to 50 bytes in size.

Your output must only be a continuous row of 1s (plus trailing newline if it has to be added), without any breaks in the middle.

Your program must halt. No infinite loops.

Your program must not use STDIN or output to STDERR.

Your program must use STDOUT or closest equivalent.

Your score is the amount of 1s your program prints before halting.

Have fun.

# Answer
# Runic Enchantments, Score: Aproximately ~~(10↑↑200)~~ (10↑↑303)18.877

```
>>>yybbqf:p'!A'!A'!A'!A'!A'!A'!A'!A'!A'!AFm1)b*?*@

```

Try it online!

Utilizes Stephen's idea of factorials (they're kind of expensive in Runic, so I hadn't considered them originally) and managed to squeeze out ~~two~~ *three hundred* of them via implicit edge looping. Value-in is `15^15` (`437,893,890,380,859,375`) and the resulting value is then multiplied against the *string* `1111` (`bbq` is just as long as `"1"` and produces more 1s).

`200->300` accomplished by removing flow control logic and simply raising the "skip when true" to jump over the start of the program (executes the `:p` for bonus length, but is dwarfed by the factorials, but is responsible for the extra 3 powers of 10 in the tower).

"Wolfram|Alpha doesn't understand your query"
> 3 votes

# Answer
# Python, 9^9^9^9^9^9^9^9^9^9^9^9^9 (or 9↑↑13)

```
print("1"*(9**9**9**9**9**9**9**9**9**9**9**9**9))

```

I hope this is right

Try it online!
> 2 votes

# Answer
# MATLAB, Score: 9↑↑(2↑(10↑313))

```
x=9;
while(cputime<realmax/2)
x=x^x;
end
ones(1,x)

```

Try it online!

`cputime` counts the number of seconds that the MATLAB thread actually runs on the CPU as a double. `realmax` is the maximum double, `~10^308`; I divide by 2 because cputime will rollover back to zero and we actually need the loop to stop. According to the profiler, on my computer MATLAB can run the loop `1e6` times in about `3.7 seconds`. That means we'll perform `x=x^x` about `10^313` times! That isn't just 9↑↑(10↑313), because it compounds on every loop. It's 9↑↑(2↑(10↑313)) I think. I could cheat and make the condition `cputime==realmax/2`, and then it would be up to random chance when the program finally ends, making an absolutely insane number, but one that can't be calculated.

---

# MATLAB, Score: 9↑↑79 (or about (10↑↑78)8.568)

```
f=@(x) factorial(x)^x;
ones(1,f(f(f(f(9^9^9^9)))))

```

Try it online!

Probly not as big as the power tower answers though. I need to figure out a short way to do that here.
> 2 votes

# Answer
# cQuents, Aproximately (10↑↑45)7.347

```
"#t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!&1

```

Try it online!

Note that it does not start printing the 1s until it calculates the result of the factorial, so this probably will not run on any real system.

According to Wolfram Alpha, this value equals

or in plaintext

```
10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^(10^7.346902562777663))))))))))))))))))))))))))))))))))))))))))))

```
> 2 votes

# Answer
## Python 3 approx 9↑↑(36^8) 9↑↑(36↑(9↑↑3))

```
print("1"*eval("**".join("9"*int('z'*9**9**9,36)))

```

Must calculate first.

(Edited because I'm bad at math notation, and to include an improvement from randomdude999)
> 2 votes

# Answer
# PHP, 43 bytes, Score: ~1e17 (based on my PC performance)

```
set_time_limit(-1);while(time()<4e9)echo 1;

```

Try it online!

This will run until `2096-10-02` and then stop. This isn't an infinite loop as it will finally halt. I can set it to longer dates, but I think `4e9` or `2096-10-02` is good enough for me, it is about the idea
> 1 votes

# Answer
# 05AB1E, approx. (10↑↑46)10.994 amount of `1`s (50 bytes)

```
žm!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1×

```

**Explanation:**

```
žm             # Push the builtin 9876543210
  !!!...!!!    # Take the factorial 46 times
           1×  # Push that many 1s as string
               # (after which it's output implicitly as result)

```

This will print exactly \\$9876543210↑↑46\\$ amount of `1`s, or approx. \\$(10↑↑46)^{10.994}\\$ (thanks to *@Draco18s* for explaining how to calculate this \\$(10↑↑a)^b\\$ approximation.
> 0 votes

---
Tags: code-challenge, busy-beaver
---


title: Ratio of Uppercase Letters to Lowercase

text:
# Question
Title: Ratio of Uppercase Letters to Lowercase
In this challenge you and your friends are debating on which case is better, uppercase or lowercase? To find out, you write a program to do this for you.

Because esolangs scare your friends, and verbose code scares you, your code will need to be as short as possible.

---

## Examples

```
PrOgRaMiNgPuZzLeS & CoDe GoLf
0.52 uppercase

DowNGoAT RiGHtGoAt LeFTGoat UpGoAT
0.58 uppercase

Foo BaR Baz
0.56 lowercase

```

---

## Specifications

The input will consist only of ASCII characters. All non-alphabetic characters should be ignored. There will be at least 1 character of each case

The output should be the amount of the case that appears the most often over the total amount of alphabetic characters. It should be a decimal accurate to *at least* 2 decimal places. If uppercase appears more often, the output should end with `uppercase`, or `lowercase`.

There will never the the same amount of uppercase and lowercase characters.

# Answer
> 2 votes
# Pyth - 40 bytes

This is the first time i've ever used vectorized string formatting which is pretty cool.

```
Kml-zrzd2eS%Vm+cdsK" %sercase"Kc"upp low

```

Test Suite.

# Answer
> 7 votes
# JavaScript (ES6) 87 bytes

**Edit** 1 byte saved thx ETHProductions
**Edit** 1 more byte saved thx l4me

An anonymous function. Long, but I didn't find a way to golf this more

```
s=>(l=t=0,s.replace(/[a-z]/ig,c=>l+=++t&&c>'Z'),l/=t,l<.5?1-l+' upp':l+' low')+'ercase'

```

**Less golfed**

```
s=>( // arrow function returning the value of an expression
  // here I use comma for clarity,
  // in the golfed version it's all merged in a single expression
  t = 0, // counter for letters
  l = 0, // counter for lowercase letters
  s.replace(
    /[a-z]/ig, // find all alphabetic chars, upper or lowercase
    c => // execute for each found char (in c)
        l += ++t && c>'Z', // increment t, increment l if c is lowercase
  ),
  l /= t, // l is the ratio now
  ( l < .5 // if ratio < 1/2
    ? (1-l) +' upp' // uppercase count / total (+" upp")
    : l +' low'     // lowrcase count / total (+" low")
  ) + 'ercase' // common suffix
)

```

# Answer
> 4 votes
# CJam, 47 45 bytes

```
q__eu-\_el-]:,_:+df/" low upp"4/.+:e>"ercase"

```

Try it online.

Not golfing for too long...

### Explanation

```
q               e# Read input.
__eu-           e# Get only the lowercase characters.
\_el-           e# Get only the uppercase characters.
]:,             e# Get the lengths of the two strings.
_:+             e# Sum of the lengths.
df/             e# Lengths divided by the sum of the lengths.
" low upp"4/.+  e# Append the first number with " low" and the second " upp"
:e>             e# Find the maximum of the two.
"ercase"        e# Output other things.

```

# Answer
> 4 votes
## Japt, 58 bytes

```
A=Uf"[a-z]" l /Uf"[A-Za-z]" l)>½?A+" low":1-A+" upp" +`ÖÐ

```

(Note: SE stripped a special char, before `Ö`, so please click the link to get the proper code)

# Answer
> 4 votes
# , ~~133 123 118 108 106 105~~ 104 bytes

Golfed down 10 bytes thanks to @ovs,8 thanks to @Giuseppe, and 10 again thanks to @ngm. At this point it's really a collaborative effort where I provide the bytes and others take them off ;)

```
function(x)cat(max(U<-mean(utf8ToInt(gsub('[^a-zA-Z]',"",x))<91),1-U),c("lowercase","uppercase")[1+2*U])

```

Try it online!

# Answer
> 3 votes
# Julia, ~~76~~ 74 bytes

```
s->(x=sum(isupper,s)/sum(isalpha,s);(x>0.5?"$x upp":"$(1-x) low")"ercase")

```

This is a lambda function that accepts a string and returns a string. To call it, assign it to a variable.

Ungolfed:

```
function f(s::AbstractString)
    # Compute the proportion of uppercase letters
    x = sum(isupper, s) / sum(isalpha, s)

    # Return a string construct as x or 1-x and the appropriate case
    (x > 0.5 ? "$x upp" : "$(1-x) low") * "ercase"
end

```

Saved 2 bytes thanks to edc65!

# Answer
> 3 votes
# MATL, 49 ~~50~~ bytes

Uses current version (4.1.1) of the language, which is earlier than the challenge.

```
jt3Y2m)tk=Ymt.5<?1w-YU' upp'h}YU' low'h]'ercase'h

```

### Examples

```
>> matl
 > jt3Y2m)tk=Ymt.5<?1w-YU' upp'h}YU' low'h]'ercase'h
 >
> PrOgRaMiNgPuZzLeS & CoDe GoLf
0.52 uppercase

>> matl
 > jt3Y2m)tk=Ymt.5<?1w-YU' upp'h}YU' low'h]'ercase'h
 >
> Foo BaR Baz
0.55556 lowercase

```

### Explanation

```
j                   % input string
t3Y2m)              % duplicate. Keep only letters
tk=Ym               % duplicate. Proportion of lowercase letters
t.5<?               % if less than .5
    1w-             % compute complement of proportion
    YU' upp'h       % convert to string and append ' upp'
}                   % else
    YU' low'h       % convert to string and append ' low'
]                   % end
'ercase'            % append 'ercase'

```

# Answer
> 3 votes
## Python 2, ~~114~~ 110 bytes

```
i=input()
n=1.*sum('@'<c<'['for c in i)/sum(c.isalpha()for c in i)
print max(n,1-n),'ulpopw'[n<.5::2]+'ercase'

```

# Answer
> 3 votes
# Perl 6,  ~~91 70 69 63~~  61 bytes

~~```
{($/=($/=@=.comb(/\w/)).grep(*~&' 'ne' ')/$/);"{$/>.5??$/!!1-$/} {<low upp>[$/>.5]}ercase"} # 91

```

```
{$/=m:g{<upper>}/m:g{\w};"{$/>.5??$/!!1-$/} {<low upp>[$/>.5]}ercase"} # 70

```

```
{"{($/=m:g{<upper>}/m:g{\w})>.5??$/!!1-$/} {<low upp>[$/>.5]}ercase"} # 69

```

```
{"{($/=m:g{<upper>}/m:g{\w})>.5??"$/ upp"!!1-$/~' low'}ercase"} # 63

```~~
```
{"{($/=m:g{<:Lu>}/m:g{\w})>.5??"$/ upp"!!1-$/~' low'}ercase"} # 61

```

Usage:

```
# give it a lexical name
my &code = {...}

.say for (
  'PrOgRaMiNgPuZzLeS & CoDe GoLf',
  'DowNGoAT RiGHtGoAt LeFTGoat UpGoAT',
  'Foo BaR Baz',
)».&code;

```

```
0.52 uppercase
0.580645 uppercase
0.555556 lowercase

```

# Answer
> 3 votes
# C#, 135 bytes

Requires:

```
using System.Linq;

```

Actual function:

```
string U(string s){var c=s.Count(char.IsUpper)*1F/s.Count(char.IsLetter);return(c>0.5?c+" upp":1-c+" low")+"ercase";}

```

With explanation:

```
string U(string s)
{
    var c = s.Count(char.IsUpper) // count uppercase letters
               * 1F               // make it a float (less bytes than (float) cast)
               / s.Count(char.IsLetter); // divide it by the total count of letters
    return (c > 0.5
        ? c + " upp"  // if ratio is greater than 0.5, the result is "<ratio> upp"
        : 1 - c + " low") // otherwise, "<ratio> low"
        + "ercase"; // add "ercase" to the output string
}

```

# Answer
> 2 votes
## Mathematica, ~~139~~ 105 bytes

```
a=ToString;If[(b=1.#~(c=StringCount)~Alphabet[]/c[#,_?LetterQ])<.5,a[1-b]<>" upp",a@b<>" low"]<>"ercase"&

```

Verbose code is scary, but I'll have to live with it...

# Answer
> 2 votes
# PHP, 140 129 characters

My first round of golf -- not too bad for a 'standard' language, eh? :-)

Original:

```
function f($s){$a=count_chars($s);for($i=65;$i<91;$i++){$u+=$a[$i];$l+=$a[$i+32];}return max($u,$l)/($u+$l).($u<$l?' low':' upp').'ercase';}

```

Shortened to 129 characters thanks to @manatwork:

```
function f($s){$a=count_chars($s);for(;$i<26;$u+=$a[$i+++65])$l+=$a[$i+97];return max($u,$l)/($u+$l).' '.($u<$l?low:upp).ercase;}

```

With comments:

```
function uclcratio($s)
{
  // Get info about string, see http://php.net/manual/de/function.count-chars.php
  $array = count_chars($s);

  // Loop through A to Z
  for ($i = 65; $i < 91; $i++) // <91 rather than <=90 to save a byte
  {
    // Add up occurrences of uppercase letters (ASCII 65-90)
    $uppercount += $array[$i];
    // Same with lowercase (ASCII 97-122)
    $lowercount += $array[$i+32];
  }
  // Compose output
  // Ratio is max over sum
  return max($uppercount, $lowercount) / ($uppercount + $lowercount)
  // in favour of which, equality not possible per challenge definition
         . ($uppercount < $lowercount ? ' low' : ' upp') . 'ercase';
}

```

# Answer
> 2 votes
# Ruby, 81+1=82

With flag `-p`,

```
$_=["#{r=$_.count(a='a-z').fdiv$_.count(a+'A-Z')} low","#{1-r} upp"].max+'ercase'

```

It's lucky that for numbers between 0 and 1, lexicographic sorting is the same as numeric sorting.

# Answer
> 2 votes
# Common Lisp, 132 bytes

```
(setq s(read-line)f(/(count-if'upper-case-p s)(count-if'alpha-char-p s)))(format t"~f ~aercase"(max f(- 1 f))(if(> f .5)"upp""low"))

```

Try it online!

# Answer
> 1 votes
# CoffeeScript, 104 characters

```
 (a)->(r=1.0*a.replace(/\W|[A-Z]/g,'').length/a.length)&&"#{(r>.5&&(r+' low')||(1-r+' upp'))+'ercase'}"

```

coffeescript was initially trying to pass the intended return value as an argument to the "r" value, which failed and was super annoying because r was a number, not a function. I got around it by placing an `&&` between the statements to separate them.

# Answer
> 1 votes
# Pyth, ~~54~~ 53

One byte saved thanks to @Maltysen

```
K0VzI}NG=hZ)I}NrG1=hK;ceS,ZK+ZK+?>ZK"low""upp""ercase

```

Try it online

```
K0                  " Set K to 0
                    " (Implicit: Set Z to 0)

Vz                  " For all characters (V) in input (z):
  I}NG              " If the character (N) is in (}) the lowercase alphabet (G):
    =hZ             " Increment (=h) Z
  )                 " End statement
  I}NrG1            " If the character is in the uppercase alphabet (rG1):
    =hK             " Increment K
;                   " End all unclosed statements/loops

c                   " (Implicit print) The division of
  e                 " the last element of
    S,ZK           " the sorted (S) list of Z and K (this returns the max value)
+ZK                 " by the sum of Z and K

+                   " (Implicit print) The concatenation of
  ?>ZK"low""upp"    " "low" if Z > K, else "upp"
  "ercase"          " and the string "ercase".

```

# Answer
> 1 votes
## Seriously, 58 bytes

```
" upp"" low"k"ercase"@+╗,;;ú;û+∩@-@-;l@ú@-l/;1-k;i<@╜@ZEεj

```

Hex Dump:

```
22207570702222206c6f77226b2265726361736522402bbb2c3b3ba33b
962bef402d402d3b6c40a3402d6c2f3b312d6b3b693c40bd405a45ee6a

```

It only works on the downloadable interpreter...the online one is still broken.

Explanation:

```
" upp"" low"k"ercase"@+╗                                    Put [" lowercase"," uppercase"]
                                                            in reg0
                        ,;;ú;û+∩@-@-                        Read input, remove non-alpha
                                    ;l@                     Put its length below it
                                       ú@-                  Delete lowercase
                                          l                 Get its length
                                           /                Get the ratio of upper/total
                                            ;1-k            Make list [upp-ratio,low-ratio]
                                                ;i<         Push 1 if low-ratio is higher
                                                   @        Move list to top
                                                    ╜@Z     Zip it with list from reg0
                                                       E    Pick the one with higher ratio
                                                        εj  Convert list to string.

```

# Answer
> 1 votes
# Pyth, 45 bytes

```
AeSK.e,s/LzbkrBG1s[cGshMKd?H"upp""low""ercase

```

Try it online. Test suite.

### Explanation

```
             rBG1               pair of alphabet, uppercase alphabet
    .e                          map k, b over enumerate of that:
      ,                           pair of
           b                          lowercase or uppercase alphabet
        /Lz                           counts of these characters in input
       s                              sum of that
                                    and
            k                         0 for lowercase, 1 for uppercase
   K                            save result in K
 eS                             sort the pairs & take the larger one
A                               save the number of letters in and the 0 or 1 in H

s[                              print the following on one line:
  cG                              larger number of letters divided by
    shMK                            sum of first items of all items of K
                                    (= the total number of letters)
        d                         space
         ?H"upp""low"             "upp" if H is 1 (for uppercase), otherwise "low"
                     "ercase      "ercase"

```

# Answer
> 1 votes
# Ruby, 97 characters

```
->s{'%f %sercase'%[(l,u=[/[a-z]/,/[A-Z]/].map{|r|s.scan(r).size}).max.fdiv(l+u),l>u ?:low: :upp]}

```

Sample run:

```
2.1.5 :001 > ['PrOgRaMiNgPuZzLeS & CoDe GoLf', 'DowNGoAT RiGHtGoAt LeFTGoat UpGoAT', 'Foo BaR Baz'].map{|s|->s{'%f %sercase'%[(l,u=[/[a-z]/,/[A-Z]/].map{|r|s.scan(r).size}).max.fdiv(l+u),l>u ?:low: :upp]}[s]}
 => ["0.520000 uppercase", "0.580645 uppercase", "0.555556 lowercase"]

```

# Answer
> 1 votes
# Tcl, 166 bytes

```
proc C s {lmap c [split $s ""] {if [string is u $c] {incr u}
if [string is lo $c] {incr l}}
puts [expr $u>$l?"[expr $u./($u+$l)] upp":"[expr $l./($u+$l)] low"]ercase}

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 28 bytes

```
ʒ.u}gság/Dò©_αð„Œ„›…#'ƒß«®èJ

```

Try it online!

---

```
ʒ.u}g                        # filter all but uppercase letters, get length.
     ság/                    # Differential between uppercase and input length.
         Dò©                 # Round up store result in register w/o pop.
            _α               # Negated, absolute difference.
              ð              # Push space.
               „Œ„›…         # Push "upper lower"
                    #        # Split on space.
                     'ƒß«    # Concat "case" resulting in [uppercase,lowercase]
                         ®èJ # Bring it all together.

```

# Answer
> 1 votes
# Java 8, ~~136~~ 130 bytes

```
s->{float l=s.replaceAll("[^a-z]","").length();l/=l+s.replaceAll("[^A-Z]","").length();return(l<.5?1-l+" upp":l+" low")+"ercase";}

```

-6 bytes creating a port of *@ProgramFOX*' C# .NET answer.

Try it online.

**Explanation:**

```
s->{                  // Method with String as both parameter and return-type
  float l=s.replaceAll("[^a-z]","").length();
                      //  Amount of lowercase
  l/=l+s.replaceAll("[^A-Z]","").length();
                      //  Lowercase compared to total amount of letters
  return(l<.5?        //  If this is below 0.5:
          1-l+" upp"  //   Return `1-l`, and append " upp"
         :            //  Else:
          l+" low")   //   Return `l`, and append " low"
        +"ercase";}   //  And append "ercase"

```

# Answer
> 1 votes
## REXX, 144 bytes

```
a=arg(1)
l=n(upper(a))
u=n(lower(a))
c.0='upp';c.1='low'
d=u<l
say 1/((u+l)/max(u,l)) c.d'ercase'
n:return length(space(translate(a,,arg(1)),0))

```

# Answer
> 1 votes
# Pyth, ~~40~~ 39 bytes

```
Jml@dQrBG1+jdeS.T,cRsJJc2."kw""ercase

```

Try it here

### Explanation

```
Jml@dQrBG1+jdeS.T,cRsJJc2."kw""ercase
 m    rBG1                                For the lower and uppercase alphabet...
  l@dQ                                    ... count the occurrences in the input.
J                 cRsJJ                   Convert to frequencies.
               .T,     c2."kw"          Pair each with the appropriate case.
             eS                           Get the more frequent.
          +jd                    "ercase  Stick it all together.

```

# Answer
> 1 votes
# PowerShell Core, ~~134~~128 bytes

```
Filter F{$p=($_-creplace"[^A-Z]",'').Length/($_-replace"[^a-z]",'').Length;$l=1-$p;(.({"$p upp"},{"$l low"})[$p-lt$l])+"ercase"}

```

Try it online!

Thanks, Veskah, for saving six bytes by converting the function to a filter!

# Answer
> 1 votes
# Perl 5 `-p`, 72 bytes

```
$_=(($u=y/A-Z//)>($l=y/a-z//)?$u:$l)/($u+$l).$".($u>$l?upp:low).'ercase'

```

Try it online!

# Answer
> 1 votes
# Kotlin, 138 bytes

## Code

```
let{var u=0.0
var l=0.0
forEach{when{it.isUpperCase()->u++
it.isLowerCase()->l++}}
"${maxOf(u,l)/(u+l)} ${if(u>l)"upp" else "low"}ercase"}

```

## Usage

```
fun String.y():String =let{var u=0.0
var l=0.0
forEach{when{it.isUpperCase()->u++
it.isLowerCase()->l++}}
"${maxOf(u,l)/(u+l)} ${if(u>l)"upp" else "low"}ercase"}

fun main(args: Array<String>) {
    println("PrOgRaMiNgPuZzLeS & CoDe GoLf".y())
    println("DowNGoAT RiGHtGoAt LeFTGoat UpGoAT".y())
    println("Foo BaR Baz".y())
}

```

# Answer
> 1 votes
# C (gcc), ~~124 121 119~~ 118 bytes

```
u,l;f(char*x){for(u=l=0;*x;x++)isalpha(*x)?*x>96?l++:u++:0;printf("%f %sercase\n",fmax(l,u)/(u+l),u>l?"upp":"low");}

```

Try it online!

Slightly ungolfed

```
u,l;
f(char*x){
  for(u=l=0;*x;x++)
    isalpha(*x)?*x>96?l++:u++:0;
  printf("%f %sercase\n",fmax(l,u)/(u+l),u>l?"upp":"low");
}

```

# Answer
> 1 votes
# C, 120 bytes

```
f(char*a){int m=0,k=0,c;for(;isalpha(c=*a++)?c&32?++k:++m:c;);printf("%f %sercase",(m>k?m:k)/(m+k+.0),m>k?"upp":"low");}

```

test and result:

```
main()
{char *p="PrOgRaMiNgPuZzLeS & CoDe GoLf", *q="DowNGoAT RiGHtGoAt LeFTGoat UpGoAT", *m="Foo BaR Baz";
 f(p);printf("\n");f(q);printf("\n");f(m);printf("\n");
}

```

results

```
0.520000 uppercase
0.580645 uppercase
0.555556 lowercase

```

It suppose Ascii character set.

# Answer
> 1 votes
# APL(NARS), 58 char, 116 bytes

```
{m←+/⍵∊⎕A⋄n←+/⍵∊⎕a⋄∊((n⌈m)÷m+n),{m>n:'upp'⋄'low'}'ercase'}

```

test:

```
  h←{m←+/⍵∊⎕A⋄n←+/⍵∊⎕a⋄∊((n⌈m)÷m+n),{m>n:'upp'⋄'low'}'ercase'}
  h "PrOgRaMiNgPuZzLeS & CoDe GoLf"
0.52 uppercase
  h "DowNGoAT RiGHtGoAt LeFTGoat UpGoAT"
0.5806451613 uppercase
  h "Foo BaR Baz"
0.5555555556 lowercase

```

# Answer
> 1 votes
Javascript 80 characters

I'm bad at this but here was my go at Javascript:

```
a=(s)=>{let a=0,b=0;for(c in s)s[c]==s[c].toUpperCase()?a++:b++;return a/(a+b);}

```

Readable version:

```
a=(s)=>{
    let a=0,b=0;
    for(c in s)
        s[c]==s[c].toUpperCase()?a++:b++;
    return a/(a+b);
}

```

Function is called with: `a('hEllO')` which outputs `0.4` for example.

I feel like there must be a way to condense the arrow function or something with the words return or toUpperCase that I can do.

# Answer
> 1 votes
# WDC 65816 machine code, 159 bytes

Hexdump:

```
00000000: a200 009b 8006 e600 9002 e601 b200 f016  ................
00000010: c941 90f2 c95b b003 e880 ebc9 6190 e7c9  .A...[......a...
00000020: 7bb0 e3c8 80e0 c220 8602 9865 0285 04c4  {...... ...e....
00000030: 0290 0ea9 6c6f 850f a977 6585 1184 0280  ....lo...we.....
00000040: 0aa9 7570 850f a970 6585 11a9 6400 8508  ..up...pe...d...
00000050: 6406 a900 0018 6502 c504 9006 e504 e606  d.....e.........
00000060: 80f6 c608 d0ef 0ac5 0490 02e6 06a9 302e  ..............0.
00000070: 850a a900 2085 0da9 7263 8513 a961 7385  .... ...rc...as.
00000080: 15a9 6500 8517 a230 00a5 06c9 0a00 9006  ..e....0........
00000090: e90a 00e8 80f5 e230 6930 850d 860c 60    .......0i0....`

```

Assembly:

```
; pointer to null-terminated string is in $00-$01
; enter in 8-bit accumulator mode (SEP #$20), 16-bit index mode (REP #$10)
; output is a null-terminated string starting at $0A, ends at $18
count:
    ; X - number of uppercase chars
    ; Y - number of lowercase chars
    LDX #$0000
    TXY
    BRA .firstiter
.loop:
    INC $00
    BCC .firstiter
    INC $01
.firstiter:
    LDA ($00)
    BEQ calc_maj
    CMP #$41 ; 'A'
    BCC .loop
    CMP #$5B ; 'Z'+1
    BCS +
    INX
    BRA .loop
+   CMP #$61 ; 'a'
    BCC .loop
    CMP #$7B ; 'z'+1
    BCS .loop
    INY
    BRA .loop
calc_maj:
    ; okay, now the hard part
    ; $02 is amount of lowercase
    ; $04 is total
    REP #$20
    STX $02
    TYA
    ADC $02
    STA $04
    CPY $02
    BCC +
    ; Y > X thus more lowercase
    LDA #$6F6C ; 'lo'
    STA $0A+5
    LDA #$6577 ; 'we'
    STA $0A+7
    STY $02
    BRA ++
+   ; Y < X => more uppercase
    LDA #$7075 ; 'up'
    STA $0A+5
    LDA #$6570 ; 'pe'
    STA $0A+7
++  ; now $02 is the amount of larger and the buffer's upper/lower word is already initialized
    LDA.w #100
    STA $08
    STZ $06
    LDA #$0000
.divmul_outer:
    CLC : ADC $02
.divmul_inner:
    CMP $04
    BCC +
    SBC $04
    INC $06
    BRA .divmul_inner
+   DEC $08
    BNE .divmul_outer
    ; if tmp * 2 >= $04: inc $06
    ASL
    CMP $04
    BCC +
    INC $06
+   ; $6 now contains $02 * #100 / $04
    ; let's write all the other letters while we're still in 16bit mode
    ; 0.XX XXXXrcase\0
    LDA #$2E30 ; "0."
    STA $0A
    LDA #$2000 ; "\0 "
    STA $0A+3
    LDA #$6372 ; "rc"
    STA $0A+9
    LDA #$7361 ; "as"
    STA $0A+11
    LDA #$0065 ; "e\0"
    STA $0A+13
    LDX #$0030
    LDA $06
-   CMP #$000A
    BCC +
    SBC #$000A
    INX
    BRA -
+   SEP #$30
    ADC #$30
    STA $0A+3
    STX $0A+2
    RTS

```

(assembled with Asar. The +/- things are labels.)

Input: A 16-bit pointer to the string to count, null terminated. Output: A null-terminated string starting at $0A (and ending at $18). Enter in 8-bit accumulator, 16-bit index mode. (SEP #$20 REP #$10)

God I hate this CPU. Will optimize tomorrow maybe.

# Answer
> 0 votes
# Gema, 125 characters

```
\A=@set{l;0}@set{u;0}
<J1>=@incr{l}
<K1>=@incr{u}
?=
\Z=0.@div{@cmpn{$l;$u;$u;;$l}00;@add{$l;$u}} @cmpn{$l;$u;upp;;low}ercase

```

Sample run:

```
bash-4.3$ for input in 'PrOgRaMiNgPuZzLeS & CoDe GoLf' 'DowNGoAT RiGHtGoAt LeFTGoat UpGoAT' 'Foo BaR Baz'; do
>     gema '\A=@set{l;0}@set{u;0};<J1>=@incr{l};<K1>=@incr{u};?=;\Z=0.@div{@cmpn{$l;$u;$u;;$l}00;@add{$l;$u}} @cmpn{$l;$u;upp;;low}ercase' <<< "$input"
>     echo " <- $input"
> done
0.52 uppercase <- PrOgRaMiNgPuZzLeS & CoDe GoLf
0.58 uppercase <- DowNGoAT RiGHtGoAt LeFTGoat UpGoAT
0.55 lowercase <- Foo BaR Baz

```

# Answer
> 0 votes
# Matlab, 110 bytes

Solution

```
i=input('','s');a=sum(i>64&i<91);b=sum(i>96&i<123);d=a>b;disp([num2str(max(a,b)/(a+b)),' upp'*d+' low'*~d,'ercase'])

```

Test:

```
i='PrOgRaMiNgPuZzLeS & CoDe GoLf';
0.52 uppercase
i='DowNGoAT RiGHtGoAt LeFTGoat UpGoAT';
0.58065 uppercase
i='Foo BaR Baz'
0.55556 lowercase

```

# Answer
> 0 votes
### Pure Bash, ~~183 185 182~~ 179 bytes

~~+2~~ +4 bytes for more golfing.

(Second linebreak is there only to avoid scrollbar, so not counted).

```
o=({upp,low}ercase) q=;eval s+={A..Z};b="${1//[$s]}";eval s+={a..z}
c="${1//[$s]}";b=$[(${#1}-${#b})*64#fE/(${#1}-${#c})];((b<40#ck))&&
q=1 b=$[41#og-b];printf "%.2f ${o[q]}\n" .$b

```

Sample:

```
(set -- "Foo BaR Baz";o=({upp,low}ercase) q=;eval s+={A..Z};b="${1//[$s]}"
eval s+={a..z};c="${1//[$s]}";b=$[(${#1}-${#b})*64#fE/(${#1}-${#c})];((b<
40#ck))&&q=1 b=$[41#og-b];printf "%.2f ${o[q]}\n" .$b)
0.56 lowercase

```

or

```
ulRatio() { local b c s o=({upp,low}ercase) q=;eval s+={A..Z};b="${1//[$s]}"
eval s+={a..z};c="${1//[$s]}";b=$[(${#1}-${#b})*64#fE/(${#1}-${#c})];((b<40\
#ck))&&q=1 b=$[41#og-b];printf "%.2f ${o[q]}\n" .$b;}

for string in "PrOgRaMiNgPuZzLeS & CoDe GoLf" \
        "DowNGoAT RiGHtGoAt LeFTGoat UpGoAT" "Foo BaR Baz" ;do
    echo -e "\\n$string"
    ulRatio "$string"
  done

PrOgRaMiNgPuZzLeS & CoDe GoLf
0.52 uppercase

DowNGoAT RiGHtGoAt LeFTGoat UpGoAT
0.58 uppercase

Foo BaR Baz
0.56 lowercase

```

# Answer
> 0 votes
# Candy, ~~62~~ 84 bytes

The legit answer is:

```
b0a(~x#97<{0|1}~y#32*XW-#65-=xX0#27w{ibY+})bZ/="ercase"A12/<{1A-p"upp"|Ap"low"}(;)N;

```

But adding a range operator and literal characters to Candy, it gets shorter:

```
(~`a`zw{i}A`A`Zw{v})"ercase"YZY+/~12/>{Ap"upp"|1A-p"low"}(;)N;

```

Long form as:

```
while
  peekA
  "a" "z" between
  if
    incrZ
  endif
  pushA
  "A" "Z" between
  if
    incrY
  endif
endwhile
"ercase"
pushY
pushZ pushY add
div
peekA
digit1 digit2 div
greater
if
  pushA print
  "upp"
else
  digit1 pushA sub print
  "low"
endif
while
  printChr
endwhile
digit10 printChr  # linefeed

```

# Answer
> 0 votes
## Clojure, 149 bytes

```
#(let[C(for[c(re-seq #"[a-zA-Z]"%)](pos?(compare"["c)))[k v](last(sort-by val(frequencies C)))](str(float(/ v(count C)))" "(if k"upp""low")"ercase"))

```

---
Tags: code-golf, string
---


# Question
Title: Print your char count in words, in many languages
This challenge is inspired by my earlier challenge "Create a program that prints the amount of characters it has, in words".

This challenge's rules are simple: make a program that prints its character count, in words, which works in as many languages as possible.

Each programming language the program works in must make the program print its char count in a different natural language.

E.g. you can make a polyglot which prints "fifty" (suppose this is its char count) in one language and "pedeset" (Serbocroatian for 50) in another, but not a polyglot printing "fifty" in both languages.

An extension to the "don't invent languages to solve the task" rule also applies here: don't make a constructed language just to validate your otherwise nonsense output in some language.

If the polyglot printing "fifty" in one language was tested in another and printed (prant?) "Aijsisdjdsl", it's illegal to make a conlang using "Aijsisdjdsl" as the word for "fifty".

Capitalization is ignored: in case you're printing "one" (somehow) you can print "one", "oNe", "ONE" or anything else.

Base ten is required.

Proper spacing is also required.

In the (unlikely but just for specification) case your program reaches one billion characters or more, use the American number scale. A billion here is 10^9 and a million is 10^6.

Do not use "one hundred and one": use "one hundred one".

Do not use the hyphen. Print forty four, not forty-four.

If the language you use has another script, use it instead of the romanization of it. If your program prints Arabic in some language, it should print (yet again, example with 50) "خمسون" and not "khamsun".

Use the grammatically correct translation.

For our purposes, we use Ethnologue to determine what is and isn't a language in this challenge. It's the most widely used so we'll just go with that.

For simplicity, any languages with identical numerals will be considered the same for this challenge. Using any Japanese/Chinese numeral gives you a score of 1.

If a word is spelled the same in multiple languages, e.g. English and French's "six", it counts as one point toward your score.

Dialects Ethnologue differentiates will be considered different languages as long as they don't fall in the two rules above.

Different compilers of the same programming languages are not differentiated here.

Your score is the amount of languages your program works in, per standard rosetta-stone rules.

If the two (or more) best answers are tying, the one with the lowest byte count wins.

The encoding used to determine byte count for tiebreakers is UTF-8.

The highest score wins (in case of tie see above). Have fun.

# Answer
> 33 votes
# ~~9~~ ~~10~~ ~~12~~ ~~13~~ ~~16~~ ~~18~~ ~~21~~ 23 languages, 1000 bytes

* Bash (prints "duizend", Dutch)
* Zsh (prints "een Dausend", Luxembourgish)
* Dash (and other true POSIX shells) (prints "nje mije", Albanian)
* C (prints "et tusind", Danish)
* C++ (prints "ib txhiab", Hmong)
* brainfuck (prints "mille", Italian)
* boolfuck (prints "afe", Samoan)
* Brainlove (prints "mil", Spanish)
* 2DFuck (prints "sewu", Javanese)
* Python 1 (prints "one thousand", English)
* Python 2 (prints "eintausend", German)
* Python 3 (prints "hal kun", Somali)
* Asar (prints "tuhat", Estonian)
* \>\<\> (prints "jedna hiljada", Bosnian)
* Gol\>\<\> (prints "eenduisend", Afrikaans)
* Befunge-98 (prints "o mie", Romanian)
* Befunge-96 (prints "otu puku", Igbo)
* Labyrinth (prints "elf", Maltese)
* Hexagony (prints "ett tusen", Swedish)
* GNU Make (prints "isang libo", Filipino)
* A Pear Tree (prints "hezar", Kurdish)
* Octave (prints "tūkstantis", Lithuanian)
* Whispers (prints "seribu", Malay)

```
#ifdef    warnings //[[^
#_ if 0
#{
#(________ )
'''''echo' -n<<"'''+r'''":
    @echo   "isang libo"
define N #
1_801_201_
0
1...@
endif
print "tuhat"
macro _()
#}
disp("t\xc5\xabkstantis")
quit
#{
> "seribu"
>> Output 1
'''+r''':
[ -n "$ZSH_VERSION" ]&&echo een Dausend||([ -n "$BASH_VERSION" ]&&echo duizend||echo nje mije)
:<<"endmacro;\"^*///]\"\"\"#/t#"
#endif
#include<stdio.h>
int main(){puts(sizeof('1')-1?"et tusind":"ib txhiab");}
/*
print"hezar";exit;<<'/*';#NJ@G@GMCI
1234567890123456789012345678901234567890123|u;ts;6ie$;;tn;e@$<
]+[+++[[<+>->+++++>+<<]+>]<<<.<.+++.(.<.)>>+;+;;;;+;;+;;+;;+;;+;;+;+;+;+;+;;+;;+;[-]]![!.!...!..!..!.!..!..!.!.!.!.!...!.!...!.!...!.!.!.!.!][
'''
print(["hal kun","eintausend","one thousand"][(type(1==1)==type(1))+(3/2==1)])
r""""
01234567891234567890123456789012                               1
                       >"ukup uto">:#,_@
                H"eenduisend"\
        >o<"jedna hiljada"~\ u
#}
endef #   >"eim o"4k,@ /"`"/"/"\
endmacro;"^*///]"""#/t#

```

There should be a hard tab at the start of line 6.

Try it online! (use the switch languages button to try them all)

Length is exactly 1000 ASCII characters, and also 1000 bytes.

Asar is a SNES assembler that has quite sloppy input parsing and thus accepts a lot of inputs that one may consider invalid. I used version 1.71 for this, downloadable here, and depended on quite a few bugs, so there is a chance this will break in later versions.

All of the other languages are well-known enough to be on TIO.

I used Google Translate for the translations, so they may not be perfectly grammatically accurate. If anyone knows some of the languages better, please suggest improvements, I've got some wiggle room here :)

Credits: @JoKing for some minor optimizations regarding brainfuck, befunge, (gol)\>\<\>, hexagony, and python. @flawr for suggesting and helping with octave. @caird coinheringaahing for suggesting whispers.

Fun fact: I made most of this polyglot months ago. It included the first 10 languages mentioned here. (edit: I've since shuffled the language list around a bit so it makes more sense, but check the 2nd oldest version of this polyglot in the edit history and add hexagony to get that list).

# Explanation (slightly outdated)

This explanation was made for an older revision. It's hard enough keeping track of all the natural language shuffling (to make more difficult programming languages use shorter natural language words) and Hexagony's constant grid shifting, let alone update the explanation every single revision. I'm leaving this here since it still gives a good overview of how what path most of these languages take.

## Asar

Asar is a SNES assembler written by Alcaro in 2011, intended to be backwards-compatible with xkas (written by byuu in around 2006). It doesn't have the nicest code. The first line begins with a special kind of label definition, the label is called `ifdef`. Then follows a `warnings` command, which is supposed to control when warnings are thrown. Usually it's followed by either `push` or `pull`, but it doesn't reject other words following it. So that's the first line: a label-definition followed by a no-op. The 2nd line is a similar label definition (this time the label is called simply `_`) followed by an `if` statement. The condition is 0, so the contents of the if are ignored. This means we can pretty much go wild inside it, the only rule we have to follow is that all double-quotes must be paired. The end of that if statement is at the `endif` on line 10. After that comes a simple print statement which prints the output. Then comes a macro declaration. Declaring a macro that isn't used is pretty much equivalent to an `if 0`. The end of the macro declaration is on the very last line. In Asar, comments are started with `;`, so the rest of the last line is ignored.

## Bash, Zsh, Dash

The first 3 lines are just regular comments. The 4th line is equivalent to `echo -n <<"'''+r''':"`. This is an echo without a linebreak following it. Then we have a heredoc that ends at any occurrence of `'''+r''':`. The contents of the heredoc are piped to the stdin of that echo command, but that doesn't matter since echo ignores its stdin. After the end of the heredoc on line 14, we have regular shell code that checks whether the variables for either zsh or bash are defined and chooses what to print based on that. After that, we have the null command `:`, which does nothing, into which we pipe the rest of the script using another heredoc. The heredoc ends with `endmacro;"^*///]"""#/t#`, which just happens to be the very last line of the script.

## C, C++

The first line is a preprocessor directive which checks whether the define "warnings" is defined. There's also a comment after the directive. `warnings` isn't defined, so the contents of the block are skipped. There are a bunch more garbage preprocessor directives inside the skipped if branch, but they are ignored too. The `#endif` is on line 18. After that we have a standard C program. It checks whether the size of a character literal is greater than 1 or not. If it's greater, we are in C, because in C character literals are actually of `int` type, which has a size of at least 2 bytes on literally every platform in use today. In C++, however, the type of a character literal is `char`, which is defined to have a size of 1, so a different branch is taken. The rest of the code is a single comment, started with /\* at line 21. It's terminated in the middle of the last line, but followed immediately by a single line comment.

## Brainfuck

On the first line, we have 2 open brackets. This is because one of them is eaten by the heredoc that ends the shell part, which is before the brainfuck part. There are some balanced brackets within the skipped part too, but they don't matter because they are balanced. The next closing bracket is on line 21, which is also the start of the brainfuck code. I used this text-to-brainfuck converter, because somehow it generated even better output than BF-Crunch. Then follows the boolfuck code, which is mostly ignored due to `;` not being defined. The increments don't matter either, we just switch to the next cell which has never been written to so the next open bracket is a guaranteed jump. The next closing bracket after that is on the very last line, and there are no brainfuck instructions after it.

## Boolfuck

The boolfuck control flow is quite similar. However, once the brainfuck code is reached, most of it is ignored as `-` isn't defined in boolfuck. The area with `+` and `;` is where the output is actually printed. It just prints the string "mil" bit by bit, with `+` negating the current bit and `;` outputting it. The rest of the control flow is identical to brainfuck.

## Python 1, 2, 3

The first 3 lines are regular comments. The 4th line starts with a triple-quoted string literal, delimited by single quotes. This string literal is often closed and reopened because I needed to get a backslash in somewhere (I've forgotten where), so I needed the string literal to be raw, but I couldn't put the r before the first quotes. Anyways, the first place where the string literal is closed and not immediately followed by another string literal is on line 23, which is the start of the Python code. This code uses a few simple tests to determine which version of Python it's running on: in Python 1.6, there was no separate boolean type, so the results of comparisons were just `int`s. The first condition checks that. The second condition checks whether division rounds down or not. In Python 2, division on integers rounded the result down, whereas in Python 3, it results in a floating point answer. After the Python code, we have another raw string literal that lasts until the last line, where it is immediately followed by a comment.

## \>\<\>, Gol\>\<\>

Now we get to the 2D languages. Gol\>\<\> is almost perfectly backwards compatible with fish, so they start execution the same way. In fish, execution starts from the north east ("top left") corner of the program, with the instruction pointer pointing west. In fish, `#` is a mirror which reflects the instruction pointer back in the direction it came from. The `#` causes the IP to point west instead. In fish, program space is topologically a torus, so going off the western edge results in reappearing at the eastern edge of the program. There it encounters `^`, which changes the instruction pointer's direction to north. Execution then continues from the very bottom of the script. The IP goes right past the very last character of the program and hits the `/` on line 31. The `/` reflects the IP like a mirror, so it'll go east again. Here is where we determine if we are running fish or golfish. In golfish, quotes inside string literals can be escaped with ```. So in golfish, the string literal is only terminated on the 3rd quote on that line. In regular fish, however, the backtick escape doesn't exist, so the string literal ends after the 2nd quote. (The 4th quote is needed to keep Asar happy about paired quotes). Then, both IPs are reflected upwards. The fish one goes west on line 30 and follows a pretty simple text printing program. The golfish one goes west on line 29, after switching to a different stack with the `u` in its path on line 30. There, it follows a very simple string printing code too (just push the string on the stack and call `H`, which exits and dumps the whole stack as ASCII text).

## Befunge-98

In Befunge-98, execution starts out in the north west ("top left") corner of program space, pointing east. `#` is a trampoline command, it skips the next instruction. The letters a-f just push their hex value on the stack. Spaces are no-ops. `w` pops 2 items from the stack, compares them, and turns left or right depending on which one is larger. here, `f` is larger than `e` (15 is larger than 14), so we turn left, with the IP pointing north. Now we jump to the bottom of the program, like in fish, and follow the path of arrows to line 31. This uses a simple string printing code with the `k` operator, which repeats the next instruction (print character) some number of times, 5 in this case.

## Hexagony

This was the one language that probably costed me the most time while writing this thing. This explanation is a bit oversimplified, go look at Hexagony's README or wiki page if you want to learn more. Hexagony reformats your program into a hexagon. Then execution starts at the north-west corner. The first command, `#`, switches to the IP with the index of the current memory cell (there are 6 IPs, each one starting at a different corner of the hexagon). Memory is initialized to all 0's though, so this switches to the first IP, which is the one that is already executing. All alphabetic characters simply set the current memory cell to their value, so most of the rest of the 1st line is just no-ops. Then there's a mirror, `/`, which makes the IP point north-west (as if it got reflected off the mirror). This means the IP will wrap around to the very bottom of the hexagon. There, it happens to hit the `/` at the very end of the script. This is also a mirror and makes the IP go east again. Then we set the current memory cell to `t` and use the "switch IP" command again. Since there are only 6 IPs, the current memory cell is taken modulo 6 when switching, so it goes to the 3rd IP, which starts at the eastern corner of the hexagon. This IP starts out moving southwest and it executes some useless operations before reaching the end of line 23 in the original code. There it uses the `$` operator to skip over some characters the first time around, then encounters `|` which turns it around and prints some more characters.

## Labyrinth

In labyrinth, control flow is determined by the program's layout. All spaces and alphabetic characters are considered walls. The `#` command pushes the number of items on the stack, which is 0, to the stack. Then execution continues in the only possible direction, south. Here, the number of items on the stack is pushed again, this time pushing a 1. Now there's 2 directions to go: south again or east. Since the topmost value on the stack is positive, execution would try to go west, but that path is blocked, so it goes east instead. `_` pushes a 0. Now there's again 2 directions to go, but we came from one direction and unless nothing else is possible, the IP will never flip around and go back the direction it came from, so we continue south. Here we have a `(`, which decrements the top of the stack. This means the topmost item is now `-1`. Excluding the direction we came from, there's 3 directions to go, but since the top of the stack is negative, we go east. Here we push 0 a bunch of times, which means we continue east for as long as possible. In the end, we go south because that's the only other place to go. There we find a `'`, which is a no-op if debugging output isn't enabled. Now, labyrinth treats tabs as a single space, so the character south of the `'` is actually `"` from the start of the echo's parameters. Execution continues there. Below that, there is only one path to follow, which leads to the 4th character of line 9. There, we simply construct the ascii values corresponding to "elf" and print them.

## Make

The first 3 lines are comments. The 4th line is somehow a valid target name. (To be honest, I have no idea either about why this works.) Since this is the first target in the makefile, it's what gets executed when no argument is given to make. The rule just prints the character count. Then we define a variable called N which contains the rest of the script. It ends on the 2nd-to-last line with the `endef` command. Following it is a comment that ends with a backslash. This causes make to interpret the next line as part of the comment too.

## A Pear Tree

A Pear Tree starts execution by finding the longest substring of the program whose CRC32 is 0. Then it shifts the whole program so that said substring is at the start of the program. This long substring with a CRC32 of 0 is `print"hezar";exit;<<'/*';#NJ@G@GMCI`, which *just happens to be* valid Perl code. No, actually I used a tool called crchack to generate some letters to add to a comment so that the string's CRC is 0. So this Perl program is shifted to the very beginning of the program. It contains a print statement, an exit statement and a heredoc. The heredoc is terminated by the line that was right before the perl script originally, and thus is at the very end of the program now. So the heredoc skips the entire rest of the script and all of the syntax errors that would arise from not doing so.

# Answer
> 13 votes
# 6 languages, prints 80

```
//'Ÿ¯"y"«q
   áttatíu/*
";"
åo 八
t?  十
t@   "
io    o
oo     @
"o
0o
1 K`ochenta

```

(There's also 5/90 solution with a different approach in the edit history if you're interested)

## 05AB1E/English \- `eighty`

```
//'Ÿ¯"y"«q
//          # no-ops
  'Ÿ¯       # push dictionary string "eight"
     "y"    # push literal string "y"
        «   # concatenate
         q  # end program

```

Try It Online!

Once execution ends, the stack top (`eighty`) is implicitly printed, and nothing later on in the file will be considered at all.

## ink/Íslenska \- `áttatíu`

```
   áttatíu/*

```

Try It Online!

The very first line in the file is a comment, due to the `//`. The `/*` at the end of this line begins a multi-line comment (which we never have to close), so ink doesn't care about anything later on in the file either.

That just leaves the text `áttatíu`, which ink happily prints, because that is what ink does.

## Alice/日本語 \- `八十`

```
/

  "
   八
    十
     "
      o
       @

```

Try It Online!

In Alice, `/` is a mirror, but unlike in other 2D languages you might be familiar with, they reflect you 135 degrees rather than 90. So after encountering the `/`, we move diagonally, encountering `"八十"` (which pushes the string `八十` onto the stack), `o` (which outputs it), and `@` (which terminates the program).

## \>\<\>/Norsk \- `åtti`

```
//

";
åo
t?
t@
io
oo
"o
0o
1

```

Try It Online!

The `/` at the start deflects the instruction pointer upwards, after which it wraps around to the bottom, travelling up the first column.

It then pushes the numbers `1` and `0` and the characters `oittin` onto the stack, bounces around on the mirrors at the top, and travels up along the second column.

In the second column, we print the first four items on the stack (`åtti`). Then we shuffle the last three values around a bit using `@`, leaving the `0` at the top, which thanks to the `?` makes us skip the final print instruction, before we arrive at the `;` which ends the program.

## Gol\>\<\>/Svenska \- `åttio`

```
//

";
åo
t?
t@
io
oo
"o
0o
1

```

Try It Online!

Works just like \>\<\> except the `@` shuffles the stack values in a different way, so we end up not skipping the last print, thus printing `åttio` instead of `åtti`.

## Retina/Español \- `ochenta`

```
1 K`ochenta

```

Try It Online!

The first ten lines are presumably interpreted as replacement stages, but since we don't have any input to manage, we don't really care what they do. the last stage, however, is a constant stage - we can tell because the config string before the backtick has a `K` in it. That means we just discard any input that stage would get from the stages before it, and output `ochenta`.

# Answer
> 10 votes
# 3 Languages, 800 chars

* PHP, Norwegian, Outputs `ÅTTE HUNDRE`
* Emoji, Persian, Outputs `هشتصد`
* COW, English, Outputs `EIGHT HUNDRED`

```
<?=['ÅTTE HUNDRE','⛽هشتصد➡','
MoO
MoO MoO
MoO MoO MoO
MoO MoO MoO MoO
MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MMM MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO Moo MoO MoO MoO MoO Moo MOo MOo
Moo MoO Moo MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO Moo MMM Moo MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
Moo MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MOo MOo
MOo MOo MOo MOo MOo Moo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo Moo MMM
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MMM MoO Moo MOo Moo'][0];

```

PHP - Try it online!

COW - Try it online!

Emoji - Try it online!

# Answer
> 9 votes
# ~~3~~ ~~8~~ 9 languages, 300 characters

```
                            //®di.•paü¾p•ë"兩百"„„í°¡r\}qtrescientos➡\u000A\u002F\u002A
    //\
{{Write("trois cent"/*\u002A\u002Finterface M{static void main(String[]a){System.out.print("driehonderd"                                             /*
    #include<stdio.h>
 int main(){{puts(sizeof'a'<sizeof(int)?"trezentos":"dreihundert"/**/);}}//

```

Try it online in 05AB1E / Chinese \- outputs `兩百`.
Try it online in 05AB1E (legacy) / Italian \- outputs `trecento`.
Try it online in 2sable / English \- outputs `three hundred`.
Try it online in Java 8 / Dutch \- outputs `driehonderd`.
Try it online in C# (Visual Interactive Compiler) / French \- outputs `trois cent`.
Try it online in C / German \- outputs `dreihundert`.
Try it online in C++ / Portuguese \- outputs `trezentos`.
Try it online in Whitespace / Japanese \- outputs `三百`.
Try it online in Emoji / Spanish \- outputs `trescientos`.

## Explanation:

**05AB1E / Chinese and 05AB1E (legacy) / Italian and 2sable / English:**

```
                    # Spaces/tabs are no-ops
  //                # Divide twice (without input)
                    # Legacy 05AB1E / new 05AB1E: this pushes an empty string
                    # 2sable: the stack remains empty
    ®               # Push -1
     d              # Legacy 05AB1E: check if this -1 is an integer (truthy)
                    # New 05AB1E: check if this -1 is non-negative (≥0) (falsey)
                    # 2sable: check if this consists only of digits (falsey)
      i             # If it is truthy:
       .•paü¾p•     #  Push compressed string "trecento"
      ë             # Else:
       "兩百"       #  Push string "兩百"
       „„í°¡        #  Push dictionary string "one hundred"
             r      #  Reverse the stack
                    #   New 05AB1E: "","兩百","one hundred" → "one hundred","兩百",""
                    #   2sable: "兩百","one hundred" → "one hundred","兩百"
              \     #  Discard the top item
                    #   New 05AB1E: "one hundred","兩百","" → "one hundred","兩百"
                    #   2sable: "one hundred","兩百" → "one hundred"
      }             # Close the if-else
       q            # Terminate the program
                    # (after which the top of the stack is output implicitly as result)
                    # And any character after it are no-ops

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*) to understand why `„„í°¡` is `"one hundred"` and `.•paü¾p•` is `"trecento"`.

**Emoji / Spanish:**

```
                    # Some no-ops
trescientos    # Push string "trescientos"
                ➡  # Print the top to STDOUT
                    # Some more no-ops

```

**Whitespace / Japanese:**

Only spaces, tabs, and newlines are relevant for Whitespace programs and every other character is ignored. So the program is actually (`S` = space; `T` = tab; `N` = newline):

```
SSSTSSTTTSSSSSTSSTN
TN
SSSSSTTTSTTSSTTTTTTSN
TN
SS

```
1. `SSSTSSTTTSSSSSTSSTN` push the integer 19977 to the stack (first `S` is to enable stack manipulation; second `S` is to push a number; third `S` is positive (`T` would have been negative); the `S` and `T` that follow are the integer in binary where `S=0` and `T=1`; and the trailing `N` finishes this command.
2. `TNSS` print this integer as character (with this unicode value) to STDOUT (first `TN` enables I/O; the following `S` is to output to STDOUT; and the second `S` to output as character (`T` would have been as integer)).
3. `SSSSSTTTSTTSSTTTTTTSN` push 30334
4. `TNSS` print as character again

**C# (Visual Interactive Compiler) / French:**

The first line contains some no-op spaces/tab, and a comment (`//` starts the comment, making everything after it on that same line no-ops).
The second line is similar, again a no-op tab and a comment.
The third line starts with `{{Write("trois cent"`, and `/*` starts a (potentially multi-line) comment-block. This stops at the `*/` on the last line, making everything in between no-ops. After which `);}}` is part of the C# program again (and the very last `//` is a comment again, only there to make the program-size 300).

So the non-comment parts of the C# (Visual Interactive Compiler) program are:

```
{{Write("trois cent");}}

```

The `{{` and `}}` are code-blocks, and basically no-ops in this case.
The `Write("trois cent");` prints this text to STDOUT.

**C / German and C++ / Portuguese:**

First line is a comment again.
The `//\` on the second line is relevant in C and C++, as it will comment out the entire next line. The `#include<stdio.h>` and `int` in front of the `main`-function are mandatory in C++ (and optional in C; it would run fine without these two parts, but would generate some warnings).
The `/**/` and `//` are again comments.

So the non-comment parts of the C and C++ programs are:

```
#include<stdio.h>         // Required include for `puts` in C++
int main(){               // Mandatory main-function:
  {                       //  No-op code-block (similar as the C# part above)
    puts(                 //   Print to STDOUT with trailinb newline:
      sizeof'a'           //    If the byte-size of character 'a'
      <                   //    is smaller than
      sizeof(int)?        //    the byte-size of an integer:
       "trezentos"        //     Print "trezentos"
      :                   //    Else:
       "dreihundert");}}  //     Print "dreihundert"

```

In C (and Java), values of type `char` are saved as an integer. `sizeof(int)` and `sizeof'a'` will therefore both result in `4` in C, and `4<4` is falsey, so `"dreihundert"` is printed. In C++ (and C#), values of type `char` are actually a separated type saved as characters. `sizeof'a'` will therefore result in `1` in C++, and `1<4` is truthy, so `"trezentos"` is printed.

**Java 8 / Dutch:**

In Java, we can use `\uHEX` as unicode values, which are read as characters after compilation. The very first line therefore compiles to (I'll ignore the leading spaces/tabs for now to make it a bit more compact):

```
//®di.•paü¾p•ë"兩百"„„í°¡r\}qtrescientos➡
/*

```

The `\u000A\u002F\u002A` are a newline, `/` and `*` respectively. Just like in the C# program, this will stop at the first `*/`, which is the `\u002A\u002` on the third line in this case. There the Java program starts:

```
interface M{static void main(String[]a){System.out.print("driehonderd"

```

After that come a bunch of no-op spaces/tabs again, followed by another `/*` which stops at the same place as the C# program. So the full Java program is:

```
interface M{static void main(String[]a){System.out.print("driehonderd");}}

interface M{                    // Class:
  static void main(String[]a){  //  Mandatory main method
    System.out.print(           //   Print to STDOUT
      "driehonderd");}}         //    The string "driehonderd"

```

# Why these languages?

**Natural languages:**

* I'm fluent in English and Dutch
* I've learned French and German at high school
* I watch quite a lot of Japanese anime
* I know a few loose words in Spanish, Italian, and Portuguese
* Chinese was short enough to fit after adding 2sable ;)

**Programming languages:**

* I'm pretty skilled at Java, 05AB1E, C#, and Whitespace
* I've used the polyglot tricks for combining Java & C as well as Java & C# before here and here
* I've seen the C / C++ difference before, and it was therefore easy to add here
* Emoji is a perfect language to add, since it ignores everything except for the relevant emoji commands (unlike Emojicode I tried to add as well..)
* 2sable is based on an old version of 05AB1E (legacy), and therefore rather similar as 05AB1E and 05AB1E (legacy), except it's a bit older than both.

*I might try to learn and add Aheui for a suiting Korean output later on, since it will ignore everything except for the Korean characters in the code.*

# Answer
> 3 votes
# ~~3~~ 4 languages, outputs 20

This answer is inspired by this answer. Let's see whether I can fit in the ~~4th~~ 5th language in 20 characters.

```
(廿)"二十""hai"tyve➡S

```

Try it online in Actually!

Try it online in 05AB1E!

Try it online in Emoji!

Try it online in Underload!

## Explanation

Actually:

```
(                           Roll empty stack left
 廿                         Unidentified instruction
   )                        Roll empty stack right
    "二十""hai"             Push 2 strings
               t         Pop a, b, push a[b:]. Nothing special since b is a string.
                   y        Push prime factors of the string on the top of the stack
                    v      Discard TOS for the seed of the RNG
                     e     Push exp(Top Stack String)
                      ➡S Sort the Top Of Stack; no effect to the text

Outputs the whole stack implicitly.

```

05AB1E:

```
(                           Negate the empty stack
 廿                         Unidentified instruction
   )                        AFAICT this is a NOP
    "二十""hai"             Push 2 strings onto the stack
              t           Square root top of the stack string
                  y         Push string variable
                   v        Enumerated loop
                    e       Number of permutations
                     ➡S Cast to list of characters / digits.

This outputs the TOS implicitly.

```

Emoji:

```
(廿)"二十""hai"             No operations
              tyve➡  Output tyve
                          S NOPs

```

Underload:

<pre><code>(廿)                         Push 廿 onto the stack
    "二十""h                 NOPs
            a                Enclose TOS with braces
             i"tyve➡  NOPs
                           S Output TOS
```
</code></pre>

---
Tags: natural-language, polyglot, rosetta-stone
---