title: How long does it take to type this?

text:
# Question
Title: How long does it take to type this?
## Introduction

I can type at a moderate pace, using the QWERTY keyboard layout. But if a word like yellowwooddoor has a ton of repeated letters, it takes a bit longer to type it. Even worse is when a word like "jump" has the same finger used for multiple different consecutive letters.

Here's how long it takes me to type letters on each finger (very unscientifically measured):

Columns are Finger name, keystrokes/second, seconds/keystroke, and the keys used by each finger

```
Typing same letter twice:
L Pinky 5.2 0.1923076923 1qaz
L Ring  5   0.2          2wsx
L Mid   5.3 0.1886792453 3edc
L Index 5.5 0.1818181818 4rfv5tgb
R Thumb 6.5 0.1538461538 [space]
R Index 6.9 0.1449275362 6yhn7ujm
R Mid   6.3 0.1587301587 8ik,
R Ring  6.2 0.1612903226 9ol.
R Pinky 6.1 0.1639344262 0p;'

Typing different letter on same finger:
L Pinky 4.6 0.2173913043
L Ring  4.6 0.2173913043
L Mid   4.5 0.2222222222
L Index 5.3 0.1886792453
R Index 5.4 0.1851851852
R Mid   5.1 0.1960784314
R Ring  5.2 0.1923076923
R Pinky 5.2 0.1923076923

```

Same data in CSV format.

It takes

```
.75 * (first_finger_same_letter_time + second_finger_same_letter_time) / 2

```

time to switch between two fingers.

## Challenge

Given a string as input, how long does it take to type it?

* The "timer" starts the moment the first key is pressed and ends when the last key is pressed. You are just counting the time between keypresses.
* This is . Shortest answer in bytes wins.
* Submission can be either a complete program or function.
* Input and output any way you want it, stdin/out, function params, file, doesn't matter.
* Output should be accurate to at least 3 decimal places (+/- 0.001 for rounding error is fine). Leading 0. for numbers under 1 and trailing newline optional.
* Input will be a string that contains (lowercase) a-z, 0-9, space, semicolon, comma, period, and apostrophe.
* I always type spaces with my right thumb.
* I use the normal touch typing fingers (you can also look at the above table for finger-key mappings).
* Reference code used to generate test cases

## Test cases

(empty string or any one-character string) - 0.000

`aa` \- 0.192

`fff` \- 0.364

`fj` \- 0.123

`the quick brown fox jumped over the lazy dog` \- 5.795

`yellowwooddoor` \- 1.983

`orangewooddoor` \- 1.841

`jump on it, jump on it` \- 2.748

`type on it, type on it` \- 2.549

`abcdefghijklmnopqrstuvwxyz01234567890 ;,.'` \- 5.746

`ok, this may not be the most accurate but it's in the ballpark, maybe within 30 percent or so.` \- 12.138

# Answer
> 7 votes
# JavaScript (Node.js), 180 bytes

```
s=>(B=Buffer)(s).map(p=c=>(b='23841410645532207643205431765001333746443'[c*45%91%73%41]*2,t+=1/p?p-b?3/8*(g(b)+g(p)):g(b|c!=s):0,p=b,s=c),t=0,g=x=>10/B('4.2.5-75E6?3>4=4AA')[x])&&t

```

Try it online!

## How?

### Storing delays

The helper function \\$g\\$ takes an integer \\$0\le x \le17\\$ and returns a delay in seconds.

```
g = x => 10 / Buffer('4.2.5-75E6?3>4=4AA')[x]

```

The input \\$x\\$ is expected to be either:

* twice the bin number to get the delay for the same letter
* twice the bin number + 1 to get the delay for different letters

What is actually stored in the string `'4.2.5-75E6?3>4=4AA'` is the number of keystrokes per second multiplied by \\$10\\$ and converted to ASCII. Conveniently, all resulting characters are printable.

For instance, \\$5.2\\$ is stored as `chr(52)` which is `'4'`.

### Converting a character to a key bin

We use the following hash function to convert an ASCII code \\$c\\$ to an index into a lookup table containing the bin numbers in \\$\[0..8\]\\$:

$$i = (((c\times 45) \bmod 91)\bmod 73)\bmod 41$$

### Main loop

The total time \\$t\\$ is updated with:

```
t +=                        // add to t:
  1 / p ?                   //   if p is numeric:
    p - b ?                 //     if p is not equal to b:
      3 / 8 * (g(b) + g(p)) //       0.75 * (g(b) + g(p)) / 2
    :                       //     else:
      g(b | c != s)         //       g(b) if c == s or g(b + 1) otherwise
  :                         //   else (first iteration):
    0                       //     leave t unchanged

```

where \\$p\\$ is the previous bin and \\$s\\$ is the previous character.

# Answer
> 4 votes
# Jelly, 78 bytes

```
“bk¶ŀqṣṁq*E’b25+45s2
Øq;"““;“,.'”Zṙ-ØD;"s2ẎW$€3,4¦ẎœiⱮQḢ€ị¢QƑịZƊQ3.75⁵Ḋ?÷$SµƝS

```

**Try it online!**

### How?

```
“...’b25+45s2 - Link 1, keystrokes per 10 seconds: no arguments
“...’         - base 250 integer = 379310849477441257135820
     b25      - to base 25 = [16,7,7,1,5,1,8,0,10,8,24,9,18,6,17,7,20]
        +45   - add 45 = [61,52,52,46,50,46,53,45,55,53,69,54,63,51,62,52,65]
           s2 - split into twos
              - = [[61,52],[52,46],[50,46],[53,45],[55,53],[69,54],[63,51],[62,52],[65]]
             - For: 0...    1...    2...    3...    4...    6...    8...    9...    space

Øq;"““;“,.'”Zṙ-ØD;"s2ẎW$€3,4¦ẎœiⱮQḢ€ị¢QƑịZƊQ3.75⁵Ḋ?÷$SµƝS - Main Link: list of characters
                                                      µƝ  - for each neighbouring pair:
Øq                                                        -   qwerty = ["qwertyuiop","asdfghjkl","zxcvbnm"]
    ““;“,.'”                                              -   list of lists = ["",";",",.'"]
   "                                                      -   zip with:
  ;                                                       -     concatenate = ["qwertyuiop","asdfghjkl;","zxcvbnm,.'"]
            Z                                             -   transpose = ["qaz","wsx","edc","rfv","tgb","yhn","ujm","ik,","ol.","p;'"]
             ṙ-                                           -   rotate left -1 = ["p;'","qaz","wsx","edc","rfv","tgb","yhn","ujm","ik,","ol."]
               ØD                                         -   digits = "0123456789"
                  "                                       -   zip with:
                 ;                                        -     concatenate = ["0p;'","1qaz","2wsx","3edc","4rfv","5tgb","6yhn","7ujm","8ik,","9ol."]
                   s2                                     -   split into twos = [["0p;'","1qaz"],["2wsx","3edc"],["4rfv","5tgb"],["6yhn","7ujm"],["8ik,","9ol."]]
                            ¦                             -   sparse application...
                         3,4                              -   ...to indices: [3,4]
                       $€                                 -   ...do: last two links as a monad for each:
                     Ẏ                                    -     tighten
                      W                                   -     wrap in a list = [["0p;'","1qaz"],["2wsx","3edc"],["4rfv5tgb"],["6yhn7ujm"],["8ik,","9ol."]]
                             Ẏ                            -   tighten = ["0p;'","1qaz","2wsx","3edc","4rfv5tgb","6yhn7ujm","8ik,","9ol."]
                                 Q                        -   de-duplicate (the neighbouring letters)
                                Ɱ                         -   map with:
                              œi                          -     multi-dimensional index-into    e.g. "fj" -> [[5,3],[6,7]]
                                                          -     (note <space> is not there so yields an empty list)
                                  Ḣ€                      -   head of each                                -> [5,6]
                                                          -     (...and the head of an empty list is 0)
                                     ¢                    -   call the last Link (1) as a nilad
                                    ị                     -   index-into                                  -> [[55,53],[69,54]]
                                                          -     (...and 0 indexes into the rightmost entry)
                                          Ɗ               -   last three links as a monad:
                                       Ƒ                  -     invariant under?:
                                      Q                   -       de-duplicate (1 if so, else 0)
                                         Z                -       transpose                               -> [[55,69],[53,54]]
                                        ị                 -       index-into                              -> [55,69]
                                           Q              -   de-duplicate                                -> [55,69]
                                                    $     -   last two links as a monad:
                                                  ?       -     if...
                                                 Ḋ        -     ...condition: dequeue
                                            3.75          -     ...then: 3.75
                                                ⁵         -     ...else: 10                               -> 3.75
                                                   ÷      -     divide                                    -> [0.06818181818181818,0.05434782608695652]
                                                     S    -   sum                                         -> 0.12252964426877469
                                                        S - sum

```

# Answer
> 2 votes
# 05AB1E, ~~92~~ 86 bytes

```
Îü)v•δ'ā∍ë*8U¾Ã•₂в45+2ô9ÝÀžV€Sζ‚ø˜ð",.;'"S.;ykD4/ïD3›-D4›-‚©θè®€ËOUεXè}T/zX_iO3*8/ëθ]O

```

Try it online or verify all test cases.

**Explanation:**

```
Î                     # Push 0 and the input-string
 ü)                   # Create all pairs of the (implicit) input-string
                      # (which will be [] if the input-string is of length 0 or 1)
                      #  i.e. "ab d" → ["a","b"],["b"," "],[" ","d"]]
   v                  # Loop over these pairs `y`:
    •δ'ā∍ë*8U¾Ã•     '#  Push compressed integer 307264255556527588774514
      ₂в              #  Converted to Base-26 as list: [7,1,5,1,8,0,10,8,24,9,18,6,17,7,16,7,20]
        45+           #  Add 45 to each: [52,46,50,46,53,45,55,53,69,54,63,51,62,52,61,52,65]
           2ô         #  Split into parts of size 2: [[52,46],[50,46],[53,45],[55,53],[69,54],[63,51],[62,52],[61,52],[65]]
    9Ý                #  Push list [0,1,2,3,4,5,6,7,8,9]
      À               #  Rotate it once to [1,2,3,4,5,6,7,8,9,0]
       žV             #  Push builtin ["qwertyuiop","asdfghjkl","zxcvbnm"]
         €S           #  Convert each to a list of characters
           ζ          #  Zip/transpose; swapping rows/columns, with space as default filler:
                      #   [["q","a","z"],["w","s","x"],["e","d","c"],["r","f","v"],["t","g","b"],["y","h","n"],["u","j","m"],["i","k"," "],["o","l"," "],["p"," "," "]]
            ‚ø        #  Pair it with the digit list, and zip/transpose again
              ˜       #  Then flatten this entire list:
                      #   ["1","q","a","z","2","w","s","x","3","e","d","c","4","r","f","v","5","t","g","b","6","y","h","n","7","u","j","m","8","i","k"," ","9","o","l"," ","0","p"," "," "]
               ð",.;'"S.;
                      #  Replace the four spaces with [",", ".", ";", "'"] in order
     yk               #  Get the indices of the characters in the pair `y` in this list
                      #   i.e. ["b"," "] → [19,-1]
        4/            #  Divide both by 4
                      #   i.e. [19,-1] → [4.75,-0.25]
          ï           #  Floor the decimals to integers
                      #   i.e. [4.75,-0.25] → [4,-1]
           D3›-       #  If an index is larger than 3: decrease it by 1
                      #   i.e. [4,-1] → [3,-1]
               D4›-   #  If an index is now larger than 4: decrease it by 1 again
       D           ‚  #  Pair it with the original index
                      #   i.e. [[19,-1],[3,-1]]
                    © #  And save it in the register (without popping)
     θè               #  Then use the last of the two to index into the list of pairs
                      #   i.e. [3,-1] → [[55,53],[65]]
       ®€Ë            #  Check for each pair in the register if they're equal
                      #   i.e. [[19,-1],[3,-1]] → [0,0]
          O           #  Take the sum of that
           U          #  And pop and store it in variable `X`
            ε  }      #  Map the pairs in the list to:
             Xè       #   The `X`'th value in the pair
                      #    i.e. [[55,53],[65]] and `X`=0 → [55,65]
     T/               #  Divide each by 10
                      #   i.e. [55,65] → [5.5,6.5]
       z              #  And take 1/value for each
                      #  i.e. [5.5,6.5] → [0.181...,0.153...]
        X_i           #  If variable `X` was 0:
           O          #   Take the sum of these decimal values
                      #    i.e. [0.181...,0.153...] → 0.335...
            3*8/      #   Multiply it by 3, and then divide it by 8
                      #    i.e. 0.335... → 0.125...
          ë           #  Else:
           θ          #   Pop the pair of decimal values, and only leave the last one
   ]                  # Close both the if-else statement and the loop
    O                 # And take the sum of the stack
                      # (which is output implicitly as result)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•δ'ā∍ë*8U¾Ã•` is `307264255556527588774514` and `•δ'ā∍ë*8U¾Ã•₂в` is `[7,1,5,1,8,0,10,8,24,9,18,6,17,7,16,7,20]`.

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


title: New Order #1: How does this feel?

text:
# Question
Title: New Order #1: How does this feel?
## Introduction

Putting all positive numbers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive numbers.

The first challenge in this series is to output a(n) for a given n as input, where a(n) is A064413, also known as the EKG sequence because the graph of its values resembles an electrocardiogram (hence the *"How does this feel"* reference). Interesting properties of this sequence are that all positive integers appear exactly once. Another notable feature is that all primes occur in increasing order.

## Task

Given an integer input n, output a(n).

\\$a(n)\\$ is defined as:

* \\$a(1) = 1; a(2) = 2;\\$
* for \\$n \> 2\\$, \\$a(n)\\$ is the smallest number not already used which shares a factor with \\$a(n-1)\\$

*Note: 1-based indexing is assumed here; you may use 0-based indexing, so \\$a(0) = 1; a(1) = 2\\$, etc. Please mention this in your answer if you choose to use this.*

## Test cases

```
Input | Output
--------------
1     | 1
5     | 3
20    | 11
50    | 49
123   | 132
1234  | 1296
3000  | 3122
9999  | 10374

```

## Rules

* Input and output are integers (your program should at least support input and output in the range of 1 up to 32767)
* Invalid input (floats, strings, negative values, etc.) may lead to unpredicted output, errors or (un)defined behaviour.
* Default I/O rules apply.
* Default loopholes are forbidden.
* This is , so the shortest answers in bytes wins

## Final note

See this related PP&CG question.

# Answer
> 2 votes
# 05AB1E, 25 bytes

```
1ˆ2ˆF∞.Δ¯yå≠¯θy¿2@*}ˆ}¯¨θ

```

0-indexed

Try it online or Output the first \\$n\\$ items.

**Explanation:**

```
1ˆ2ˆ            # Add both 1 and 2 to the global_array
F               # Loop the (implicit) input amount of times:
 ∞.Δ            #  Get the first 1-indexed value resulting in truthy for the following:
    ¯yå≠        #   Where this value is not in the global_array yet
              * #   AND:
        ¯θ ¿    #   Where the greatest common divisor of the last item of the global_array
          y @2  #   and the current value, is larger than or equal to 2
   }ˆ           #  After a new value has been found: add it to the global_array
}¯              # After the loop: push the global_array
  ¨θ            # Then remove the last element, and then take the new last element
                # (which is output implicitly as result)

```

# Answer
> 7 votes
# Haskell, ~~66 65~~ 64 bytes

```
f n|n<3=n|m<-n-1=[k|k<-[1..],k`gcd`f m>1,all(/=k)$f<$>[1..m]]!!0

```

Try it online!

# Answer
> 5 votes
# Haskell, 60 bytes

```
((1:2#[3..])!!)
n#l|x:_<-[y|y<-l,gcd y n>1]=n:x#filter(/=x)l

```

Try it online!

Zero-indexed; could save four bytes if series started with 2 (kinda (-1)-indexed, but without value for -1 being defined). Builds the infinite list by lazily maintaining the list of unused numbers.

# Answer
> 4 votes
# Python 2, 104 bytes

This uses 0-based indexing.

```
from fractions import*
l=[1,2]
exec'i=3\nwhile gcd(i,l[-1])<2or i in l:i+=1\nl+=i,;'*input()
print l[-2]

```

Try it online!

# Answer
> 1 votes
## Ruby, 86 bytes

```
a=->(n){n<3?n:1.step{|i|return i if a[n-1].gcd(i)!=1&&(0...n).map(&a).all?{|j|j!=i}}}

```

This runs forever for inputs as low as 10, though.

---

Here's a version with memoization with 102 bytes that runs in acceptable time:

```
m={};a=->(n){n<3?n:m[n]||1.step{|i|return m[n]=i if a[n-1].gcd(i)!=1&&(0...n).map(&a).all?{|j|j!=i}}}

```

# Answer
> 1 votes
# MACHINE LANGUAGE(X86, 32 bit)+C language library malloc()/free()functions, bytes 325

```
00000750  51                push ecx
00000751  52                push edx
00000752  8B44240C          mov eax,[esp+0xc]
00000756  8B4C2410          mov ecx,[esp+0x10]
0000075A  3D00000000        cmp eax,0x0
0000075F  7414              jz 0x775
00000761  81F900000000      cmp ecx,0x0
00000767  740C              jz 0x775
00000769  39C8              cmp eax,ecx
0000076B  7710              ja 0x77d
0000076D  89C2              mov edx,eax
0000076F  89C8              mov eax,ecx
00000771  89D1              mov ecx,edx
00000773  EB08              jmp short 0x77d
00000775  B8FFFFFFFF        mov eax,0xffffffff
0000077A  F9                stc
0000077B  EB11              jmp short 0x78e
0000077D  31D2              xor edx,edx
0000077F  F7F1              div ecx
00000781  89C8              mov eax,ecx
00000783  89D1              mov ecx,edx
00000785  81FA00000000      cmp edx,0x0
0000078B  77F0              ja 0x77d
0000078D  F8                clc
0000078E  5A                pop edx
0000078F  59                pop ecx
00000790  C20800            ret 0x8

00000793  53                push ebx
00000794  56                push esi
00000795  57                push edi
00000796  55                push ebp
00000797  55                push ebp
00000798  8B442418          mov eax,[esp+0x18]
0000079C  3D02000000        cmp eax,0x2
000007A1  7641              jna 0x7e4
000007A3  3DA0860100        cmp eax,0x186a0
000007A8  7757              ja 0x801
000007AA  40                inc eax
000007AB  89C7              mov edi,eax
000007AD  C1E003            shl eax,0x3
000007B0  50                push eax
000007B1  E80E050000        call 0xcc4
000007B6  81C404000000      add esp,0x4
000007BC  3D00000000        cmp eax,0x0
000007C1  743E              jz 0x801
000007C3  89C5              mov ebp,eax
000007C5  89F8              mov eax,edi
000007C7  C1E002            shl eax,0x2
000007CA  890424            mov [esp],eax
000007CD  50                push eax
000007CE  E8F1040000        call 0xcc4
000007D3  81C404000000      add esp,0x4
000007D9  3D00000000        cmp eax,0x0
000007DE  7415              jz 0x7f5
000007E0  89C3              mov ebx,eax
000007E2  EB28              jmp short 0x80c
000007E4  E9A3000000        jmp 0x88c
000007E9  53                push ebx
000007EA  E8E5040000        call 0xcd4
000007EF  81C404000000      add esp,0x4
000007F5  55                push ebp
000007F6  E8D9040000        call 0xcd4
000007FB  81C404000000      add esp,0x4
00000801  B8FFFFFFFF        mov eax,0xffffffff
00000806  F9                stc
00000807  E981000000        jmp 0x88d
0000080C C60301            mov byte [ebx],0x1
0000080F  C6430101          mov byte [ebx+0x1],0x1
00000813  C7450001000000    mov dword [ebp+0x0],0x1
0000081A  C7450402000000    mov dword [ebp+0x4],0x2
00000821  B902000000        mov ecx,0x2
00000826  BE01000000        mov esi,0x1
0000082B  B802000000        mov eax,0x2
00000830  8B542418          mov edx,[esp+0x18]
00000834  4A                dec edx
00000835  C6040300          mov byte [ebx+eax],0x0
00000839  40                inc eax
0000083A  3B0424            cmp eax,[esp]
0000083D  72F6              jc 0x835
0000083F  BF02000000        mov edi,0x2
00000844  81C701000000      add edi,0x1
0000084A  3B3C24            cmp edi,[esp]
0000084D  779A              ja 0x7e9
0000084F  803C3B01          cmp byte [ebx+edi],0x1
00000853  74EF              jz 0x844
00000855  57                push edi
00000856  51                push ecx
00000857  E8F4FEFFFF        call 0x750
0000085C  3D01000000        cmp eax,0x1
00000861  76E1              jna 0x844
00000863  46                inc esi
00000864  897CB500          mov [ebp+esi*4+0x0],edi
00000868  89F9              mov ecx,edi
0000086A  C6043B01          mov byte [ebx+edi],0x1
0000086E  39D6              cmp esi,edx
00000870  72CD              jc 0x83f
00000872  53                push ebx
00000873  E85C040000        call 0xcd4
00000878  81C404000000      add esp,0x4
0000087E  55                push ebp
0000087F  E850040000        call 0xcd4
00000884  81C404000000      add esp,0x4
0000088A  89F8              mov eax,edi
0000088C  F8                clc
0000088D  5D                pop ebp
0000088E  5D                pop ebp
0000088F  5F                pop edi
00000890  5E                pop esi
00000891  5B                pop ebx
00000892  C20400            ret 0x4
00000895

```

Above gcd and the function... This below assembly code generate the functions and the test program:

```
; nasmw -fobj  this.asm
; bcc32 -v  this.obj
section _DATA use32 public class=DATA

global _main
extern _printf
extern _malloc
extern _free

dspace dd 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

fmt db "%u " , 13, 10, 0, 0
fmt1 db "%u %u" , 13, 10, 0, 0

IgcdIIuIIIuIIIuIn db "gcd(%u, %u)=%u" , 13, 10, 0, 0
IfunIIuIIIuIn db "fun(%u)=%u" , 13, 10, 0, 0

section _TEXT use32 public class=CODE

gcd:
      push    ecx
      push    edx
      mov     eax,  dword[esp+  12]
      mov     ecx,  dword[esp+  16]
      cmp     eax,  0
      je      .e
      cmp     ecx,  0
      je      .e
      cmp     eax,  ecx
      ja      .1
      mov     edx,  eax
      mov     eax,  ecx
      mov     ecx,  edx
      jmp     short  .1
.e:   mov     eax,  -1
      stc
      jmp     short  .z
.1:   xor     edx,  edx
      div     ecx
      mov     eax,  ecx
      mov     ecx,  edx
      cmp     edx,  0
      ja      .1            ; r<c
.2:   clc
.z:
      pop     edx
      pop     ecx
      ret     8

fun:
      push    ebx
      push    esi
      push    edi

   push    ebp
      push    ebp
      mov     eax,  dword[esp+  24]
      cmp     eax,  2
      jbe     .a
      cmp     eax,  100000
      ja      .e
      inc     eax
      mov     edi,  eax
      shl     eax,  3
      push    eax
      call    _malloc
      add     esp,  4
      cmp     eax,  0
      je      .e
      mov     ebp,  eax
      mov     eax,  edi
      shl     eax,  2
      mov     dword[esp+  0],  eax
      push    eax
      call    _malloc
      add     esp,  4
      cmp     eax,  0
      je      .0
      mov     ebx,  eax
      jmp     short  .1
.a:   jmp     .y
.b:   push    ebx
      call    _free
      add     esp,  4
.0:   push    ebp
      call    _free
      add     esp,  4
.e:   mov     eax,  -1
      stc
      jmp     .z
.1:   mov     byte[ebx],  1
      mov     byte[ebx+1],  1
      mov     dword[ebp],  1
      mov     dword[ebp+4],  2
      mov     ecx,  2
      mov     esi,  1
      mov     eax,  2
      mov     edx,  dword[esp+  24]
      dec     edx
.2:   mov     byte[ebx+eax],  0
      inc     eax
      cmp     eax,  dword[esp+  0]
      jb      .2
.3:   mov     edi,  2
.4:   add     edi,  1
      cmp     edi,  dword[esp+  0]
      ja      .b
      cmp     byte[ebx+edi],  1
      je      .4
      push    edi
      push    ecx
      call    gcd
      cmp     eax,  1
      jbe     .4
      inc     esi
      mov     [ebp+esi*4],  edi
      mov     ecx,  edi
      mov     byte[ebx+edi],  1
      cmp     esi,  edx
      jb      .3
      push    ebx
      call    _free
      add     esp,  4
      push    ebp
      call    _free
      add     esp,  4
      mov     eax,  edi
.y:   clc
.z:
      pop     ebp
      pop     ebp
      pop     edi
      pop     esi
      pop     ebx
      ret     4

_main:
      pushad

      push    6
      push    3
      call    gcd
      pushad
      push    eax
      push    6
      push    3
      push    IgcdIIuIIIuIIIuIn
      call    _printf
      add     esp,  16
      popad
      push    2
      push    2
      call    gcd
      pushad
      push    eax
      push    2
      push    2
      push    IgcdIIuIIIuIIIuIn
      call    _printf
      add     esp,  16
      popad

      push    1
      push    1
      call    gcd
      pushad
      push    eax
      push    1
      push    1
      push    IgcdIIuIIIuIIIuIn
      call    _printf
      add     esp,  16
      popad
      push    0
      push    1
      call    gcd
      pushad
      push    eax
      push    0
      push    1
      push    IgcdIIuIIIuIIIuIn
      call    _printf
      add     esp,  16
      popad
      push    0
      call    fun
      pushad
      push    eax
      push    0
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    1
      call    fun
      pushadpush    eax
      push    1
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    2
      call    fun
      pushad
      push    eax
      push    2
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    3
      call    fun
      pushad
      push    eax
      push    3
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    4
      call    fun
      pushad
      push    eax
      push    4
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    5
      call    fun
      pushad
      push    eax
      push    5
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    123
      call    fun
      pushad
      push    eax
      push    123
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    1234
      call    fun
      pushad
      push    eax
      push    1234
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    3000
      call    fun
      pushad
      push    eax
      push    3000
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    9999
      call    fun
      pushad
      push    eax
      push    9999
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      push    99999
      call    fun
      pushad
      push    eax
      push    99999
      push    IfunIIuIIIuIn
      call    _printf
      add     esp,  12
      popad
      popad
      mov     eax,  0
      ret

```

the results:

```
gcd(3, 6)=3
gcd(2, 2)=2
gcd(1, 1)=1
gcd(1, 0)=4294967295
fun(0)=0
fun(1)=1
fun(2)=2
fun(3)=4
fun(4)=6
fun(5)=3
fun(123)=132
fun(1234)=1296
fun(3000)=3122
fun(9999)=10374
fun(99999)=102709

```

It is possible bugs and wrong copy past...

# Answer
> 1 votes
# Perl 6, ~~84~~ ~~80~~ ~~73~~ ~~***69***~~ ~~50~~ 49 bytes

(0-indexed)

```
{(1,2,{+(1...all @_[*-1]gcd*>1,*∉@_)}...*)[$_]}

```

Thanks to this answer for some tricks.

Thanks to ASCII-only for shaving a byte.

# Answer
> 0 votes
# APL(NARS), chars 119, bytes 238

```
∇r←a w;i;j;v
r←w⋄→0×⍳w≤2⋄i←2⋄r←⍳2⋄v←1,1,(2×w)⍴0
j←¯1+v⍳0
j+←1⋄→3×⍳1=j⊃v⋄→3×⍳∼1<j∨i⊃r⋄r←r,j⋄i+←1⋄v[j]←1⋄→2×⍳w>i
r←i⊃r
∇

```

this test it takes 1m:49s here:

```
  a¨1 5 20 50 123 1234 3000
1 3 11 49 132 1296 3122

```

# Answer
> 0 votes
# Java (JDK), ~~161~~ ~~155~~ ~~152~~ 151 bytes

Saved a byte by switching `int[]` tracking to leverage the existing `BigInteger`!

```
n->{int j,k=n;for(var b=java.math.BigInteger.ONE;0<--n;b=b.setBit(k=j))for(j=1;b.testBit(++j)|b.valueOf(j).gcd(b.valueOf(k)).intValue()<2;);;return k;}

```

Try it online!

# Answer
> 0 votes
# Gaia, 27 bytes

```
2┅@⟨:1⟪Ė₌0⟪;)d;d&1D⟫?⟫#+⟩ₓE

```

Try it online!

1-based indexing.

Runs rather slowly, as it tries each integer until it finds `a(n)`.

```
2┅				| push [1 2]
  @				| push n
   ⟨			 ⟩ₓ	| do n times:
    :				| dup
     1⟪		      ⟫#	| and find the first 1 integer i where the following results in a truthy value:
       Ė₌	     ?		| is i an Ėlement of the list? Also push an extra copy of the arguments
	 0			| if so, give falsy result, so try the next integer
	  ⟪	    ⟫		| else do the following:
	   ;)d			| get divisors of a(n-1)
	      ;d		| get divisors of i
		&1D		| set intersect and remove the first element (which is always 1)
				| this yields an empty set if no divisors are shared (falsy, so try next integer)
				| or a non-empty set (truthy, so returns i = a(n))
			+	| and concatenate to list (end loop).
			   E	| finally, Extract the nth element (n taken implicitly)

```

---
Tags: code-golf, number, sequence
---


title: The Alphabet Chromosome

text:
# Question
Title: The Alphabet Chromosome
## Introduction

Alphabet challenges are in our DNA, so let's show it.

## Challenge

Print the following the text exactly:

```
AaBbCc        cCbBaA
BbCcDd        dDcCbB
EeFfGg        gGfFeE
HhIiJj        jJiIhH
KkLlMm        mMlLkK
NnOoPp        pPoOnN
QqRrSs        sSrRqQ
TtUuVv        vVuUtT
   WwXx      xXwW
       Yy  yY
         ZZ
         zz
         ZZ
       Yy  yY
   WwXx      xXwW
TtUuVv        vVuUtT
QqRrSs        sSrRqQ
NnOoPp        pPoOnN
KkLlMm        mMlLkK
HhIiJj        jJiIhH
EeFfGg        gGfFeE
BbCcDd        dDcCbB
AaBbCc        cCbBaA

```

## Rules

* You must match the case of each letter
* Trailing and/or leading newlines and/or spaces are allowed

## Winning

Shortest code in bytes wins.

# Answer
# Vim (no external tools), 106 bytes

Newlines for clarity:

```
:h<_↵↵↵YZZPllabc♥
:s/./\u&&/g↵
qa6li↵♥q7@a3i ♥fY
i↵    →→↵  →↵→ð♥
ʌHA ♥9l
qbmaʌ99jY$P`ah@bq@b
y11G:g//m0↵P

```

Here  is Return,  is Right,  is Escape, `ʌ` is CTRL-V, and `ð` is Delete.
> 18 votes

# Answer
## PowerShell v2+, ~~175~~ ~~169~~ ~~163~~ 154 bytes

```
($x=(-join(65..67+66..86|%{$_;32+$_}|%{[char]$_})-split'(.{6})'-ne'')+'   WwXx'+'       Yy'+(' '*9+'Z')|% *ht 10|%{$_+-join$_[9..0]})
' '*9+'zz'
$x[10..0]

```

Try it online!

Abuses the fact that default `Write-Output` at the end of execution inserts a newline between elements.

The first line constructs the branches. We loop over two ranges corresponding to the ASCII values for the capital letters, each iteration output a `char` array of that letter and that letter `+32` (which is the lowercase ASCII point). That's `-join`ed together into one long string, then `-split` on every six elements (encapsulated in parens so they're preserved), followed by a `-ne''` to pull out the empty elements as a result of the split, thus forming an array of strings.

These strings in an array get array-concatenation to add on the `WwXx`, `Yy`, and `Z` elements, then a PadRig`ht 10` to make them all the appropriate width. At this point we have an array of strings like the following (one element per line).

```
AaBbCc
BbCcDd
EeFfGg
HhIiJj
KkLlMm
NnOoPp
QqRrSs
TtUuVv
   WwXx
       Yy
         Z

```

That whole array is piped to another loop to construct the mirrored strings with `-join` and array-reversing `[9..0]`.

```
AaBbCc        cCbBaA
BbCcDd        dDcCbB
EeFfGg        gGfFeE
HhIiJj        jJiIhH
KkLlMm        mMlLkK
NnOoPp        pPoOnN
QqRrSs        sSrRqQ
TtUuVv        vVuUtT
   WwXx      xXwW
       Yy  yY
         ZZ

```

We save the resulting strings into `$x` and enclose in parens to also place a copy on the pipeline.

The next line places the `zz` string on the pipeline, then the `$x` array in reverse order. All of those are left on the pipeline and output is implicit.

```
PS C:\Tools\Scripts\golfing> .\alphabet-chromosome.ps1
AaBbCc        cCbBaA
BbCcDd        dDcCbB
EeFfGg        gGfFeE
HhIiJj        jJiIhH
KkLlMm        mMlLkK
NnOoPp        pPoOnN
QqRrSs        sSrRqQ
TtUuVv        vVuUtT
   WwXx      xXwW
       Yy  yY
         ZZ
         zz
         ZZ
       Yy  yY
   WwXx      xXwW
TtUuVv        vVuUtT
QqRrSs        sSrRqQ
NnOoPp        pPoOnN
KkLlMm        mMlLkK
HhIiJj        jJiIhH
EeFfGg        gGfFeE
BbCcDd        dDcCbB
AaBbCc        cCbBaA

```

*-9 bytes thanks to mazzy.*
> 3 votes

# Answer
## Python 2, 230 bytes

```
s='';m=['AaBbCc','BbCcDd','EeFfGg','HhIiJj','KkLlMm','NnOoPp','QqRrSs','TtUuVv','   WwXx',' '*7+'Yy',' '*9+'Z'];
p=lambda l:l.ljust(10)+l[::-1].rjust(10)+'\n';
for l in m:s+=p(l);
s+=' '*9+'zz\n';
for l in m[::-1]:s+=p(l)
print s

```
> 3 votes

# Answer
# Python 2, 156 bytes

```
r=('AaBbCc.BbCcDd.EeFfGg.HhIiJj.KkLlMm.NnOoPp.QqRrSs.TtUuVv.   WwXx.%8cy.%10c.%10c'%(89,90,'z')).split('.')
for k in r+r[-2::-1]:s='%-10s'%k;print s+s[::-1]

```

Try it online!

Maybe the formula `512/(i**4+47)-1` is of interest to future golfers: it maps the integers around 0 to $$\cdots,-1,-1,0,3,7,9,\fbox{9},9,7,3,0,-1,-1,\cdots$$

which encodes how many spaces to prepend to each line (`(-1)*' '` being equal to `0*' '`).
> 3 votes

# Answer
# Python 2, ~~331~~ ~~241~~ 229 bytes

~~Will golf it more later.~~

```
l=("AaBbCc|BbCcDd|EeFfGg|HhIiJj|KkLlMm|NnOoPp|QqRrSs|TtUuVv|   WwXx|%sYy"%(" "*7)).split("|");n=0;v=1;p='for i in([8]*8+[6,2])[::v]:print l[n]+" "*i+l[n][::-1];n+=v';exec p;v=-1;n=9;print"{0}ZZ\n{0}zz\n{0}ZZ".format(" "*9);exec p

```
> 2 votes

# Answer
# Lua, 212 Bytes

```
s=([[         Z
       Yy
   WwXx
TtUuVv_QqRrSs_NnOoPp_KkLlMm_HhIiJj_EeFfGg_BbCcDd_AaBbCc    ]]):gsub("_","    \n")S="         zz"for z in s:gmatch"[%w ]+"do k=z..z:reverse()S=k..'\n'..S..'\n'..k end print(S)

```

Simple enough, based off of TimmyD's answer, kind of. Builds the top left arm using a really poorly compressed chunk, then does both mirrors at once around a 'zz', and prints.

Try it on Repl.It
> 2 votes

# Answer
# Stax, ~~42~~ ~~41~~ ~~38~~ 35 bytes

```
înáöêòé{V║»╧å╓ä¥ì√‼╦▓°nlΓΣ▌ê9t☻*$╢√

```

Run and debug it

*Update:* There was a bug in the 41 byte solution. (yes, even though it has no input) While fixing it, I found 3 more bytes to shave.

*Update again:* There's competition afoot, so I removed 3 more contingency bytes.

**Explanation:** *(of a different, yet identically sized solution)*

```
VA3(        "ABC"
VAD2T       "BCD...VWX"
+3/         concatenate and split into groups of 3
'Y]+        concatenate ["Y"]
{cv\$m      map each string using: copy, lowercase, zip, flatten
.ZzM+       concatenate ["Z", "z"]
|p          palindromize list of strings
m           map each string _ using the rest of the program and implicitly print output
  c%Nh6+H   (-len(_)/2 + 6) * 2
  )         left-pad (npm lol amirite) to length
  A(        right-pad to 10
  :m        mirror (a + a[::-1])

```

Run this one
> 2 votes

# Answer
# 05AB1E, ~~48~~ ~~46~~ ~~40~~ ~~38~~ 36 bytes

```
Ž3ô8.DƵJ6XD)bTj»0ð:1žRAu¦«Dl.ιS.;º.∊

```

-2 bytes (and the opportunity for 10 more with this alternative approach) thanks to *@MagicOctopusUrn*.

Try it online.

**Explanation:**

```
Ž3ô            # Push compressed integer 1008
   8.D         # Duplicate it 8 times
      ƵJ       # Push compressed integer 120
        6      # Push 6
         XD    # Push 1 twice
           )   # Wrap all into a list
b              # Convert each to binary
 Tj            # Add leading spaces to each binary-string to make them size 10
   »           # Then join all strings by newlines
0ð:            # Replace all 0s with spaces
 žR            # Push the string "ABC"
   Au¦«        # Merge the uppercased alphabet minus the first "A" with it
       Dl      # Create a lowercase copy
         .ι    # Intersect the uppercase and lowercase strings: "AaBbCcBb..."
           S   # Convert it to a list of characters
1           .; # Replace every 1 with each of these characters in the same order
º              # Then mirror everything vertically without overlap,
 .∊            # and horizontally with the last line overlapping
               # (and output the result implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž3ô` is `1008` and `ƵJ` is `120`.
> 2 votes

# Answer
# Matricks, 105 bytes (noncompeting)

Whoa, I found a lot of bugs. The only hard part of this challenge was the cross in the middle. That makes almost half the byte count.

Run with the `-A 1` flag

```
m+/c2+66+*r3*32%c2 7 6v{k-{}1z-L1Q}u{q-Lc2k+{}2b0b0b0a[a0a0u[a89a121]a[u0u90]]}a{Y}u[mQc9a122a122]u{z1cX}

```

Explanation:

```
m+/c2+66+*r3*32%c2 7 6                       # Construct the "normal" block
v{k-{}1z-L1Q}                                # Add the "abnormal" part above
u{q-Lc2k+{}2b0b0b0a[a0a0u[a89a121]a[u0u90]]} # Make the 1/4 of the weird diagonal
a{Y}u[mQc9a122a122]u{z1cX}                   # Mirror the block just created, adding
                                             # lowercase zs in between halves

```

Another bug I haven't fixed yet is that the last part, `u{z1cX}` doesn't work when you put the cut after the `X`. Will investigate/fix.
> 1 votes

# Answer
# ///, 229 bytes

```
/*/\/\///^/        *0/AaBbCc^cCbBaA
*1/BbCcDd^dDcCbB
*2/EeFfGg^gGfFeE
*3/HhIiJj^jJiIhH
*4/KkLlMm^mMlLkK
*5/NnOoPp^pPoOnN
*6/QqRrSs^sSrRqQ
*7/TtUuVv^vVuUtT
*8/   WwXx      xXwW
*9/       Yy  yY
/0123456789^ ZZ
^ zz
^ ZZ
9876543210

```

Try it online!
> 1 votes

# Answer
# PowerShell, 150 bytes

```
($x='AaBbCc
BbCcDd
EeFfGg
HhIiJj
KkLlMm
NnOoPp
QqRrSs
TtUuVv
   WwXx
       Yy
         Z'-split'
'|% *ht 10|%{$_+-join$_[9..0]})
' '*9+'zz'
$x[10..0]

```

Try it online!
> 1 votes

# Answer
# Brainfuck, 456 bytes

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

```

Try it online!
> 1 votes

# Answer
# Python 3, 215 bytes (Non-Competing)

```
p=lambda l:l.ljust(10)+l[::-1].rjust(10)
a=("AaBbCc|BbCcDd|EeFfGg|HhIiJj|KkLlMm|NnOoPp|QqRrSs|TtUuVv|   WwXx|%sYy|%sZ"%(7*' ',9*' ')).split('|')
print('\n'.join([p(x)for x in a]+[' '*9+'zz']+[p(x)for x in a[::-1]]))

```

Try it online!

Takes some ideas from the two Python 2 solutions, but applies them to an approach using join() that seems to save quite a few bytes. It's possible that this can be golfed further; I might revisit this later.
> 0 votes

# Answer
# Ruby, ~~177 ...~~  145 bytes

```
puts r=(("%s%s%s\n"*8+"%5s%s\n%9s\n%11s")%[*?a..?c,*?b..?z].map{|x|x.upcase+x}).lines.map{|l|l=l.chop.ljust 10;l+l.reverse},"%11s"%"zz",r.reverse

```

Try it online!
> 0 votes

# Answer
# Bubblegum, 168 bytes

```
00000000: 6dd1 c712 8230 1006 e0fb 3e45 5e85 264d  m....0....>E^.&M
00000010: 7a51 b8a1 14e9 1d91 a757 4632 ce38 9bd3  zQ.......WF2.8..
00000020: e6cb a4ec 1f26 626f dc9d 1ce3 cedd d888  .....&bo........
00000030: 819d f898 62cc ef0c 4272 4ac5 8c62 26a6  ....b...BrJ..b&.
00000040: a744 00e9 21e7 4a41 b150 72f9 2181 5a9e  .D..!.JA.Pr.!.Z.
00000050: 2bad a658 6bd5 b954 416f 8cd6 ec28 7666  +..Xk..TAo...(vf
00000060: 6b34 3a58 bd3d 3823 c5d1 19ec de02 77f2  k4:X.=8#......w.
00000070: 667f a1b8 f8b3 37b9 f0a9 2ecf ebfa b5f5  f.....7.........
00000080: fabc c0b1 1ebc 0879 0574 4648 18fe ea6d  .......y.tFH...m
00000090: c3fc b7e3 ef44 f462 f489 6833 68db 6840  .....D.b..h3h.h@
000000a0: 6894 68e8 0cf2 3d6f                      h.h...=o

```

Try it online!

Since this is my first Bubblegum submission, it might not be the optimal solution. Please double-check.
> 0 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity, alphabet
---


title: Compile Quarterstaff to BF

text:
# Question
Title: Compile Quarterstaff to BF
Quarterstaff repo here with additional quarterbf interpreter: rather bereft of documentation, however, but it does contain the two interpreters

you can go to https://tio.run/#quarterstaff to run quarterstaff programs online. however, the TIO BF implementation seems to have limited cells, according to the documentation

---

The title is rather descriptive, except that it doesn't describe what Quarterstaff and BF are. For this challenge, I have created two languages: Quarterstaff, and a dialect of BF that probably already existed in its exact form, but I wanted to be certain, especially with the I/O format, that it would work, called QuarterBF. In this challenge, you will compile a program written Quarterstaff to QuarterBF (but the underlying conversion should work for any generic BF dialect with byte cells and an infinite tape and such).

I have created interpreters for both of these. However, should you find the spec for one of them here conflicts with the interpreter, the spec is prioritised for the challenge (the interpreters should just be helping you out here)

First, the QuarterBF spec, since it will be easier to explain some of the Quarterstaff concepts afterwards (I cribbed some of this from the esolangs page for Brainf\***):

## BF spec

Brainfuck operates on an array of memory cells, also referred to as the tape, each initially set to zero. These memory cells can each hold an integer between 0 and 255, inclusive, and the tape extends infinitely to the right (some implementations will use a limited number of cells, hence I made my own to be sure / make an appropriate interpreter easy to find). There is a pointer, initially pointing to the first memory cell. There are no cells to the left of the first memory cell, and attempting to move further left is undefined behaviour. The commands are:

```
> : move the pointer to the right
< : move the pointer to the left
+ : increment the cell under the pointer, unless the cell is 255, in which case set cell to 0
- : decrement the cell under the pointer, unless the cell is 0, in which case set cell to 255
, : input a character code into the cell under the pointer (described more below)
. : output the character that the integer in the cell under the pointer represents
[ : Jump past the matching ] if the cell under the pointer is 0
] : Jump back to the matching [ if the cell under the pointer is nonzero

```

In QuarterBF input is interactive. The exact mechanism this works by could be gleaned by reading the source if you wanted, but it's not totally necessary. The important points: it sets a cell to the character code of an input character, sets to 0 on EOF, and to 10 for end of line newlines (which is the newline charcode)

Either way, you don't have to worry so much about how input works, because the values of `?` and `!` translate essentially perfectly to the values `,` and `.` anyway.

## Quarterstaff spec:

Quarterstaff's memory consists of registers. one of these registers is called "value", and the others are named variables. variables are case sensitive. Variables can be referenced before assignment and are initially zero (alternately, referencing a variable before assignment does nothing, because if it hasn't been assigned yet, it means it has a value of zero, therefore adding zero has no effect).

```
[a string of digits] : add the number those digits represent to the value
[a string of letters not preceded by >] : add the variable that the name represents to value
[a string of letters preceded by >] : set the variable to the current value, set value to 0
. : set value to zero
- : multiply value by -1
? : add to value the amount that the underlying bf implementation would set a cell to when , is executed
! : output the character with the charcode corresponding to value.
[ : Jump past the matching ] if value is 0
] : Jump back to the matching [ if value is nonzero
([...] is a while loop)
{ : Jump past the matching } if value is nonzero
} : Jump back to the matching { if value is 0
({...} is a while-not loop)
(, |, ): part of an if else construct...
[any characters not mentioned here] separator between commands; doesn't execute anything, but separates variables or numbers

```

### Explanation of if:

if-style 1:

```
when coming to this paren, check if value is zero or not
v
(...)
  ^  if value was nonzero, execute the commands within

either way, then continue execution after the )

```

if-style 2:

```
when coming to this paren, check if value is zero or not
v
(...|...)
  A   B
if the value is nonzero, execute the subprogram designated A. else execute the one designated B.
then, continue execution after the closing )

```

`(...)` is equivalent to `(...|)`

# The challenge

Taking a quarterstaff program as input, compile it to BF; output a program which functions the same, but in BF.

i.e.

* it halts if and only if the inputted program halts
* outputs the exact same text as it.
* if it doesn't halt, it should print the text that the original program prints in finite time, in finite time (it shouldn't put output into a buffer and then print it when it stops executing or something)

### Allowances and some restrictions:

* you may assume that input to the outputted program is always in printable ASCII and ASCII whitespace (and EOF. Basically, no need to worry about any characters \>255 overflowing or whatever), and that the quarterstaff program will never try to output anything other than printable ASCII and ASCII whitespace.
* you may assume the inputted program is only ascii printables and ascii whitespace
* you may **not** assume that the variables and values only go up to 255. you need to implement **infinite** variables and accumulator
* basically, you don't get to limit anything (except possible i/o characters). your bf spec has infinite cells, you can use them!
* you may assume that the Quarterstaff program has fully matched brackets, and does not invoke undefined behaviour (e.g. trying to output non-ASCII like I mentioned earlier)
* you should **not** invoke undefined behaviour in your outputted bf program. just because I included an interpreter doesn't mean you get to exploit any bugs or lack of exceptions for undefined behaviour. When the spec in this question and implementation differ, follow the question spec. This includes when the interpreter technically could suffer from recursing too deep. doesn't mean you get to assume that a program never recurses that much.

Scoring is by the length of the program, shorter is better; (this is not metagolf, the length of your bf programs does not matter, as long as they work)

### test cases:

prime tester (slightly different from my answer on the prime challenge; a space was replaced with a newline):

```
10-?[-38a a a a a a a a a a>a10-?]a>b
b[>b>d a>c c[1>c1d>d b d(.>e|>d1>e)c]e f>f1b]2-f(.|1)48!

```

cat (prints each line after you input it, then exits on EOF)

```
?[!?]

```

prints a newline

```
10!

```

also prints a newline

```
5 5!

```

truth machine:

```
49-?{49!}49!

```

# Answer
# Python 3.8 (pre-release), 769 bytes

```
import base64,zlib
exec(zlib.decompress(base64.b85decode('c$|e(O>dkq5WVv&NG^sQ59(GuRK#}Fdv=dG)b#;{MMCnD$WWA)xWB#6EcrN8>cx!5<2TRq9{u_0F--aRYn0)X-RUJ}NBuc_(1O`p??iUc`>fZ(TQ;OzP-HE8guxkB&RDAgS--{(feY*i#mIVtV^(BvOJt)Kq%1RAA_5p7)CPe{;BX-10FW+u3dSkV4A4M;_<vo>uMN==IgxdbA%B*$9OOCghdi9Bt{>XQ`$81vwk&MJzrXQ!N99ZLqfM)IHZH|WS>0Z-D}}^Zs&Q)jp$ey_Ey}Xa^1jRG`l!#%b8(b=D&|_>RpV)DPhIoVPsJ>cWm(?L@?HxicC!=)>rJC)>V)OxK7#!+M<?k1rq!JYc4?xqYUv}=lnU5kyj%8?N^e3|;i1bIFUlk;&-Df|N6Ri1VzjS!oB_%|4=~YpjG;cP&pF7U*8MOQ1Ng77OTQbU1<1#i=ep787@UHXD@-ty#%}E@Dq{~_p%Bzk7vh0jD%eza$i3<01$tQk;y4jbpI3TP1jWW08<M3Q-oHABlXH?2E)Y0O^P-diDbU*b(AEcAmvB`wp8@s<7csy4$ir*tl6z}j880LTVI*oG5cqx=hipi=w+Ptp@%k$OA{iXS2pkfF4fs-I)5cj*@zt$c;!7!3gBIt~W%&c?HhT(5j!u~6I?(m*5D^$cbd1YG6x9@(Vf4*(Dwh4HuQmTU?%+AO-+#HpM#QrG3m~&3+y')))

```

Try it online! Test suite (also executes brainfuck)

OK, so this is a version following the specifications, but the rules seem to be missing that `!` resets the value to 0. So, at a cost of two bytes, here is a fixed version:

# Python 3.8 (pre-release), 771 bytes

```
import base64,zlib
exec(zlib.decompress(base64.b85decode('c$|e(O>dkq5WVv&NG^sQ59(GuRK#}Fdv=dG)b#;{MMCnD$WWA)xWB#6EcrN8>cx!5<2TRq9{u_0F--aRYn0)X-RUJ}NBuc_(1O`p??iUc`>fZ(TQ;OzP-HE8guxkB&RDAgS--{(feY*i#mIVtV^(BvOJt)Kq%1RAA_5p7)CPe{;BX-10FW+u3dSkV4A4M;_<vo>uMN==IgxdbA%B*$9OOCghdi9Bt{>XQ`$81vwk&MJzrXQ!N99ZLqfM)IHZH|WS>0Z-D}}^Zs&Q)jp$ey_Ey}Xa^1jRG`l!#%b8(b=D&|_>RpV)DPhIoVPsJ>cWm(?L@?HxicC!=)>rJC)>V)OxK7#!+M<?k1rq!JYc4?xqYUv}=lnU5kyj%8?N^e3|;i1bIFUlk;&-Df|N6Ri1VzjS!oB_%|4=~YpjG;cP&pF7U*8MOQ1Ng77OTQbU1<1#i=ep787@UHXD@-ty#%}E@Dq{~_p%Bzk7vh0jD%eza$i3<01$tQk;y4jbpI3TP1jWW08<M3Q-oHABlXH?2E)Y0O^P-diDbU*b(AEcAmvB`wp8@s<7csy4$ir*tl6z}jB~D&Q%)&^NK_gK9FcI01aBmUd-{bXf07~*WxDjY15*zlV$fk|6qT;Jtx5SrHtR5}SrOWaM(rxw>k|Lcj%XOgZ-60|{gy<NThbXEkG{fkd=~OKHPhV^PbKJppa=-s_iH(S5nf(R5Kqbo')))

```

Try it online! Test suite (also executes brainfuck)
> 2 votes

---
Tags: code-golf, compiler
---


title: Simulate Bitwise Cyclic Tag

text:
# Question
Title: Simulate Bitwise Cyclic Tag
## Challenge

Given two strings in any default I/O format, do the following:

**NOTE: The challenge will refer to the first string as the "data" and the second referred to as the "program".**

1. Change the program to an infinite string which is just the program repeated infinitely (e.g. `10` --\> `1010101010...`). The challenge will refer to this as the "infinite program"
2. While the data is non-empty, do the following while looping over the infinite program:

a. If the current command is "0", delete the left-most bit in the data. If the data is empty, "0" does not do anything.

b. If the current command is "1", append the next character in the program to the data if the left-most bit in the data is a one.

c. If the data is not empty now, output the data.

## Test Cases

Data is the left side of the input and the program is the right side.

```
100, 0 --> 00, 0
1111, 1 --> 11111, 111111, 1111111, ...
10, 011 --> 0, 0, 0
1110, 011 --> 110, 1101, 11010, 1010...

```

## Notes

* The data and program will consist of only 0s and 1s
* For data/programs that do not halt, your program does not need to halt.
* The data and program will not be empty in the input.
* You may have multiple trailing and leading newlines
* Standard Loopholes are forbidden
* You can use any convenient I/O format

As always with , **shortest code wins**!

# Answer
> 4 votes
## Haskell, ~~77~~ ~~71~~ 62 bytes

```
f@(d:e)#(p:q)=f:[e,f++take d q]!!p#q
_#_=[]
a!b=tail$a#cycle b

```

Try it online!

Edit: -9 bytes thanks to @xnor.

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 82 bytes

```
m=>n=>{for(int i=0;m!="";Print(m=n[i++]<49?m.Substring(1):m[0]>48?m+n[i]:m))n+=n;}

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~24~~ 21 bytes

```
[¹Nèi¬i¹N>è«}ë¦}DõQ#=

```

Takes the program as first input and data as second input.input.

Try it online.

**Explanation:**

```
[             # Start an infinite loop:
 ¹Nè          #  Get the N'th digit of the first (program) input
              #  (NOTES: N is the index of the infinite loop;
              #          indexing in 05AB1E automatically wraps around)
    i         #  If this digit is 1:
     ¬        #   Push the head of the current data (without popping it)
              #   (will take the second (data) input implicitly if it's the first iteration)
      i     } #   If this head is 1:
       ¹N>è   #    Get the (N+1)'th digit of the first (program) input
           «  #    And append it to the current data
    ë }       #  Else (the digit is a 0 instead):
     ¦        #   Remove the first digit from the current data
              #   (will take the second input (data) implicitly if it's the first iteration)
 DõQ          #  If the current data is an empty string:
    #         #   Stop the infinite loop
 =            #  Print the current data with trailing newline (without popping it)

```

# Answer
> 2 votes
# Ruby, ~~62~~ 59 bytes

```
->c,d{p(d)while(a,*c=c;b,*d=d;c<<a;[]!=d=[b]*a+d+c[0,a*b])}

```

Try it online!

### How

* Get the first bit from code `c` and data `d`, call them `a` and `b`. Put `a` back at the end of `c`.
* Put back `b` at the beginning of `d` if `a==1`. This can be shortened to `[b]*a`
* Put the first byte of `c` at the end of `d` if `a==1 and b==1`. This can be shortened to `c[0,a*b]`.
* If we have more data, print and repeat.

# Answer
> 1 votes
# , 65 bytes

```
(([:(][echo)(}.@[)`([,{.@[#1{],])@.({.@]));1|.])&>/^:(0<0#@{>)^:5

```

Try it online!

I may golf this further later. Note the `5` at the end would be infinity `_` in the actual program, but I've left it there to make running the non-halting examples easier.

# Answer
> 1 votes
# Python 3, 74 bytes

```
def f(d,p):
 while d:c,*p=p+p[:1];d=(d[1:],d+p[:1]*d[0])[c];d and print(d)

```

Try it online!

Arguments: `d`: data, `p`: program.

# Answer
> 1 votes
# C++ (gcc), 178 bytes

```
void a(std::string s,std::string d){while(!s.empty())for(int i=0;i<d.size();i++){if(d[i]=='0')s.erase(0,1);else if(s[0]=='1')s.push_back(d[(i+1)>=d.size()?0:i+1]);std::cout<<s;}}

```

Try it online!

# Answer
> 0 votes
# Python 1, 75 bytes

```
a,b=input()
while a:b=b[1:]+b[:1];a=[a[1:],a+b[:1]*a[0]][b[0]];print a or''

```

Try it online!

# Answer
> 0 votes
# Python 2, ~~96~~ 82 bytes

```
def g(d,p):
 while d:
	c=p[0];p=p[1:]+[c];d=[d[1:],d+[p[0]]*d[0]][c]
	if d:yield d

```

Try it online!

Stealing a bit from Emodiment of Ignorance's answer...

A generator which uses lists of 1's and 0's for input / output.

# Answer
> 0 votes
# Jelly, 40 bytes

```
;€Ø2œịxØ1œị$Ʋ$Ḋ€2,1œị$?1¦ṙ€1$2¦µ⁺1ịGṄƲ¿Ḣ

```

Try it online!

I’ve assumed trailing newlines are ok. I’ve also gone with a list of two lists of zeros and ones as input, and output to stdout.

# Answer
> 0 votes
# C++ (gcc), ~~294~~ ~~289~~ 272 bytes

-22 bytes thanks to @ceilingcat

```
#import<cstdio>
#import<queue>
void a(char*e,char*p){std::queue<char>d;for(;*e;)d.push(*e++);for(char*c=p;d.size();c=*++c?c:p){*c-49?d.pop():d.front()-48?d.push(c[1]?c[1]:*p):a("","");if(d.size()){for(int i=0;i++<d.size();d.pop())d.push(putchar(d.front()));putchar(32);}}}

```

Try it online!

Fairly straightforward algorithm. Copies the data into a queue, and repeatedly loops through the program. On a "0", it removes the first element in the queue (the first "bit"). On a 1, it adds the next "bit" of the program to the data if the first "bit" of the data is 1. Then it loops through the data, printing it "bit" by "bit", and finally prints a space to separate successive data entries.

---
Tags: code-golf, interpreter
---


title: An Séimhiú agus an tUrú

text:
# Question
Title: An Séimhiú agus an tUrú
# An Séimhiú agus an tUrú

In Irish Gaelic (Gaeilge) there are a number of ways that the start of a word can be changed. The most common of these are lenition (an séimhiú) and eclipsis (an t-urú)

Lenition involves adding the letter *h* as the second letter. For example, the word "bean" (woman) would be lenited to "bhean".

Eclipsing adds a prefix to the word. The prefix is determined by the first letter of the word. For example, the word "capall" (horse) starts with a *c*. Its eclipsis is *g*. So when the word "capall" is eclipsed it becomes "gcapall".

## Challenge

Write a function or program that takes a word and returns both its lenited and eclipsed forms.

### Lenition

Only words beginning with:

```
b
c
d
f
g
m
p
s
t

```

are lenited. Words beginning with other letters are not changed.

**Some examples:**

```
bean       bhean
capall     chapall
Sasana     Shasana
lón        lón
Ífreann    Ífreann

```

### Eclipsis

If a word starts with any of the following letters, it is prefixed by its respective eclipsis:

```
Letter   Eclipsis
b        m
c        g
d        n
f        bh
g        n
p        b
t        d

```

Words that don't start with those letters remain unchanged.

**Examples:**

```
bean        mbean
capall      gcapall
cailín      gcailín
doras       ndoras
fuinneog    bhfuinneog
Gaeilge     nGaeilge
Sasana      Sasana

```

There are other changes that can happen to the start of a word, but we'll just focus on these ones.

## Rules

The input is only one word. Words will only contain `a-z`, `A-Z` or the *fada* vowels `á`, `Á`, `é`, `É`, `í`, `Í`, `ó`, `Ó`, `ú` and `Ú`.

To make it a bit more simple the word itself doesn't necessarily need to be an Irish word, just that it is treated like one in the code. So inputting `delta` should return `dhelta` and `ndelta`.

For this challenge you can assume that the input words have not already been lenited or eclipsed (in Irish, a word is only lenited or eclipsed once. You would never end up with "bhhean" or "ngcapall").

Standard rules apply, including the default I/O rules. Similarly, default loopholes are forbidden.

Finally, this is so shortest answer in bytes wins.

## Test cases

```
Input      Lenited     Eclipsed
bean       bhean       mbean
capall     chapall     gcapall
fuinneog   fhuinneog   bhfuinneog
Sasana     Shasana     Sasana
Gaeilge    Ghaeilge    nGaeilge
lón        lón         lón
áthas      áthas       áthas
Ífreann    Ífreann     Ífreann

```

# Answer
> 2 votes
# JavaScript (ES6),  ~~98~~  97 bytes

Returns an array `[lenited, eclipsed]`.

```
s=>[(x=[...'2n1111gbnd1m1','bh',2][parseInt(c=s[0],30)*17%22])>'1'?c+'h'+s.slice(1):s,x>{}?x+s:s]

```

Try it online!

### How?

We define the following lookup table:

```
A = [ ...'2n1111gbnd1m1', 'bh', 2 ]

//     0    1    2    3    4    5    6    7    8    9    10   11   12   13  14
A = [ '2', 'n', '1', '1', '1', '1', 'g', 'b', 'n', 'd', '1', 'm', '1', 'bh', 2 ]

```

where:

* a single character (or the string *"bh"*) is used for eclipsis; all letters that trigger eclipsis also trigger lenition
* \\$1\\$ means that there's no eclipsis and no lenition
* \\$2\\$ means that there's no eclipsis but there is lenition

The first letter of the input word is converted from Base30 to decimal, multiplied by \\$17\\$ and then reduced with a modulo \\$22\\$. The result is used to pick the correct value from \\$A\\$.

Any result above \\$14\\$ yields *undefined*, and so does any letter in the range **u-z** or any fada vowel. An undefined value is interpreted the same way as \\$1\\$ (no eclipsis, no lenition).

```
  1st letter | from Base30 | * 17 | mod 22 | A[n]
-------------+-------------+------+--------+-----------
      a      |      10     |  170 |   16   | undefined
      b      |      11     |  187 |   11   | 'm'
      c      |      12     |  204 |    6   | 'g'
      d      |      13     |  221 |    1   | 'n'
      e      |      14     |  238 |   18   | undefined
      f      |      15     |  255 |   13   | 'bh'
      g      |      16     |  272 |    8   | 'n'
      h      |      17     |  289 |    3   | '1'
      i      |      18     |  306 |   20   | undefined
      j      |      19     |  323 |   15   | undefined
      k      |      20     |  340 |   10   | '1'
      l      |      21     |  357 |    5   | '1'
      m      |      22     |  374 |    0   | '2'
      n      |      23     |  391 |   17   | undefined
      o      |      24     |  408 |   12   | '1'
      p      |      25     |  425 |    7   | 'b'
      q      |      26     |  442 |    2   | '1'
      r      |      27     |  459 |   19   | undefined
      s      |      28     |  476 |   14   | 2
      t      |      29     |  493 |    9   | 'd'
 u-z or fada |     NaN     |  NaN |  NaN   | undefined

```

# Answer
> 2 votes
# Perl 6, ~~83~~ 77 bytes

*-6 bytes thanks to Jo King*

```
{S:i/^<[bcdfgmpst]>/$/h/,{S/0/bh/}({$_ x tr/dbcfptg/nmg0bd/}($= m/./.lc))~$_}

```

Try it online!

Returns a two-element list.

# Answer
> 2 votes
# 05AB1E, ~~45~~ 44 bytes

```
.•1˜3WÓƵ•sнlk©diн'hI¦JI®7‹i.•B}в •S„bhš®èì]‚

```

Ended up longer than I anticipated beforehand.. Can probably be golfed some more, though.

Try it online or verify all test cases.

**Explanation:**

```
.•1˜3WÓƵ•                   # Push compressed string "fbcdgptms"
s                           # Swap to take the (implicit) input-string
 н                          # Get its first character
  l                         # Convert it to lowercase
   k                        # Get the index in the string (-1 if not found)
    ©                       # Store it in the register (without popping)
     di                     # If the index is non-negative (>= 0):
       н                    #  Get the first character of the (implicit) input-string again
        'h                 '#  Push a "h"
          I                 #  Push the input
           ¦                #  And remove its first character
            J               #  Join all three strings together
       I                    #  Then push the input-string again
        ®7‹i                #  If the index from the register is smaller than 7:
            .•B}в •         #   Push compressed string "mgnnbd"
                   S        #   As a list of characters: ["m","g","n","n","b","d"]
                    „bhš    #   And prepend "bh" to this list: ["bh","m","g","n","n","b","d"]
                        ®è  #   Then use the index from the register in this list
                          ì #   And prepend it in front of the input-string
      ]                     # Close both if-statements
       ‚                    # Pair the two strings at the top of the stack
                            # (uses the input implicitly if we haven't entered the first if)
                            # (and output this pair of strings implicitly)

```

See this 05AB1E tips of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•1˜3WÓƵ•` is `"fbcdgptms"` and `.•B}в •` is `"mgnnbd"`.

Alternative for `.•B}в •S„bhš` with the same byte-count can be `.•„Å'ÀāÊˆÑ•#`, where `.•„Å'ÀāÊˆÑ•` is the compressed string `"bh m g n n b d"` and `#` will split on spaces.

# Answer
> 2 votes
# Python 3, 100 bytes

```
lambda w,l='bBcCdDgGpPtTfF':(w[0]+'h'*(w[0]in'msMS'+l)+w[1:],[*'mgnnbd','bh',''][l.find(w[0])//2]+w)

```

Try it online!

-3 thanks to Black Owl Kai.

# Answer
> 1 votes
# Stax, 41 bytes

```
ü≤↔y╩▓╤:ï{╪Θ↨ë24¿→Äw↔t⌠íΘq↕:pWhg2╗P♦_}éBb

```

Run and debug it

# Answer
> 1 votes
# PowerShell, 121 122 116 98 Bytes

-24 bytes thanks to @mazzy

```
param($a)$a-replace'^[bcdfgmpst]','$&h';@{b='m';c='g';d='n';g='n';f='bh';p='b';t='d'}[''+$a[0]]+$a

```

Try it online!

Uses a simple regex for the lenition and a switch statement far superior hashtable thanks to @mazzy for the eclipsis. This can probably get a lot shorter.

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 151 bytes

```
x=>{var p=(char)(x[0]%32+96);return(x.Insert(1,(a+"ms").Contains(p)?"h":""),p==102?"bh"+x:"mgnnbd "[a.IndexOf(p)<0?6:a.IndexOf(p)]+x);};var a="bcdgpt";

```

It's really long, and there are probably ways to golf it more. But I'm just too lazy.

Try it online!

# Answer
> 1 votes
# Java 10, ~~140~~ 135 bytes

```
s->{var h=s.charAt(0);int i="fbcdgptms".indexOf(h|32);return(i<0?s:h+"h"+s.substring(1))+" "+",bh,m,g,n,n,b,d,,".split(",",10)[i+1]+s;}

```

Port of my 05AB1E answer.
-5 bytes thanks to *@OlivierGrégoire*.

Try it online.

**Explanation:**

```
s->{                              // Method with String as both parameter and return-type
  var h=s.charAt(0);              //  Get the first character of the input
  int i="fbcdgptms".indexOf(h     //  Get its index in the string "fbcdgptms"
                            |32); //  After converting it to lowercase
  return(i<0?                     //  If the index is -1 (not found):
          s                       //   Return the input unchanged
         :                        //  Else:
          h                       //   Return the first character
          +"h"                    //   Appended with an "h"
          +s.substring(1))        //   Appended with the rest of the string
         +" "                     //  Then append a space delimiter
         +",bh,m,g,n,n,b,d,,".split(",",10)
                                  //  Push {"","bh","m","g","n","n","b","d","",""}
          [i+1]                   //  and append the character at index `i+1`
         +s;}                     //  And append the input-string

```

# Answer
> 1 votes
# C# (.NET Core), ~~165~~, ~~131~~, 126 bytes

Edit: ASCII-only with -34 bytes. Puts everything into one string.

Edit2: Kevin Cruijssen with the 5 byte golf to ToUpper()!

```
p=>{var s="BCDFGMPSTMGN N B D";var k=s.IndexOf(p.ToUpper()[0]);return(p.Insert(1,k<0?"":"h"),k<0?p:s[k]==70?"bh"+p:s[k+9]+p);}

```

Try it online!

# Answer
> 1 votes
# Perl 6, 101 bytes

```
{.subst(/:i ^<[bcdfgmpst]>/,{$_~'h'}),.subst(/^./,{(%(<b m c g d n f bh g n p b t d>){.lc}//'')~$_})}

```

Try it online!

# Answer
> 0 votes
# Python 3, 118 bytes

```
s='fbcdgpt'
def f(w):a=w[0].lower();return w[0]+'h'*(a in'ms'+s)+w[1:],dict(zip(s,'bmgnnbd')).get(a,'')+'h'*(a=='f')+w

```

Try it online!

# Answer
> 0 votes
# Retina 0.8.2, 77 bytes

```
i`^[bcdfgmpst]
$&h$'¶$&$&
T`L`l`¶.
¶f
¶ph
T`\ptcb\dgms`b\dgmnn_`¶.
^.+$
$&¶$&

```

Try it online! Link includes test cases. Explanation:

```
i`^[bcdfgmpst]
$&h$'¶$&$&

```

If the word can be lenited, create the lenition, and make a copy for the eclipsis with a duplicate first letter.

```
T`L`l`¶.

```

Lowercase the duplicate letter.

```
¶f
¶ph

```

If it's an `f` then change it to `ph`; it will get fixed to `bh` later.

```
T`\ptcb\dgms`b\dgmnn_`¶.

```

Fix or remove the eclipsis (`m` and `s` have a lentition but no eclipsis).

```
^.+$
$&¶$&

```

If there was no lentition then duplicate the word anyway.

# Answer
> 0 votes
### **JAVASCRIPT 131 bytes**

Implementing Kevin Cruijssen answer in javaScript:

```
(w,i='bcdfgmpst'.indexOf(w.toLowerCase()[0]))=>(i>=0?[w,w[0]+'h'+w.substr(1),'m,g,n,bh,n,,b,,d'.split(',')[i]+w]:[w,w,w]).join(' ')

```

```
(
 w,                                                          // the input (string)
 i='bcdfgmpst'.indexOf(w.toLowerCase()[0])                   // the index of the lenited word
)=>(
i>=0?                                                        // if index greater or equals 0
 [w,w[0]+'h'+w.substr(1),'m,g,n,bh,n,,b,,d'.split(',')[i]+w] // return Array(input, lenited, eclipsis)
:                                                            // else
 [w,w,w]                                                     // return Array(input, input, input)
).join(' ')                                                  //Join array items with spaces

```

---
Tags: code-golf, natural-language
---


title: How long is a Welsh word?

text:
# Question
Title: How long is a Welsh word?
Write a program or function which receives as input a string representing a Welsh word (UTF-8 unless otherwise specified by you).

The following are all *single letters* in Welsh:

> a, b, c, ch, d, dd, e, f, ff, g, ng, h, i, j, l, ll, m, n, o, p, ph, r, rh, s, t, th, u, w, y

To quote Wikipedia,

> While the digraphs *ch*, *dd*, *ff*, *ng*, *ll*, *ph*, *rh*, *th* are each written with two symbols, they are all considered to be single letters. This means, for example that Llanelli (a town in South Wales) is considered to have only six letters in Welsh, compared to eight letters in English.

These letters also exist in Welsh, though they are restricted to technical vocabulary borrowed from other languages:

> k, q, v, x, z

Letters with diacritics are not regarded as separate letters, but your function must accept them and be able to count them. Possible such letters are:

> â, ê, î, ô, û, ŷ, ŵ, á, é, í, ó, ú, ý, ẃ, ä, ë, ï, ö, ü, ÿ, ẅ, à, è, ì, ò, ù, ẁ

(This means that ASCII is not an acceptable input encoding, as it cannot encode these characters.)

### Notes:

* This is code golf.
* You do not have to account for words like *llongyfarch*, in which the *ng* is not a digraph, but two separate letters. This word has nine letters, but you can miscount it as eight. (If you *can* account for such words, that's kind of awesome, but outside the scope of this challenge.)
* The input is guaranteed to have no whitespace (unless you prefer it with a single trailing newline (or something more esoteric), in which case that can be provided). There will certainly be no internal whitespace.

### Test cases:

* Llandudno, 8
* Llanelli, 6
* Rhyl, 3
* Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch, 50 (really 51, but we'll count 50)
* Tŷr, 3
* Cymru, 5
* Glyndŵr, 7

# Answer
> 7 votes
# 05AB1E, ~~24~~ ~~23~~ 21 bytes

Code:

```
u•éÓœ°D¥M™ù>•30B2ô0:g

```

Explanation:

```
u                      # Convert the input to uppercase.
 •éÓœ°D¥M™ù>•30B       # Compressed version of CHDDFFNGLLPHRHTH.
                         It convert the text between the •'s from base 214 to
                         base 10 and converts that to base 30.
                2ô     # Split into pieces of 2.
                  0:   # Replace each element that also occurs in the input by 0.
                    g  # Get the length of the processed input.

```

Uses the **CP-1252** encoding. Try it online!

# Answer
> 16 votes
# Retina, 23 bytes

```
i`[cprt]h|dd|ff|ng|ll|.

```

Try it online!

Even moar regex.

# Answer
> 5 votes
# JavaScript (ES6), 44 bytes

```
x=>x.match(/[cprt]h|dd|ff|ng|ll|./gi).length

```

The trivial answer may be the shortest.

# Answer
> 5 votes
# BASH 52 50 (sed + wc) 41

-9 thanks to Jordan

```
sed -r 's,dd|ff|ng|ll|[cprt]h,1,gi'|wc -m

```

If uppercase letter are required this needs an `i` at the end of the sed command. (I left it out because all of the "single letters" in the question are lowercase even though some examples aren't).

# Answer
> 4 votes
## Straw, ~~30~~ ~~58~~ ~~35~~ 33 bytes

```
<((?i:[cprt]h|dd|ff|ng|ll|.))0/$>

```

Replace each occurence of the regex by `0`, and convert from unary to decimal.

~~Sadly, Straw can't pass flags to regexs.~~ I forget about the `?flags:` construct

Try it online! (The added code is to verify all test cases)

# Answer
> 3 votes
# Python 3, 64 bytes

```
import re
print(len(re.findall("[cprt]h|dd|ff|ng|ll|.",input())))

```

Uses regex again

**Ideone it!**

# Answer
> 3 votes
## PowerShell v2+, ~~52~~ ~~50~~ 48 bytes

```
($args[0]-replace'dd|ff|ng|ll|[prtc]h',0).length

```

Does a `-replace` on all the two-symbol-single-letter letters, changes 'em to `0` (done because changing to a non-numeral would require quotes), then gets the `.length` of the resultant string.

### Test cases

```
PS C:\Tools\Scripts\golfing> 'Llandudno','Llanelli','Rhyl','Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch','Tŷr','Cymru','Glyndŵr'|%{"$_ --> "+(.\how-long-is-a-welsh-word.ps1 $_)}
Llandudno --> 8
Llanelli --> 6
Rhyl --> 3
Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch --> 50
Tŷr --> 3
Cymru --> 5
Glyndŵr --> 7

```

# Answer
> 2 votes
# , 31 bytes

```
Íã[cprt]hüddüffüngüllü./
Dé0@"

```

Try it online, or Verify all test cases!

This contains some unprintable characters, so here is a hexdump:

```
0000000: cde3 5b63 7072 745d 68fc 6464 fc66 66fc  ..[cprt]h.dd.ff.
0000010: 6e67 fc6c 6cfc 2e2f 010a 44e9 3040 22    ng.ll../..D.0@"

```

# Answer
> 2 votes
# PHP , 56 Bytes

```
<?=preg_match_all("#[cprt]h|dd|ff|ll|ng|.#iu",$argv[1]);

```

# Answer
> 1 votes
# Java 7, ~~156~~ 73 bytes

Loads of bytes saved thanks to *@OlivierGrégoire*.

```
int c(String s){return s.replaceAll("[cprt]h|dd|ff|ng|ll","*").length();}

```

**Ungolfed & test cases:**

Try it here.

```
class M{
  static int c(String s){
    return s.replaceAll("[cprt]h|dd|ff|ng|ll", "*").length();
  }

  public static void main(String[] a){
    System.out.println(c("llandudno"));
    System.out.println(c("llanelli"));
    System.out.println(c("rhyl"));
    System.out.println(c("llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch"));
    System.out.println(c("tŷr"));
    System.out.println(c("cymru"));
    System.out.println(c("glyndŵr"));
  }
}

```

**Output:**

```
8
6
3
50
3
5
7

```

# Answer
> 1 votes
## R, 54 bytes

Very similar to the other answers. Matches any of the two character letters and replaces them with `@` and subsequently counts the number of characters. Reads input from stdin. Uses the option `ignore.case = TRUE` (third argument to `gsub`) to match both upper and lowercase characters.

```
nchar(gsub("ch|dd|ff|ng|ll|ph|rh|th","@",scan(,""),T))

```

**Bonus**

Both `gsub` and `nchar` are vectorized which means that this also works on a character vector, e.g.:

```
v=c("Llandudno","Llanelli","Rhyl","Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch","Tŷr","Cymru","Glyndŵr")
nchar(gsub("ch|dd|ff|ng|ll|ph|rh|th","@",v,T))

```

produces:

```
[1]  8  6  3 50  3  5  7

```

# Answer
> 1 votes
# Perl 6, 36 bytes

```
+*.comb(/:i.|<[cprt]>h|dd|ff|ng|ll/)

```

Try it online!

# Answer
> 0 votes
# XQuery, 77 bytes

```
declare variable$s external;count(tokenize($s,'[cprt]h|ff|dd|ll|ng|.','i'))-1

```

# Answer
> 0 votes
# tcl, 71

```
proc L s {string le [regsub -all -nocase ch|dd|ff|ng|ll|ph|rh|th $s @]}

```

# demo

# Answer
> 0 votes
# Perl 5, 35 + 1 (`-p`) = 36 bytes

```
s/[cprt]h|dd|ff|ng|ll/a/gi;$_=y///c

```

Try it online!

---
Tags: code-golf, string, counting, natural-language
---


title: Golff y Côd - Treiglad

text:
# Question
Title: Golff y Côd - Treiglad
***Read this yng Nghymraeg***

## Challenge

Given a word in Welsh, output all of the possible mutated forms of the word.

## Mutations

A mutation is a change of the first letter of a word when following certain words or in certain grammatical contexts.

In Welsh, the following are considered "consonants":

```
b c ch d dd f ff g ng h l ll m n p ph r rh s t th

```

Note that multiple character consonants such as ch, ng and rh are counted as *one letter* in Welsh, and therefore one consonant.

The other letters in the Welsh alphabet are vowels, listed below:

```
a e i o u w y

```

See below, all of the mutations with the original letter on the left and the resulting mutated letters on the right:

```
Original | Mutations
---------+---------------
p        | b mh ph
t        | d nh th
c        | g ngh ch
b        | f m
d        | dd n
g        | [no letter] ng
m        | f
ll       | l
rh       | r

```

Here, `[no letter]` means that the g is removed from the start of the word.

Note that there are some consonants which do not mutate:

```
ch
dd
f
ff
j
l
n
ng
ph
r
s
th

```

Vowels may also be found at the start of words but do not mutate:

```
a
e
i
o
u
w
y

```

## Examples

**Input:** `dydd`

**Output:**

```
dydd
ddydd
nydd

```

---

**Input:** `pobl`

**Output:**

```
pobl
bobl
mhobl
phobl

```

---

**Input:** `gwernymynydd`

**Output:**

```
gwernymynydd
wernymynydd
ngwernymynydd

```

---

**Input:** `ffrindiau`

**Output:**

```
ffrindiau

```

---

**Input:** `enw`

**Output:**

```
enw

```

---

**Input:** `theatr`

**Output:**

```
theatr

```

---

<sub>*On the request of ArtOfCode ;)*</sub>

**Input:** `llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch`

**Output:**

```
llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch
lanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch

```

## Rules

The input will only ever be one word.

There will always be more letters after the leading consonant in your input.

## Winning

The shortest code in bytes wins.

# Answer
# JavaScript (ES6), 180 bytes

```
x=>x.replace(/^([cpt](?!h)|d(?!d)|[bgm]|ll|rh)(.+)/,(_,y,z)=>({p:"b mh ph",t:"d nh th",c:"g ngh ch",b:"f m",d:"dd n",g:" ng",m:"f"}[y]||y[0]).split` `.map(b=>a.push(b+z)),a=[x])&&a

```

Outputs as an array of strings. This is my first try, so it's almost certainly not optimal.

### Try it out

```
f=x=>x.replace(/^([cpt](?!h)|d(?!d)|[bgm]|ll|rh)(.+)/,(_,y,z)=>({p:"b mh ph",t:"d nh th",c:"g ngh ch",b:"f m",d:"dd n",g:" ng",m:"f"}[y]||y[0]).split` `.map(b=>a.push(b+z)),a=[x])&&a
```

```
<input id=A value="pobl"><button onclick="B.innerHTML=f(A.value).join('<br>')">Run</button><br>
<pre id=B>
```
> 5 votes

# Answer
## C#, 356 ~~338~~ ~~360~~ bytes

I know that C# is a poor choice for code golf, but it's worth the shot:

Third attempt, all cases now pass, including th- ph- etc. This adjustment cost roughly 18 bytes.

Thanks pinkfloydx33 for the tips saving 24 bytes!

```
namespace System{using Linq;using S=String;class P{static void Main(S[]a){Action<S>w=Console.WriteLine;w(a[0]);foreach(S r in"th-dd-ch-ph-p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r".Split('-')){var b=r.Split('.');if(a[0].StartsWith(b[0])){foreach(S f in b.Skip(1))w(Text.RegularExpressions.Regex.Replace(a[0],$"^{b[0]}",f));break;}}}}}

```

## Output

```
$> ./p gwernymynydd
gwernymynydd
wernymynydd
ngwernymynydd

```

## Formatted Version

```
    namespace System {
    using Linq;
    using S = String;

    class P {
        static void Main(S[] a) {
            Action<S> w = Console.WriteLine;
            w(a[0]);
            foreach (S r in "th-dd-ch-ph-p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r"
                .Split('-')) {
                var b = r.Split('.');
                if (a[0].StartsWith(b[0])) {
                    foreach (S f in b.Skip(1))
                        w(Text.RegularExpressions.Regex.Replace(a[0], $"^{b[0]}", f));
                    break;
                }
            }
        }
    }
}

```
> 4 votes

# Answer
## PowerShell v3+, ~~254~~ 231 bytes

```
param($a)$a;$z=-join$a[1..$a.length]
if(($x=@{112='b mh ph';116='d nh th';99='g ngh ch';98='f m';100='dd n';109='f'})[+$a[0]]-and$a-notmatch'^[cpt]h|^dd'){-split$x[+$a[0]]|%{"$_$z"}}
($z,"ng$z")*($a[0]-eq103)
$z*($a-match'^ll|^rh')

```

working to golf further...

### Examples

(Output is space-separated because that's the default Output Field Separator for stringified arrays. I don't know if the words I used for testing are actual words, but they fit the exceptions.)

```
PS C:\Tools\Scripts\golfing> 'dydd','pobl','gwernymynydd','ffrindiau','enw','rhee','llewyn','chern','ddydd','phobl'|%{"$_ --> "+(.\golff-yr-cod.ps1 $_)}
dydd --> dydd ddydd nydd
pobl --> pobl bobl mhobl phobl
gwernymynydd --> gwernymynydd wernymynydd ngwernymynydd
ffrindiau --> ffrindiau
enw --> enw
rhee --> rhee hee
llewyn --> llewyn lewyn
chern --> chern
ddydd --> ddydd
phobl --> phobl

```
> 3 votes

# Answer
## Python 3, ~~196,189~~ 185 bytes

Original attempt

```
w=input();print(w);[w.startswith(a)and[print(w.replace(a,i,1))for i in
r]+exit()for(a,*r)in(j.split(',')for j
in'th rh ph p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())]

```

Vaultah noted that `not w.find(a)` would be a replacement for `w.startswith(a)` that would save 2 characters. But instead of `not x and y` we can use `x or y` which saves some characters more:

```
w=input();print(w);[w.find(a)or[print(w.replace(a,i,1))for i in
r]+exit()for(a,*r)in(j.split(',')for j
in'th rh ph p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())]

```

Yet further savings by replacing `w.replace(a,i,1)` with `i+w[len(a):]`:

```
w=input();print(w);[w.find(a)or[print(i+w[len(a):])for i in
r]+exit()for(a,*r)in(j.split(',')for j
in'th rh ph p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())]

```

Then I noticed that there was a bug, `rh` was listed twice; once in my short-circuit list that would take care of those double-letter consonants. Unfortunately `dd` was missing from there, so no savings, and we have

```
w=input();print(w);[w.find(a)or[print(i+w[len(a):])for i in
r]+exit()for(a,*r)in(j.split(',')for j
in'th ph dd p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())]

```

Given any of the sample inputs, it gives the desired output; given

```
gorsaf

```

it outputs

```
gorsaf
orsaf
ngorsaf

```

and given input

```
theatr

```

it prints

```
theatr

```
> 3 votes

# Answer
## C#, 349 bytes

Based on @grizzly's submission, but corrected to work with the consonants that don't get transformed (ph/ch/th/dd) that it wasn't working with, plus trimmed some excess out. Hope that's alright?

I had it down to 290 until I realized that I was missing the th/ch/ph/dd cases :-(. Adding in the Regex call killed it

```
namespace System{class P{static void Main(string[]a){var x=a[0];if(!Text.RegularExpressions.Regex.IsMatch(x,"^[pct]h|^dd"))foreach(var r in"p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r".Split('-')){var b=r.Split('.');if(a[0].StartsWith(b[0]))for(int i=1;i<b.Length;)x+='\n'+b[i++]+a[0].Substring(b[0].Length);}Console.Write(x);}}}

```

Interesting note, never knew that you could omit the space between `var r in"string"`

Formatted:

```
namespace System
{
    class P
    {
        static void Main(string[] a)
        {
            var x = a[0];
            if (!Text.RegularExpressions.Regex.IsMatch(x, "^[pct]h|^dd"))
                foreach (var r in"p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r".Split('-'))
                {
                    var b = r.Split('.');
                    if (a[0].StartsWith(b[0]))
                        for (int i = 1; i < b.Length;) x += '\n' + b[i++] + a[0].Substring(b[0].Length);
                }
            Console.Write(x);
        }
    }
}

```
> 1 votes

# Answer
# Perl 6, 162 bytes

```
{/^(.|<[cprt]>h|dd|ff|ng|ll)(.*)/;(%('p',<b mh ph>,'t',<d nh th>,'c',<g ngh ch>,'b',<f m>,'d',<dd n>,'g',«'' ng»,'m',<f>,'ll',<l>,'rh',<r>){$0}//~$0).map(*~$1)}

```

Try it online!
> 0 votes

---
Tags: code-golf, string, natural-language
---