title: Counting fading

text:
# Question
Title: Counting fading
### Background

Being in a philosophical mood, I remembered one old idea. I think it is suitable for CG. Duplicates are not found, but it's of course just a kind of totalistic cellular automaton or erosion.

Given an infinite board filled with empty (let `0`) cells. We create *a figure* \- a finite set of non-empty (let `1`) cells. Figure may be with holes, disconnected, random etc. But the bounding box of the figure is finite.

We call *the border* of a figure a subset of its cells that have at least one empty neighbor (in this model we use *4 neighbors*: top, left, right, bottom).

Example of border (blue):

One step of fading algorithm:

1. Define a figure boundary
2. Eliminate it, replacing by empty cells

Example of fading step:

### Task:

Determine how many described steps it takes to completely disappear a given figure.

### About size of board

Since the figure can only fade, we just have to deal with the board, just one strip padding figure' bounding box.
**UPD - About minimal input**
So strictly speaking the minimal board is `[[0, 0], [0, 0]]` \- empty board with no figure. And as mentioned in comments, you may not handling an empty array; sorry that made that point clear just now.

### Input:

Figure in any appropriate form:

* binary array (all board)
* array of strings (too)
* sparse array (list of positions of non-empty cells and dimensions)

### Output:

Non-negative number of steps, totally eliminating a figure.

### Notes:

Of course, the literal passage of the algorithm to fixed point and counting steps is an acceptable solution. But I've got at least two addition ideas:

* Some built-ins of Mathematica ;) But I can't configure it properly (
* Perhaps one can analyze the maximum distances to the border, and get the answer only by a given array

### Test cases:

```
[[0, 0], [0, 0]] → 0

[[0, 0 ,0], [0, 1, 0], [0, 0, 0]] → 1

[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0],
 [0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0],
 [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
 [0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0],
 [0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] → 3

Example of string input:
00000000
01111110
01111110
01111110  → 3
01111110
01111110
01111110
00000000

Example of sparse array input (dimensions and non-empty cells):
[16, 16],
[[2, 2], [2, 3], [2, 4], [2, 13], [2, 14], [2, 15], [3, 2], [3, 3], [3, 4], [3, 5], [3, 8], [3, 9], [3, 10], [3, 12], [3, 13], [3, 14], [3, 15], [4, 2], [4, 3], [4, 4], [4, 5], [4, 8], [4, 9], [4, 10], [4, 12], [4, 13], [4, 14], [4, 15], [5, 3], [5, 4], [5, 5], [5, 8], [5, 9], [5, 10], [5, 12], [5, 13], [5, 14], [6, 8], [6, 9], [6, 10], [7, 7], [7, 8], [7, 9], [7, 10], [8, 7], [8, 8], [8, 9], [8, 10], [9, 7], [9, 8], [9, 9], [9, 10], [11, 2], [11, 3], [11, 4], [12, 2], [12, 3], [12, 4], [12, 5], [12, 6], [12, 7], [12, 8], [12, 9], [12, 10], [12, 11], [12, 12], [12, 13], [12, 14], [13, 2], [13, 3], [13, 4], [13, 5], [13, 6], [13, 7], [13, 8], [13, 9], [13, 10], [13, 11], [13, 12], [13, 13], [13, 14], [13, 15], [14, 3], [14, 4], [14, 5], [14, 6], [14, 7], [14, 8], [14, 9], [14, 10], [14, 11], [14, 12], [14, 13], [14, 14], [14, 15], [15, 13], [15, 14], [15, 15]] → 2

```

# Answer
# Python 2 or 3, 69 bytes

```
f=lambda c:c>[]and-~f([s for s in c if sum(1==abs(e-s)for e in c)>3])

```

A recursive function that accepts a list of positions on the Cartesian grid represented as complex numbers and returns the fading count. Returns `False` for zero as it quacks like zero in Python.

**Try it online!**
> 9 votes

# Answer
# MATLAB with Image Processing Toolbox, ~~45~~ 29 bytes

```
@(x)max(max(bwdist(~x,'ci')))

```

Anonymous function that inputs a matrix and outputs a number. **Try it online!** (with Octave).

### Explanation

The code

1. computes the Manhattan (city-block) distance between each value and the nearest zero (`bwdist(..., 'ci')` applied to `x` negated);
2. takes the maximum (`max`, used twice because the image has two dimensions).
> 9 votes

# Answer
# MATLAB with Image Processing toolbox, ~~59~~ 66 bytes

*+7 bytes from @Luis Mendo*

```
I={@(~)0,@(a)1+G(imerode(a,strel('dis',1)))}
G=@(a)I{2-~nnz(a)}(a)

```

Writing recursive code in MATLAB is surprisingly tricky; I'm using a workaround I found at this link to simulate an if-else statement inside of an anonymous function.
> 8 votes

# Answer
# Vyxal, 15 bytes

```
k□ẊṠ?Fv¨VεƛṠg;G

```

Try it Online!

Takes input as a list of coordinates.

Computes the taxicab distance of each point to the border and take the maximum.

```
k□ẊṠ?Fv¨VεƛṠg;G
k□              # push [[0,1],[1,0],[0,-1],[-1,0]]
  Ẋ             # cartesian product with input
   Ṡ            # vectorizing sum, this results in the shape inflated by one
    ?F          # remove all those that are in input, this results in the border of the shape
      v¨Vε      # vectorized and right vectorized absolute difference
          ƛ  ;  # map:
           Ṡ    #   vectorizing sum
            g   #   minimum
              G # maximum

```

### 15 byte alternative

```
ÞT?0ÞIv¨VεƛṠg;G

```

Takes input as a list of lists.
> 7 votes

# Answer
# MATL, 15 bytes

```
`t4&3ZItb-z}x@q

```

Inputs a binary matrix and outputs a number. **Try it online!**! Or **verify all test cases**.

### Explanation

The program erodes the image until it doesn't change.

```
`         % Do...while
  t       %   Takes input (implicitly) the first time. Duplicate. Call this (*)
  4&3ZI   %   Erode using 4-neighbourhood
  t       %   Duplicate
  b       %   Bubble up: moves (*) to the top of the stack
  -       %   Subtract, element-wise
  z       %   Number of non-zeros. Gives 0 if the last erosion didn't modify
          %   the image. Call this (**)
}         % Finally (this code is run on loop exit)
  x       %   Delete the image
  @       %   Push number of current iteration (which is the last one)
  q       %   Subtract 1
          % End (implicit). A new iteration will be run if the top of stack (**)
          % is not 0
          % Display stack (implicit)

```
> 7 votes

# Answer
# Julia 0.6, ~~62~~ 48 bytes

```
!m=any(m)&&1+!(conv2(1m,[0 1 0;1 1 1;0 1 0]).>4)

```

Try it online!

Performs erosion as 2D convolution with given 3x3 kernel.

14 bytes saved by MarcMush by switching to boolean inputs.
> 7 votes

# Answer
# Wolfram Language (Mathematica), ~~44~~ ~~42~~ 41 bytes

-1 not handling empty input

```
Max@#/. 1:>1+#0@Erosion[#,CrossMatrix@1]&

```

Try it online!

Input a binary array of `0`,`1`s.

I don't think there's a shorter way to generate `{{0,1,0},{1,1,1},{0,1,0}}`.
> 6 votes

# Answer
# Jelly,  ~~23~~  11 bytes

```
ạỊS=5ðƇ`ƬL’

```

A monadic Link that accepts a list of positions, as complex numbers, of non-empty cells and yields the fading count.

**Try it online!**

### How?

```
ạỊS=5ðƇ`ƬL’ - Link: list of coordinates, C
        Ƭ   - start with X=C and collect up while distinct applying:
       `    -   using X as both arguments of:
      Ƈ     -     filter keep those c in X for which:
     ð      -       the dyadic chain - f(c, X):
ạ           -         (c) absolute difference (X) (vectorises)
 Ị          -         insignificant? -- less than or equal to 1?
  S         -         sum -- number of neighbours + self
   =5       -         equals five?
         L  - length
          ’ - decrement -- as we've counted the empty list that then didn't change

```
> 5 votes

# Answer
# JavaScript (ES11), 88 bytes

Expects a binary matrix.

```
f=m=>m>(m=m.map((r,y)=>r.map((v,x)=>(g=d=>d+2?m[y+d--%2]?.[x+d%2]&g(d):v)(2))))?1+f(m):0

```

Attempt This Online!

### Commented

```
f =                      // f is a recursive function taking:
m =>                     //   m[] = input binary matrix
m > (                    // test whether m[] is lexicographically greater
  m =                    // than its updated version
  m.map((r, y) =>        // for each row r[] at index y in m[]:
    r.map((v, x) =>      //   for each value v at index x in r[]:
      ( g =              //     g is a helper recursive function taking
        d =>             //     a direction d in [-1 .. 2]
        d + 2 ?          //     if d is not equal to -2:
          m[y + d-- % 2] //       apply dy to y (decrement d afterwards)
          ?.[x + d % 2]  //       apply dx to x
          & g(d)         //       and do a recursive call
        :                //     else:
          v              //       stop and return v
      )(2)               //     initial call to g with d = 2
    )                    //   end of inner map()
  )                      // end of outer map()
) ?                      // if m[] was updated:
  1 +                    //   increment the final result
  f(m)                   //   and do a recursive call
:                        // else:
  0                      //   stop

```
> 5 votes

# Answer
# Retina 0.8.2, 89 bytes

```
s`1.*
$&_
}`(?<=(.)*)1(?=(.)*)(?=.*¶(?<-1>.)*(?(1)^)0|0|(?<=0(?(2)$)(?<-2>.)*¶.+|01))
0
_

```

Try it online! Takes input as an array of binary strings. Explanation: Loosely based on my original answer to Flood fill by distance.

```
s`1.*
$&_

```

If there are any `1`s remaining, then increase the iteration count.

```
(?<=(.)*)1(?=(.)*)

```

For each matching `1`, keeping track of its position, ...

```
(?=.*¶(?<-1>.)*(?(1)^)0|0|(?<=0(?(2)$)(?<-2>.)*¶.+|01))

```

...that is either above, to the left, below, or to the right of a `0`, using its captured position and .NET balancing groups in order to locate the relevant digit, ...

```
0

```

... erode one step.

```
}`

```

Repeat until there is nothing left to do.

```
_

```

Convert the final iteration count to decimal.
> 5 votes

# Answer
# Python3, 177 bytes:

```
E=enumerate
def f(b):
 b=[(x,y)for x,r in E(b)for y,v in E(r)if v]
 c=0
 while b:b=[(x,y)for x,y in b if all((x+X,y+Y)in b for X,Y in[(1,0),(0,1),(0,-1),(-1,0)])];c+=1
 return c

```

Try it online!
> 4 votes

# Answer
# Python script in Golly, 83 bytes

```
from golly import*
setrule("4/V")
i=0
while not empty():
 run(1)
 i+=1
show(str(i))

```

Takes input by drawing the figure in Golly.
> 4 votes

# Answer
# , 26 bytes

```
_1+[:#(#~4=1#.1=|@-/~)^:a:

```

Try it online!

* Takes input as complex numbers
* Create a distance table between each element and all the others
* For each row, count how many values equal exactly 1 (only true for compass adjacency)
* Remove any whose count is not 4 (ie, remove any non-interior elements)
* Continue this process until a fixed point, keeping a list of intermediate results
* Return the length of this list minus 1

## , alternate, 34 bytes

```
[:>./1<./"1@:#.]|@-"1/&($#:I.@,)-.

```

Try it online!

Input is a binary matrix.

We do a single calculation on the input, with no transforms, instead of iterating to simulate the fade:

1. Positions of all the ones
2. Positions of all the zeros
3. Manhattan distance between every element of each of those sets
4. Return the largest
> 4 votes

# Answer
# Excel (ms365), 122 bytes

Assuming:

* A range of cells as input;
* Cells contain either a 0 or a 1.

With Excel 365 one could create a named function which can call itself recursively. So let's create a function called 'z' which refers to:

```
=LAMBDA(x,y,IF(OR(x),z(MAKEARRAY(ROWS(x),COLUMNS(x),LAMBDA(r,c,AND(TOROW(INDEX(x,r-{1,0,0,-1},c-{0,1,-1,0}),3)))),y+1),y))

```

Now one could call this function through:

```
=z(<Range>,0)

```

Not sure if I was supposed to add the bytes to actually call the function.
> 4 votes

# Answer
# Charcoal, 29 bytes

```
Ｗ⊙θ⁼⊕⊗×ⅈ⊕ⅈＬΦθ¬›Σ↔Ｅμ⁻ξ§κπⅈＭ→Ｉⅈ

```

Try it online! Link is to verbose version of code. Takes input as a list of points. Explanation:

```
Ｗ⊙θ⁼⊕⊗×ⅈ⊕ⅈＬΦθ¬›Σ↔Ｅμ⁻ξ§κπⅈ

```

While there exists a point in the set with enough near (by taxicab distance) neighbours to survive another iteration, ...

```
Ｍ→

```

... increment the iteration count.

```
Ｉⅈ

```

Output the final iteration count.

30 bytes taking input as a list of newline-terminated strings:

```
ＷＳ⊞υιＩ⌈Ｅυ⌈Ｅι⌊Ｅυ⌊Ｅ⌕Ａν0⁺↔⁻πμ↔⁻ξκ

```

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

```
ＷＳ⊞υι

```

Input the strings.

```
Ｉ⌈Ｅυ⌈Ｅι⌊Ｅυ⌊Ｅ⌕Ａν0⁺↔⁻πμ↔⁻ξκ

```

Calculate the taxicab distance from each point to the nearest `0`, and output the maximum of those.
> 3 votes

# Answer
# 05AB1E, 28 bytes

```
Δ2Fø0δ.ø}2Fø€ü3}εεÅsyøÅs«ß]N

```

Input as a bit-matrix.

Try it online or verify all test cases.

**Explanation:**

```
Δ           # Loop until the result no longer changes, using the (implicit) input-matrix:
 2Fø0δ.ø}   #  Add a border of 0s around the matrix:
 2F     }   #   Loop 2 times:
   ø        #    Zip/transpose; swapping rows/columns
     δ      #    Map over each inner row-list:
    0 .ø    #     Surround it with both a leading and trailing 0
 2Fø€ü3}    #  Convert the matrix into overlapping 3x3 blocks:
 2F    }    #   Loop 2 times again:
   ø        #    Zip/transpose; swapping rows/columns
    €       #     Map over each inner list:
     ü3     #      Split it into triplets
 εεÅsyøÅs«ß #  Get the minimum of each cross of each 3x3 block:
 εε         #   Nested map over the 3x3 blocks:
   Ås       #    Get the middle row-list of the current block
   y        #    Push the 3x3 block again
    ø       #    Zip/transpose; swapping rows/columns
     Ås     #    Push its middle column-list of this transposed block
       «    #    Merge the middle row and column together to a single list
        ß   #    Pop and push its minimum
]           # Close the nested map and changes-loop
 N          # Push the last 0-based index of the changes-loop
            # (which is output implicitly as result)

```
> 1 votes

# Answer
# Pip `-x`, 29 bytes

```
YaWy&UiyFI:5={2>$+(aAD_)MSy}i

```

Takes input from the command-line as a string representing a Pip list of two-element lists, each of which represents the coordinates of a non-empty cell. Attempt This Online!

### Explanation

Port of Jonathan Allen's Jelly answer.

```
YaWy&UiyFI:5={2>$+(aAD_)MSy}i
Ya                            ; Yank the input into global variable y
  Wy                          ; Loop while y is not empty
    &Ui                       ; (and increment i on each loop):
       yFI:                   ;  Filter y by this function and assign back to y:
             {             }  ;   (Inside the function, the function argument is a)
                        MSy   ;   Map this function to y and sum the results:
                      _       ;    Each element of y (2-item list)
                   aAD        ;    Absolute difference (itemwise) with a
                $+(    )      ;    Add the two elements of the result
              2>              ;    1 if less than 2, 0 otherwise
                              ;   This gives the number of cells in cell a's 5-cell
                              ;   neighborhood (including the cell itself) that are
                              ;   nonempty
           5=                 ;   Return 1 if that fn's result is 5, 0 otherwise
                              ;  This filters and keeps only the nonempty cells
                              ;  that are surrounded by all nonempty cells
                            i ; After the loop, print the final value of i

```
> 1 votes

---
Tags: code-golf, array
---


title: Covfefify a string

text:
# Question
Title: Covfefify a string
In this challenge, you must take a string matching the regex `^[a-zA-Z]+$` or whatever is reasonable (you don't have to consider uppercase or lowercase letters if you want) (you may assume the string is long enough, and has the right structure for all the operations), and output another string, produced similarly to word at the end of a recent dadaist tweet by the POTUS (`"Despite the constant negative press covfefe"`).

## How to covfefify a string:

### First, get the first sound group (made up terminology).

How do you do this? Well:

* Find the first vowel (`y` is also a vowel)

```
  v
creation

```
* Find the first consonant after that

```
    v
creation

```
* Remove the rest of the string

```
creat

```

That is your first sound group.

### Next step:

Get the last consonant of the sound group

```
t

```

and replace it with the voiced or voiceless version. To do this, find the letter in this table. Replace with the letter given (which may be the same letter)

```
b: p
c: g
d: t
f: v
g: k
h: h
j: j
k: g
l: l
m: m
n: n
p: b
q: q
r: r
s: z
t: d
v: f
w: w
x: x
z: s

```

so, we get

```
d

```

Then, take the next vowel after that consonant. You can assume that this consonant is not at the end of the string. Join these two together, then repeat it twice:

```
didi

```

Concatenate this to the first sound group:

```
creatdidi

```

You're done: the string is covfefified, and you can now output it.

Test cases:

```
coverage: covfefe

example: exxaxa

programming: progkaka (the a is the first vowel after the g, even though it is not immediately after)
code: codtete

president: preszizi

```

This is , so please make your program as short as possible!

# Answer
# Jelly,  ~~58~~  57 bytes

```
<TḢị
e€Øyµ¬TĖEÐḟḢṪ;ç¥T
ḣÇḢ⁸ÇịµḢØYiị“ßȷ%Hẹrȧq’œ?ØY¤⁾cgy;ẋ2

```

A full program that accepts a list of lowercase characters and prints the result.

**Try it online!**

### How?

```
<TḢị - Link 1, extract first value from y not less than x: number, x; list of numbers, y
     -                                                     e.g. 5, [3,4,7]
<    - x less than vectorised across y                             [0,0,1]
 T   - truthy indices                                              [    3]
  Ḣ  - head                                                             3
   ị - index into y                                                     7

e€Øyµ¬TĖEÐḟḢṪ;ç¥T - Link 2, indices of the letters to manipulate: list of characters, w
  Øy              - vowel+ yield = "AEIOUYaeiouy"                 e.g.  "smouching"
e€                - exists in for €ach letter in w                       001100100
    µ             - monadic chain separation, call that v
     ¬            - not vectorised across v                              110011011
      T           - truthy indices                                       12  56 89
       Ė          - enumerate                      [[1,1],[2,2],[3,5],[4,6],[5,8],[6,9]]
         Ðḟ       - filter discard if:
        E         -   elements are equal                       [[3,5],[4,6],[5,8],[6,9]]
           Ḣ      - head                                        [3,5]
            Ṫ     - tail                                           5
                T - truthy indices of v                                    34  7
               ¥  - last 2 links as a dyad
              ç   -   call last link (1) as a dyad                         7
             ;    -   concatenate                                     5,7
                  -                                    ...i.e the indexes of 'c' and 'i'

ḣÇḢ⁸ÇịµḢØYiị“ßȷ%Hẹrȧq’œ?ØY¤⁾cgy;ẋ2 - Main link: list of characters, w
                                   -                             e.g.  "smouching"
 Ç                                 - call the last link (2) as a monad    [5,7]
ḣ                                  - head to index (vectorises)      ["smouc","smouchi"]
  Ḣ                                - head                             "smouc"
                                   -   implicit print due to below leading constant chain
   ⁸                               - link's left argument, w
    Ç                              - call the last link (2) as a monad    [5,7]
     ị                             - index into w                         "ci"
      µ                            - monadic chain separation, call that p
       Ḣ                           - head p                               'c'
        ØY                         - consonant- yield = "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz"
          i                        - first index                          22
                          ¤        - nilad followed by link(s) as a nilad:
            “ßȷ%Hẹrȧq’             -   base 250 number = 1349402632272870364
                        ØY         -   consonant- yield = "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz"
                      œ?           -   nth permutation  = "BCDFGHJKLMNPQRSTVWXZpctvkhjglmnbqrzdfwxs"
           ị                       - index into         (special case ->) 'c'
                           ⁾cg     - literal ['c','g']
                              y    - translate (change 'c's to 'g's)      'g'
                               ;   - concatenate with the headed p        "gi"
                                ẋ2 - repeat list twice                    "gigi"
                                   - implicit print ...along with earlier = smoucgigi

```
> 94 votes

# Answer
## JavaScript (ES6), ~~107~~ 103 bytes

*Saved 4 bytes thanks to GOTO 0*

```
s=>([,a,b,c]=s.match`(.*?[aeiouy]+(.)).*?([aeiouy])`,a+(b=(a="bcdfgszkvtgp")[11-a.search(b)]||b)+c+b+c)

```

### Test cases

```
let f =

s=>([,a,b,c]=s.match`(.*?[aeiouy]+(.)).*?([aeiouy])`,a+(b=(a="bcdfgszkvtgp")[11-a.search(b)]||b)+c+b+c)

console.log(f("creation"))
console.log(f("coverage"))
console.log(f("example"))
console.log(f("programming"))
console.log(f("president"))
```
> 65 votes

# Answer
# Jelly, ~~45~~ 39 bytes

```
Øa“œṣ$b|0Ḃ’ṃ,Ṛ$yṫµfØyḢṭḢẋ2
e€ØyIi-‘ɓḣ;ç

```

Try it online!

### How it works

```
e€ØyIi-‘ɓḣ;ç                Main link. Argument: s (string)

  Øy                        Vowels with y; yield "AEIOUYaeiouy".
e€                          Test each character in s for membership.
    I                       Increments; compute the forward differences of the
                            resulting array of Booleans.
     i-                     Find the first index of -1.
       ‘                    Increment this index to find the index of the first
                            consonant that follows a vowel.
                            Let's call this index j.
        ɓ                   Begin a new chain. Left argument: s. Right argument: j
         ḣ                  Head; yield the first j characters of s.
           ç                Call the helper link with arguments s and j.
          ;                 Concatenate the results to both sides.

```

```
Øa“œṣ$b|0Ḃ’ṃ,Ṛ$yṫµfØyḢṭḢẋ2  Helper link. Left argument: s. Right argument: j

Øa                          Alphabet; set the return value to “abc...xyz”.
  “œṣ$b|0Ḃ’                 Yield 7787255460949942. This is a numeric literal in
                            bijective base 250. The value of each digit matches its
                            1-based index in Jelly's code page.
           ṃ                Convert 7787255460949942 to base 26, using the digts
                            a = 1, b = 2, ..., y = 25, z = 0.
                            This yields "bcdfkszgvtgp".
            ,Ṛ$             Pair the result with its reverse, yielding
                            ["bcdfkszgvtgp", "pgtvgzskfdcb"].
                ṫ           Call tail with arguments s and j, yielding the j-th and
                            all following characters of s.
               y            Translate the result to the right according to the
                            mapping to the left, i.e., replace 'b' with 'p', 'c'
                            with 'g', etc. 'g' appears twice in the first string
                            of the mapping; only the first occurrence counts.
                            Let's call the resulting string r.
                 µ          Begin a new chain. Argument: r
                  fØy       Filter; remove non-vowels from r.
                     Ḣ      Head; take the first vowel.
                       Ḣ    Head; take the first character/consonant of r.
                      ṭ     Tack; append vowel to the consonant.
                        ẋ2  Repeat the resulting string twice.

```
> 60 votes

# Answer
# C, ~~219~~ ~~213~~ ~~206~~ ~~179~~ 175 bytes

```
#define p putchar
#define q(a)for(;a strchr("aeiouy",*s);p(*s++));
f(s,c,h)char*s;{q(!)q()p(*s);p(c="pgt vkh jglmn bqrzd fwx s"[*s-98]);p(h=s[strcspn(s,"aeiouy")]);p(c);p(h);}

```

Try it online!
> 32 votes

# Answer
# CJam, ~~59~~ ~~58~~ ~~57~~ 56 bytes

```
q_{"aeiouy":V&,_T|:T^}#)/(_W>"cbdfkszgvtpg"_W%er@sV&0=+_

```

Try it online!

### Explanation

```
q_                   e# Read the input and copy it.
{                    e# Find the index of the first char for which the following is true:
 "aeiouy":V          e#  Push "aeiouy" and store it in V.
 &,                  e#  Check if the current char is in the vowel string (0 or 1).
 _T|:T               e#  Copy the result and OR with T (T is initially 0), storing back in T.
 ^                   e#  XOR with the original result. This will be 1 for the first
                     e#  consonant appearing after a vowel.
}#                   e# (end find)
)/                   e# Increment the index and split the string into chunks of that size.
(                    e# Pull out the first chunk.
_W>                  e# Copy it and get the last character (the consonant).
"cbdfkszgvtpg"_W%er  e# Transliterate the consonant to voiced/voiceless alternative.
@s                   e# Bring all the other split chunks to the top and join them together.
V&0=                 e# First char of the set intersection of that and the vowels.
                     e# (i.e. the first vowel in the second half)
+                    e# Concatenate the new consonant and the vowel.
_                    e# Duplicate the result of that.
                     e# Implicit output of stack contents.

```
> 32 votes

# Answer
# Perl 5, ~~81~~ ~~72~~ 71 bytes

*-1 byte thanks to Xcali!*

```
s![aeiouy]+(.)\K.*!($1=~y/bdfgpstvzck/ptvkbzdfsg/r.$&x/[aeiouy]/g)x2!ge

```

Try it online!
> 26 votes

# Answer
# PHP, 121 Bytes

```
$v=aeiouy;preg_match("#(.*?[$v]+([^$v])).*?([$v])#",$argn,$t);echo$t[1],$z=strtr($t[2].$t[3],bcdfgkpstvz,pgtvkgbzdfs),$z;

```

Try it online!
> 18 votes

# Answer
# Python 3, ~~155~~ 139 bytes

```
import re
def f(x,k='aeiouy])'):b,c,v=re.findall(f'(.*?[{k}([^{k}.*?([{k}',x)[0];return b+c+(('bcdfgkpstvz'+c)['pgtvkgbzdfs'.find(c)]+v)*2

```

*removed 16 bytes thanks to @ovs*

*removed 1 byte thanks to Gábor Fekete*
> 15 votes

# Answer
# Java 8, ~~243~~ ~~236~~ 222 bytes

```
s->{String q="[a-z&&[^aeiouy]]",a=s.replaceAll("(^"+q+"*[aeiouy]+"+q+").*","$1"),b="pgtvkhjglmnbqrzdfwxs".charAt("bcdfghjklmnpqrstvwxz".indexOf(a.charAt(a.length()-1)))+s.replaceAll(a+q+"*([aeiouy]).*","$1");return a+b+b;}

```

Uses `.replaceAll` regexes with capture groups to filter out the parts we don't want.

**Explanation:**

Try it here.

```
s->{ // Method with String parameter and String return-type
  // Temp String we use multiple times:
  String q="[a-z&&[^aeiouy]]",
   // Regex to get the first part (i.e. `creation` -> `creat` / `example` -> `ex`)
   a=s.replaceAll("(^"+q+"*[aeiouy]+"+q+").*","$1"),
   // Get the trailing consonant and convert it
   b="pgtvkhjglmnbqrzdfwxs".charAt("bcdfghjklmnpqrstvwxz".indexOf(a.charAt(a.length()-1)))
   // Get the next vowel after the previous consonant from the input-String
    +s.replaceAll(a+q+"*([aeiouy]).*","$1");
  // Return the result:
  return a+b+b;
} // End of method

```
> 15 votes

# Answer
# Pyth, 54 bytes

```
L+hb?>F}RJ"aeiouy"<b2+hKtb*2+XhK"cgdsfbpvztkg")h@JKytb

```

This defines a function `y`, that expects a string. Try it online: Test Suite
> 15 votes

# Answer
# Haskell, 143 141 138 137 136 bytes

```
z h=elem h"aeiouy"
f i|(s,(m,c:x))<-span z<$>break z i,j:_<-filter z x,d<-"pgt.vkh.jglmn.bqrzd.fwx.s"!!(fromEnum c-98)=s++m++[c,d,j,d,j]

```

Try it online!
> 13 votes

# Answer
# Python, ~~261~~ 260 bytes

```
def c(s,t='bpcgdtfvgksz'):
 q,r,t='aeiouy',range(len(s)),t+t[::-1]
 c=[i for i in r if i>[j for j in r if s[j]in q][0]and s[i]not in q][0]
 C=([t[2*i+1]for i in range(12)if s[c]==t[i*2]]or s[c])[0]
 return s[:c+1]+(C+s[[i for i in r if i>c and s[i]in q][0]])*2

```

A Non regex, Not esoteric solution. Took about 20 minutes to make, and an hour more to golf.

It probably has more list comprehension than the entire python standard library, mostly because I don't know regex...

Try it online! (With testcases)
> 12 votes

# Answer
## Python 2, ~~251~~ ~~246~~ ~~245~~ ~~239~~ ~~237~~ ~~234~~ ~~229~~ 211 bytes

First submission here.

```
def f(s):
  r=c='';n=0;w='aeiouy';a='bcdfghjklmnpqrstvwxz'
  for i in s:
    if n<2:r+=i
    if n<1and i in w:n=1
    if n==1and i in a:c='pgtvkhjglmnbqrzdfwxs'[a.index(i)];n=2
    if n==2and i in w:r+=c+i+c+i;break
  return r

```

Try it online!

Fellow golfers that helped me:

```
 Destructible Lemon / Wheat Wizard - 5 bytes
 Hubert Grzeskowiak - 1 byte
 musicman523 - 16 bytes

```
> 9 votes

# Answer
# Ruby, 90 bytes

```
->x{x[/(.*?#{$v='[aeiouy]'}+.).*?(#$v)/];$1+($1[-1].tr('bcdfgkpstvz','pgtvkgbzdfs')+$2)*2}

```

Try it online!

Ungolfing it a bit, we have something equivalent to:

```
def covfefefify(x)
  v = '[aeiouy]'
  # Match x to a regular expression capturing:
  # Group 1:
  #  some characters (non-greedy)
  #  followed by some (greedy) non-zero number of vowels
  #  followed by exactly one character
  # Ungrouped:
  #  Some more (non-greedy) characters
  # Group 2
  #  Exactly one other vowel
  # By switching between greedy and non-greedy matches, we can capture longest and shortest vowel/consonant sequences without writing out all the consonants
  x[/(.*?#{v}+.).*?(#{v})/]
  # Glue it back together, replace the necessary consonants, duplicate where needed
  $1+($1[-1].tr('bcdfgkpstvz','pgtvkgbzdfs')+$2)*2
end

```
> 8 votes

# Answer
# Ruby, ~~175~~ ~~141~~ 110 bytes

```
->s{s=~/(.*?#{v='[aeiouy]'}+(#{c='[^aeiouy]'}))#{c}*(#{v})/;"#$1#{($2.tr('bcdfgkpstvz','pgtvkgbzdfs')+$3)*2}"}

```

Try it online!

* Saved 34 bytes thanks to Eric Duminil
* Saved 31 bytes thanks to Value Ink \+ optimized suggested `tr` arguments

**Ungolfed**

```
covfefify = -> (s) {
    from = 'bcdfgkpstvz'
    to   = 'pgtvkgbzdfs'

    vowels = "[aeiouy]"
    consonants = "[^aeiouy]"

    s.match(/(.*?#{vowels}+(#{consonants}))#{consonants}*(#{vowels})/)
    d = ($2.tr(from, to) + $3) * 2
    "#$1#{d}"
}

```
> 7 votes

# Answer
# Crystal, ~~203~~ ~~194~~ ~~187~~ ~~186~~ ~~184~~ 163 bytes

```
o=""
ARGV[v=c=0].each_char{|a|r=/#{a}/
"aeiouy"=~r&&(v=x=1)||(c=v)
o+=a if c<2||x
c>0&&(x&&break||(o+=(i="pgtvkgbqrzdfs"=~r)?"bcdfgkpqrstvz"[i]: a))}
p o+o[-2..-1]

```
> 6 votes

# Answer
## Retina, 68 bytes

```
r`\B(?>([^aeiouy])+)([aeiouy]).*
$1$1$2$1$2
T-5>`fs\dbgcgk\ptzv`Ro`.

```

Try it online!
> 6 votes

# Answer
# !@#$%^&\*()\_+, ~~102~~ ~~101~~ ~~100~~ ~~99~~ 80 bytes

```
`33554(_(^1%)%)$pgtevkhijglmnobqrzdufwxys(0*!@&)^(0*!!@&_^)Q++&!@%(0*!^&)+!@0&@@

```

42nd answer of this question, it looks like. Just one byte longer than BQN! It took much more time than it should. I'm pretty sure there are still some simple tricks that I'm missing.

Accept lowercase characters. The program does not actually contain digits - `01345Q` in the code above are unprintable characters with ASCII code 0, 1, 3, 4, 5 and 25 respectively.

Try it online!
> 6 votes

# Answer
# MATLAB / Octave - ~~159~~ 158 bytes

The following works assuming the input string is all lowercase.

```
a=input('','s');m=ismember(a,'aeiouy');s='pgt vkh jglmn bqrzd fwx s';m(1:find(m,1))=1;i=find(~m,1);f=a(1:i);d=s(f(end)-97);m(1:i)=0;v=a(find(m,1));[f d v d v]

```

# Explanation

1. `a = input('','s');`: Gets a string from STDIN and stores it into the variable `a`.
2. `m=ismember(a,'aeiouy');`: Returns a Boolean array that is the same size as the string `a` determining where vowels are located
3. `s='pgt vkh jglmn bqrzd fwx s';` The `covfefe` mapping of consonants as a string. This string is 25 characters long and omitting the vowels. The first position where the vowel `'a'` is supposed to be is removed while the other positions where the vowels are located are placed with a dummy space character. This is so that when we determine the first consonant appearing after the vowel, we will convert the consonant to a position to access a character in this string to determine the first component of the converted word.
4. `m(1:find(m,1))=1`: Sets the first position of the Boolean array up to where we have found the first vowel as all vowels. This will be so that when we search for the next consonant that follows the first vowel, we will ignore these characters.
5. `i=find(~m,1);`: Finds the first position of the string that is a consonant after the first vowel.
6. `f=a(1:i)`: Removes the string after the first consonant that follows the vowel. We simply sample from the first position of the string up to this point.
7. `d=s(f(end)-97);`: Take the last character of the string that is remaining and finds where we need to sample from the lookup string and gets that character. Subtracting a character and a number in MATLAB or Octave coalesces to form an integer by converting the character into its ASCII code. In this case, we subtract the last character by the character at the beginning of the alphabet to give us the position relative to the beginning. However, instead of subtracting by `b` (98), we subtract by `a` as MATLAB starts indexing by 1 instead of 0. `'a'`'s ASCII code is 97.
8. `m(1:i)=0;`: Takes the Boolean mask and sets all characters in the input string from the first position to the first consonant following a vowel to false.
9. `v=a(find(m,1));`: Finds the next vowel that follows the first consonant from the input string.
10. `[f d v d v]`: Output our `covfefe`ied string.

# Example Runs

```
>> a=input('','s');m=ismember(a,'aeiouy');s='pgt vkh jglmn bqrzd fwx s';m(1:find(m,1))=1;i=find(~m,1);f=a(1:i);d=s(f(end)-97);m(1:i)=0;v=a(find(m,1));[f d v d v]
coverage

ans =

covfefe

>> a=input('','s');m=ismember(a,'aeiouy');s='pgt vkh jglmn bqrzd fwx s';m(1:find(m,1))=1;i=find(~m,1);f=a(1:i);d=s(f(end)-97);m(1:i)=0;v=a(find(m,1));[f d v d v]
example

ans =

exxaxa

>> a=input('','s');m=ismember(a,'aeiouy');s='pgt vkh jglmn bqrzd fwx s';m(1:find(m,1))=1;i=find(~m,1);f=a(1:i);d=s(f(end)-97);m(1:i)=0;v=a(find(m,1));[f d v d v]
programming

ans =

progkaka

>> a=input('','s');m=ismember(a,'aeiouy');s='pgt vkh jglmn bqrzd fwx s';m(1:find(m,1))=1;i=find(~m,1);f=a(1:i);d=s(f(end)-97);m(1:i)=0;v=a(find(m,1));[f d v d v]
code

ans =

codtete

>> a=input('','s');m=ismember(a,'aeiouy');s='pgt vkh jglmn bqrzd fwx s';m(1:find(m,1))=1;i=find(~m,1);f=a(1:i);d=s(f(end)-97);m(1:i)=0;v=a(find(m,1));[f d v d v]
president

ans =

preszizi

```

# Try it online!

http://www.tutorialspoint.com/execute\_octave\_online.php?PID=0Bw\_CjBb95KQMdjROYVR0aFNrWXM

When you hit the Execute button at the top, wait a few moments, then enter the desired string. Enter the string slowly as there seems to be a delay when entering in text.
> 5 votes

# Answer
# BlitzMax, 190 bytes

```
s$=Input()For i=1To s.Length
f="aeiouy".Contains(s[i-1..i])If f v=i If c Exit
If v And c|f=0c=i
Next
t$="bpdtfvgkcgsz"x$=s[c-1..c]r=t.Find(x)~1If r>=0x=t[r..r+1]
x:+s[v-1..v]Print s[..c]+x+x

```

Takes a word from stdin and prints the result to stdout. The input word is assumed to be lowercase and to contain at least one vowel followed by a consonant.

A more readable version of the progam with formatting and variable declarations:

```
SuperStrict
Framework BRL.StandardIO

Local s:String = Input()
Local v:Int
Local c:Int

For Local i:Int = 1 To s.Length
    Local f:Int = "aeiouy".Contains(s[i - 1..i])
    If f Then
        v = i
        If c Then Exit
    End If
    If v And c | f = 0 Then c = i
Next

Local t:String = "bpdtfvgkcgsz"
Local x:String = s[c-1..c]
Local r:Int = t.Find(x) ~ 1
If r >= 0 Then x = t[r..r + 1]
x :+ s[v - 1..v]
Print s[..c] + x + x

```

How it works:

BlitzMax doesn't have any builtin regex functionality or similar, so a loop is used to iterate over the characters of the input word until it finds a vowel followed by a chain of at least one consonant. The variable c stores the position of the last of those consonants, v that of the vowel. The loop continues to see if there is another vowel after the chain and if so, v is updated accordingly. Then the consonant at c is looked up in the string "bpdtfvgkcgsz", which acts as a replacement table. If the consonant is found in the table at any position, then that position is XOR-ed with 1 and the character at the resulting position gets used as its replacement. The XOR operation turns 0 into 1, 2 into 3, 4 into 5 etc. and vice versa, so that b gets swapped with p, d with t and so on. Finally, the original string up to c, the replacement character and the vowel at v are put together as required and printed.

Example results:

> coverage covfefe
>
> creation creatdidi
>
> programming progkaka
>
> stupidity stupbibi
>
> blah blahhaha
> 5 votes

# Answer
## Clojure, ~~182~~ 156 chars

```
#(let[v #{\a\e\i\o\u\y}p(partition-by v %)[s m[c][n]](if(v(first %))(cons[]p)p)z[(or((zipmap"bcdfgkpstvz""pgtvkgbzdfs")c)c)n]](apply str(concat s m[c]z z)))

```

### How It Works

```
(partition-by v "president")

```

Returns a seq of `((\p \r) (\e) (\s) (\i) (\d) (\e) (\n \t))`

```
[s m [c] [n]] (if (v (first x)) (cons [] p) p)

```

Destructures the seq into `s=(\p \r)`, `m=(\e)`, `c=\s`, `n=\i`.

Or for "example" it's `s=[]`, `m=(\e)`, `c=\x`, `n=\a`.

```
(apply str (concat s m [c] [(l c) n] [(l c) n]))

```

Returns the output string by concatenating the pieces together and stringifying it.

And then I just removed as much whitespace as I could while still making it compile.

De-uglified:

```
(defn covfefify [x]
  (let [vowel? #{\a\e\i\o\u\y}
        parts (partition-by vowel? x)
        [start mid [consonant] [last-vowel]] (if (vowel? (first x)) (cons [] parts) parts)
        lookup #(or ((zipmap "bcdfgkpstvz" "pgtvkgbzdfs") %) %)]
    (apply str (concat start mid [consonant] [(lookup consonant) last-vowel] [(lookup consonant) last-vowel]))))

```
> 5 votes

# Answer
# R, 341 characters

```
f=function(x){g=function(x,y)el(strsplit(x,y));a=g(x,'');v=g('aeiouy','');n=letters[-c(1,5,9,15,21,25)];l=data.frame(n,g('pgtvkhjglmnbqrzdfwxs',''));y=min(match(n,a)[which(match(n,a)>min(match(v,a),na.rm=T))]);m=l[which(l$n==a[y]),2];e<-a[-c(1:y)][min(match(v,a[-c(1:y)]),na.rm=T)];paste0(paste0(a[c(1:y)],collapse=''),m,e,m,e,collapse="")}

```

Horrendous R attempt, why are strings so hard

Readable version:

```
f = function(x) {
  g = function(x, y)el(strsplit(x, y))
  a = g(x, '')
  v = g('aeiouy', '')
  n = letters[-c(1, 5, 9, 15, 21, 25)]
  l = data.frame(n, g('pgtvkhjglmnbqrzdfwxs', ''))
  y = min(match(n, a)[which(match(n, a) > min(match(v, a), na.rm = T))])
  m = l[which(l$n == a[y]), 2]
  e <-a[-c(1:y)][min(match(v, a[-c(1:y)]), na.rm = T)]
  paste0(paste0(a[c(1:y)], collapse = ''), m, e, m, e, collapse = "")
}

```
> 5 votes

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

```
s=input()
g=lambda i,f='aeiuoy':i if s[i]in f else g(i+1,f)
q=g(g(0),c:='pgtcvkh jglmn bqrzd fwx s')
exit(s[:-~q]+(c[ord(s[q])-98]+s[g(q)])*2)

```

Try it online!

A little late to the party, but here's yet another non-regex Python answer! I interpreted the rules to allow printing to STDERR which saves a byte (`exit`/`print`). Using Python 3.8 over 3\<=3.7 saves me a total of 1 byte with the walrus operator as opposed to defining the `c` variable elsewhere.

Thanks a lot to Post Rock Garf Hunter (-21 bytes) for the help!
> 5 votes

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

-16 bytes thanks to Okx

I somehow hope this can be done *way* more efficiently.

```
žOÃćIsk>[DIs£¤žPså#\>]s[DIsèDžOså#\>]ŠŠ"bpcgdtfvgkhhjjkgllmmnnpbqqrrsztdvfwwxxzs"S2ôDí«ø`Šs¤sŠksŠèsŠì2×«

```

Try it online!

## Explanation

```
                  Argument: s
žOÃ0èk            Get index of first vowel in s
>[DIs£¤žPså#\>]   Increment index and split s until last character of substring is a consonant
s[DIsèDžOså#\>]   Increment index an get character at index in s until character is a vowel
ŠŠ                Rearrange stack
.•7¶ëÒ—Öb´ƒ≠Ä“šʒÆµJ^ÝV“Îpи•S2ôDí«ø`   Prepare character substitution map
Šs                Rearrange stack
¤                 Last character of substring
sŠ                Rearrange stack (yes, again)
k                 Index of last character in substitution key list
sŠ                Rearrange stack (it won't stop)
è                 Character at index in character substitution value list
sŠ                Rearrange stack (ONE LAST TIME)
ì2×«              Prepend substitution consonant before vowel, duplcicate and concatenate with the substring from the very beginning

```
> 4 votes

# Answer
# Perl, 71 bytes

```
s#[aeiouy]+(.)\K.*?([aeiouy]).*#"$1$2"=~y/bcdfgkpstvz/pgtvkgbzdfs/rx2#e

```

Also run with `perl -pe`. A few bytes less than the previous Perl solution. Admittedly I got some inspiration from there as well.
> 4 votes

# Answer
# Vim, 107 keystrokes

<sup>Who needs Java, Python 3, Modern Pascal 2.0, C#, Python 2, R, Go, C, BlitzMax, Javascript, Crystal, Clojure, Lua, Matlab/Octave, Haskell and PHP when you have vim?</sup>

```
i ⎋o⏎bcdfghjklmnpqrstvwxz⏎pgtvkhjglmnbqrzdfwxs⎋1Ghqy/[aeiouy]⏎q/[^aeiouy]⏎mz@yyl`zpld$yhjpg*jyl`zpy2lPjdGX

```

is the `Escape` key and  is the `Return` key

## Explanation

```
i ⎋                         Insert a space before the first character
o⏎bcdfghjklmnpqrstvwxz⏎     Insert the character data
  pgtvkhjglmnbqrzdfwxs⎋1Gh
qy/[aeiouy]⏎q               Find the first vocal after the space
/[^aeiouy]⏎mz               Find the next consonant and add a marker
@yyl`zp                     Find the next vocal and put it after the consonant
ld$                         Delete the rest of the world
yhjpg*                      Search for the consonant in the first row of the character data
jyl                         Copy the character in the same position in the second row
`zpy2lPjdGX                 Paste it after the last vowel and repeat the two last characters

```
> 4 votes

# Answer
# 05AB1E, ~~55~~ 42 bytes

```
η.ΔžOSåàyžPSÅ¿à*}ÐIsKžOÃнsθ.•gÍĆdQ¸G•Â‡ìDJ

```

-13 bytes thanks to *@Grimmy*.

Try it online or verify all test cases.

**Explanation:**

```
η                # Suffixes of the (implicit) input
                 #  i.e. "creation" → ["c","cr","cre","crea","creat","creati","creato","creatio","creation"]
 .Δ       }      # Find the first for which the following is truthy:
   žO            #  Push vowels (including y): "aeiouy"
     S           #  Convert it to a list of characters: ["a","e","i","o","u","y"]
      å          #  Check for each if they're in the current (implicit) suffix
                 #   i.e. "creat" → [1,1,0,0,0,0]
       à         #  Pop and push the max (basically check if any are truthy)
                 #   i.e. [1,1,0,0,0,0] → 1
   y             #  Push the suffix again
    žP           #  Push the consonants (excluding y): "bcdfghjklmnpqrstvwxz"
      S          #  Convert to a list of characters: ["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","z"]
       Å¿        #  Check for each if the suffix ends with it
                 #   i.e. "creat" → [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0]
         à       #  Pop and push the max (basically check if any are truthy)
                 #   i.e. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0] → 1
   *             #  Check if both are truthy
                 #   i.e. 1 and 1 → 1
           Ð     # Triplicate the found suffix
            I    # Push the input
             s   # Swap the top two items on the stack
                 #  i.e. stack contains now: "creat","creat","creation","creat"
K                # Remove the suffix from the input
                 #  i.e. "creation" and "creat" → "ion"
 žOÃ             # Only leave the vowels
                 #  i.e. "ion" → "io"
    н            # Pop and push the first character
                 #  i.e. "io" → "i"
s                # Swap again so the prefix is a the top of the stack again
 θ               # Pop and push the last character
                 #  i.e. "creat" → "t"
  .•gÍĆdQ¸G•     # Push string "bcdfkszgvtgp"
            Â    # Bifurcate it (short for Duplicate & Reverse copy): "pgtvgzskfdcb"
             ‡   # Transliterate the character of "bcdfkszgvtgp" to the same index in "pgtvgzskfdcb"
              ì  # Prepend the second character in front of the first
                 #  i.e. "d" and "i" → "di"
               D # Duplicate it
J                # Join the stack together (and output implicitly)
                 #  i.e. "creat" and "di" and "di" → "creatdidi"

```

See this 05AB1E tips of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•gÍĆdQ¸G•` is `"bcdfkszgvtgp"`.
> 4 votes

# Answer
# Lexurgy, ~~288~~ ~~286~~ 281 bytes

Docs here.

Lexurgy is an online tool meant for conlangers (people who make constructed languages) to apply sound changes to their conlangs via a series of programmable rules. As such, this tool involves many string operations.

* -2: remove the `u` and `w` classes and replace them with one-time substitutions.
* -5: fix a bug with the `example` case, combine some rules into a single step

```
Class v {a,e,i,o,u}
Class c {p,t,k,f,s,c,b,d,g,v,z,g,h,j,l,m,n,q,r,w,x}
a:
@c *=>@c ;/$ @c* @v* _//{$ _,$ @c _}
b:
@c=>* /; _
c:
{@v,@c}=>* /; @v {@v,@c}* _
* {{p,t,k,f,s,c,x},{b,d,g,v,z,g,x}}$1=>$1 {{b,d,g,v,z,g,x},{p,t,k,f,s,c,x}}/_ ;
e:
@c$1 ;=>; $1
f:
(@c @v)$1=>$1 $1/; _
;=>*

```

Ungolfed:

```
Class vowel {a,e,i,o,u}
Class unvoiced {p,t,k,f,s,c}
Class voiced {b,d,g,v,z,g}
Class consonant {@unvoiced,@voiced,h,j,l,m,n,q,r,w,x}

# find first consonant after first vowel
part-1:
 @consonant * => @consonant ; / $ @consonant* @vowel* _ // {$ _, $ @consonant _}

romanizer-a:
 unchanged

# delete the consonant after the seperator
part-2:
 @consonant => * / ; _

romanizer-b:
 unchanged

# remove everything except the second vowel
part-3:
 {@vowel, @consonant} => * / ; @vowel {@vowel, @consonant}* _

romanizer-c:
 unchanged

# voicings
part-4:
 * @voiced$1 => $1 @unvoiced / _ ;
 * @unvoiced$1 => $1 @voiced / _ ;

romanizer-d:
 unchanged

# swap mapped consonant and seperator
part-5:
 @consonant$1 ; => ; $1

romanizer-e:
 unchanged

# duplicate the `fe`
part-6:
 (@consonant @vowel)$1 => $1 $1 / ; _

romanizer-f:
 unchanged

# remove the seperator
part-7:
 ; => *

```
> 4 votes

# Answer
# Crystal, 130 Bytes

```
c=/[aeiouy]/
x,y,z=ARGV[0].partition /[^aeiouy]*#{c}*/
k=z[0]
b=((i="pgtvkgbqrzdfs"=~/#{k}/)?"bcdfgkpqrstvz"[i]: k)+z[c]
p y+k+b*2

```

# How it works

```
c = /[aeiouy]/

```

store a regex for searching first vowel to `c`.

```
x, y, z = ARGV[0].partition /[^aeiouy]*#{c}*/

```

split the first argument into three parts {"", String until one character before the first consonant after first vowel, rest of string} and store each of the elements into x, y and z.

```
k = z[0]

```

get the first character, the relevant consonant.

```
i = "pgtvkgbqrzdfs" =~ /#{k}/

```

get the index of the consonant inside the left string or `nil`.

```
b = ((i = ...) ? "bcdfgkpqrstvz"[i] : k) + z[c]

```

if `i` is not `nil`, use this index for the second string (kind of a golfed hash).

if `i` is `nil`, use the original character.

next, append the first vowel of `z`.

```
p y + k + (b * 2)

```

finally, print first part from first regex `y`, the first consonant `k` and two times the previous calculated string `b`.

Try it online.
> 3 votes

# Answer
# sed, 106 (105+1) bytes

This is sed with the `-E` flag, which apparently counts for one byte.

```
s/([aoeuiy][^aoeuiy])[^aoeuiy]*(.).*/\1\2/
h
s/.*(..)/\1\1/
y/bcdfgkpstvz/pgtvkgbzdfs/
x
s/.$//
G
s/\n//g

```

Try it online!
> 3 votes

# Answer
# SmileBASIC 3, 195 bytes

Very late to this question, but how could I resist a good challenge for SmileBASIC 3? Features like iterating over a sequence or manipulating a string aren't quite as robust as other languages, so this is a bit of a challenge to do it as small as possible. Assumes words are UPPERCASE.

```
V$="AEIOUY
LINPUT W$REPEAT I=I+1UNTIL.<=INSTR(V$,W$[I-1])&&.>INSTR(V$,W$[I])J=I
WHILE.>INSTR(V$,W$[J])J=J+1WEND?LEFT$(W$,I+1)+("PGTVKHJGLMNBQRZDFWXS"[INSTR("BCDFGHJKLMNPQRSTVWXZ",W$[I])]+W$[J])*2

```

Detailed explanation here!
> 3 votes

# Answer
# 05AB1E, 35 bytes

```
1ú.γžOså}R`¦??н©?н®ì.•gÍĆdQ¸G•Â‡D?,

```

Try it online!

```
1ú                 # prepend the input with a space
                   # (this ensures the word doesn’t start with a vowel)
  .γ    }          # group characters by:
    žO             #  built-in constant "aeiouy"
      så           #  is the character in that string?
         R         # reverse the list of groups
          `        # dump all on the stack (first group on top)
¦                  # remove the space we added earlier
 ?                 # print the first consonant group
  ?                # print the first vowel group
   н               # get the first letter of the second consonant group
    ©              # save it in the register
     ?             # print it
      н            # get the first letter of the second vowel group
       ®           # restore the consonant from the register
        ì          # prepend, giving a consonant-vowel pair
.•gÍĆdQ¸G•         # compressed string "pgtvgzskfdcb"
          Â        # push a reversed copy of it
           ‡       # transliterate (b => p, c => g, ...)
            D      # duplicate the transliterated pair
             ?,    # print both copies (with a newline the second time)

```
> 3 votes

# Answer
# PowerShell, 324 bytes

```
$v="[aeiouy]";$f=[regex]::match($w,$v).index+1;$s=[regex]::match($w.substring($f),"[^aeiouy]").index;$t=[regex]::match($w.substring($f),$v);
$c=@{b='p';c='g';d='t';f='v';g='k';h='h';j='j';k='g';l='l';m='m';n='n';p='b';q='q';r='r';s='z';t='d';v='f';w='w';x='x';z='s'};
$r=$c["$($w[($f+$s)])"];$w.substring(0,$f+$s+1)+"$r$t$r$t"

```

This was as short as I could get it without frying my brain. Takes input as `$w='coverage'`.

Try it online!
> 3 votes

# Answer
# JavaScript (ES5), 237 229 bytes

```
function(s){r=['aeiouy','bcdfgkpstvz','pgtvkgbzdfs']i=0,p=''while(p+=s[i],r[0].indexOf(s[i++])<0);while(p+=s[i],~r[0].indexOf(s[i++]));b=s[i-1];while(r[0].indexOf(s[i++])<0);c=r[1].indexOf(b)d=((~c)?r[2][c]:b)+s[i-1]return p+d+d}

```

Try it online!

Probably not the most golfy, but it is ES5.

Recently fixed a bug. Example output:

```
creation->creatdidi
coverage->covfefe
example->exxaxa
programming->progkaka
code->codtete
president->preszizi

```
> 2 votes

# Answer
# Lua, ~~164~~ 157 bytes

```
w=arg[1]
i,j,a,b=w:find('[aeiouy]+([^aeiouy]+)(.)')
print(w:sub(1,j-#a)..(('pgtvkhjglmnbqrzdfwxs'):sub(('bcdfghjklmnpqrstvwxz'):find(a:sub(1,1)))..b):rep(2))

```

Edit 1: *Removed 7 bytes by looking for any character after the consonants (see regex)*

**Try it online!**

This program takes a string in CLI argument and prints its covfefied version.

This is my first submission to a code golf! I didn't check the others in detail so I might have missed some common optimizations (and fell in some traps). I used Lua because I've grown to like this little language, and I tried to find a regex that suited my needs.

Here's a cleaner version, using a function (I intended to use one, but the keywords in Lua are too long!):

```
function covfefy(word)
  i, j, a, b = word:find('[aeiouy]+([^aeiouy]+)(.)')

  -- 'a' is one or several consonants following the first vowel, b is the first vowel after that
  -- 'i' is the index of the beginning of 'a', 'j' the index of 'b'

  cov = word:sub(1, j - #a)

  -- Look for the first letter of 'a' in the voiced/voiceless table
  f = ('pgtvkhjglmnbqrzdfwxs'):sub(('bcdfghjklmnpqrstvwxz'):find(a:sub(1, 1)))

  return cov .. (f .. b):rep(2)
end

```

Feel free to give some feedback :)

Note: If you're wondering, it's 149 bytes long using MoonScript!
> 2 votes

# Answer
# C#, 584 581 bytes

-3 bytes thanks to Destructible Lemon

This is my first submission on Code Golf and on Stack Exchange in general. I know that C# isn't a great golfing language and this probably isn't completely optimized but I wanted to give it a shot :p. Any tips are welcome!

Golfed Version:

```
namespace System{class B{static void Main(string[]args){var s="creation";var t="aeiou";int i=0,j=0,l=s.Length;char c=' ',f=' ';for(int x=0;x++<l;){if(t.IndexOf(s[x])>=0){i=x;break;}}for(int x=i;x++<l;){if(!(t.IndexOf(s[x])>=0)){j=x;c=s[x];for(int y=x;y++<l;){if (t.IndexOf(s[y])>=0){f=s[y];goto W;}}}}W:switch(c){case'b':c='p';break;case'c':c='g';break;case'd':c='t';break;case'f':c='v';break;case'g':c='k';break;case'k':c='j';break;case'p':c='b';break;case's':c='z';break;case't':c='d';break;case'v':c='f';break;case'z':c='s';break;}Console.Write(s.Substring(0,l-i-1)+c+f+c+f);}}}

```

Readable Version:

```
namespace System
{
    class B
    {
        static void Main(string[] args)
        {
            var s = "creation";
            var t = "aeiou";
            int i = 0, j = 0, l = s.Length;
            char c = ' ', f = ' ';
            for (int x = 0; x++ < l; )
            {
                if (t.IndexOf(s[x]) >= 0)
                {
                    i = x; break;
                }
            }
            for (int x = i; x++ < l;)
            {
                if (!(t.IndexOf(s[x]) >= 0))
                {
                    j = x; c = s[x];
                    for (int y = x; y++ < l;)
                    {
                        if (t.IndexOf(s[y]) >= 0)
                        {
                            f = s[y];
                            break;
                        }
                    }
                }
            }
            switch (c)
            {
                case 'b': c = 'p';
                    break;
                case 'c': c = 'g';
                    break;
                case 'd': c = 't';
                    break;
                case 'f': c = 'v';
                    break;
                case 'g': c = 'k';
                    break;
                case 'k': c = 'j';
                    break;
                case 'p': c = 'b';
                    break;
                case 's': c = 'z';
                    break;
                case 't': c = 'd';
                    break;
                case 'v': c = 'f';
                    break;
                case 'z': c = 's';
                    break;
            }
            Console.Write(s.Substring(0, l - i - 1) + c + f + c + f);
        }
    }
}

```
> 2 votes

# Answer
# Python 3, 190 bytes

```
f=lambda s,g='aeiouy':min([s.index(l)for l in g if l in s])
C='bcdfghjklmnpqrstvwxyz'
q=input()
v=f(q)
c=f(q[v:],C)+v+1
print(q[:c]+('pgtvkhjglmnbqrzdfwxs'[C.index(q[c-1])]+q[f(q[c:])+c])*2)

```

Try it online!

I've had this coded since the week of the challenge, but was discouraged to post in its then-current state (which also happens to be the current state) because of all the 80-byte regex answers.

But hey, what the hell. Here's another non-esoteric, non-regex answer, six months late to the party.

*-30 bytes from typing out the consonants in a string rather than using a list comprehension*

*-4 bytes from using the result of a calculation inline rather than assigning it to a variable (whoops)*
> 2 votes

# Answer
# SmileBASIC, ~~185~~ ~~179~~ 168 bytes

This is an even more golfed version of snail\_'s answer.

```
INPUT W$DEF V(C)RETURN.>INSTR(@AEIOUY,W$[C])END@L?W$[I];
I=I+1ON!V(I-1)&&V(I)GOTO@L
X$=W$[I]WHILE V(I)I=I+1WEND?X$;((X$+@PGTVKGBZDFS)[INSTR(@BCDFGKPSTVZ,X$)+1]+W$[I])*2

```

## Ungolfed:

```
'input
INPUT WORD$
'function returns true if the character at POS is a consonant
DEF CONSONANT(POS)
 RETURN INSTR(@AEIOUY,WORD$[POS])<0
END
'scan through the word until there's a vowel followed by a consonant
REPEAT
 PRINT WORD$[I];
 I=I+1
UNTIL !CONSONANT(I-1) && CONSONANT(I)
'Store and print the final letter of the "normal" section
LASTNORMAL$=WORD$[I]
PRINT LASTNORMAL$;
'Find the next vowel
WHILE CONSONANT(I)
 I=I+1
WEND
'If last normal letter is one of "BCDFGKPSTVZ", replace with corresponding letter in "PGTVKGBZDFS"
'otherwise don't change it
CORRUPTED$=(LASTNORMAL$+@PGTVKGBZDFS)[INSTR(@BCDFGKPSTVZ,LASTNORMAL$)+1]
'print the "corrupted" letter and the vowel that was found earlier, twice.
PRINT (CORRUPTED$+WORD$[I])*2

```
> 2 votes

# Answer
# Python 3, ~~170~~ 149 bytes

```
def f(s):g=lambda x,y:[(i in"aeiouy")for i in s].index(x,y);j=g(0,g(1,0));c=s[j];z="ckbdfszvtpgg"+c;return s[:j+1]+2*((c+z)[-z.index(c)-2]+s[g(1,j)])

```

Try it online!

A more readable version:

```
def f(s):
    n = [ (i in "aeiou") for i in s ]
    i = n.index(1)
    j = n.index(0, i)
    k = n.index(1, j)
    c = s[j]
    v = s[k]
    z = "ckbdfszvtpgg" + c
    r = (c+z)[-z.index(c)-2]
    return s[:j+1] + r + v + r + v

```

`i`, `j`, and `k` are the indices of the first vowel, the first consonant after that `c`, and the first vowel after that `v` respectively.
> 2 votes

# Answer
# BQN, 79 bytes<sup>SBCS</sup>

```
{s∾4⥊("s_xwf_dzrqb_nmlgj_hkv_tgp"⊑˜'z'-⊑⌽s←⊑w⊔)∾⊑/˜v∧w←0∾»∨`1‿0⍷v←∊"aeiouy"}

```

Run online!
> 2 votes

# Answer
# Perl, 90 bytes (89 + 1)

I see that I've already been beaten by another Perl answer, but I'll post this anyway. Run with `-p`.

```
s/[aeiouy](.)\K[^aeiouy]*(.).*$//;$x=$1=~y/bcdfgkpstvz/pgtvkgbzdfs/r;$_.="$x$2"x2

```
> 1 votes

# Answer
# Modern Pascal 2.0, 415, 396 bytes

```
function c(S:String):String;
var L,M,I:Longint; const v='aeiouy'; o='_pgt_vkh_jglmn_bqrzd_fwx_s';
begin S:=Lowercase(S); Result:=S;
For l:=1 to length(S) do if pos(S[l],v)>0 then Break;
For M:=l to length(S) do if pos(S[M],v)=0 then begin
Result:=Copy(S,1,M);I:=Ord(S[M])-96;Delete(S,1,M);
For L:=1 to Length(S) do If Pos(S[l],v)>0 then begin
Result+=o[I]+S[L]+o[I]+S[L];Break;End;Break;End;End;

```

// Author of Modern Pascal
> 1 votes

# Answer
## Go, 298 bytes

```
func c(l string)string{v:="aeiouy";c:="bcdfghjklmnpqrstvwxz";r:="pgtvkhjglmnbqrzdfwxs";b:=l[0:strings.IndexAny(l,v)+1];t:=strings.SplitAfterN(l,b,2)[1];i:=strings.IndexAny(t,c);b=b+t[0:i+1];x:=string(r[strings.IndexAny(c,string(t[i]))]);z:=string(t[i:][strings.IndexAny(t[i:],v)]);return b+x+z+x+z}

```
> 1 votes

# Answer
# Vyxal `o`, 32 bytes

```
ðp≬k∪$cḊṘ÷Ḣ₴₴h:₴$hJ«ƛKS⟩NĖ!ǐ«ḂĿd

```

Try it Online!

Port of Grimmy's 05AB1E answer.
> 1 votes

# Answer
# Knight, ~~161~~ 154 bytes

```
;=xP;=v=c=uF;=s"";Wx;|&v c=s+sA=tAx;I=p|?97=aAx|?101a|?105a|?111a|?117a?121a=vTx;I&v!p=cTx;&&p&c&v!u=uAa=xGx 1LxO+s*+G"pgt_vkh_jglmn_bqrzd_fwx_s"-t 98Tu 2

```

Try it online!

-7 bytes thanks to Aiden Chow
> 1 votes

# Answer
# brev 149 bytes

```
(define(v x)(string-translate x"bcdfgkpstvz""pgtvkgbzdfs"))(fn(strse x"(.*?[aeiouy]+(.))[^aeiouy]*(.)"(entire(conc(m 1)(v(m 2))(m 3)(v(m 2))(m 3)))))

```

Straight-forward regex solution♥
> 1 votes

# Answer
# Excel, 207 bytes

```
=LET(s,A1,x,SEQUENCE(LEN(s)),c,ISERROR(FIND(MID(s,x,1),"aeiouy")),k,MIN(IF(c*(x>MIN(IF(c,"",x))),x,"")),q,MID(s,k,1),m,"bcdfkszgvtgp"&q,n,MID(q&m,14-FIND(q,m),1)&MID(s,MIN(IF(c+(x<k),"",x)),1),LEFT(s,k)&n&n)

```
> 0 votes

# Answer
# Scala, 281 bytes

Modified from the answer of @WaitndSe.

---

281 bytes version. Try it online!

```
type S=String
def f(s:S):S={val r,c=new StringBuilder;var(n,w,a)=(0,"aeiouy","bcdfghjklmnpqrstvwxz");for(i<-s){if(n<2)r+=i;if(n<1&&w.contains(i))n= 1;if(n==1&&a.contains(i)){c++="pgtvkhjglmnbqrzdfwxs"(a.indexOf(i))+"";n=2};if(n==2&&w.contains(i)){r++=c+""+i+c+i;return r+""}};r+""}

```

340 bytes version. Try it online!

```
type S=String
implicit class V[A](val x:A)extends AnyVal{def Q=x.toString}
def f(s:S):S={val r,c=new StringBuilder;var(n,w,a)=(0,"aeiouy","bcdfghjklmnpqrstvwxz");for(i<-s){if(n<2)r+=i;if(n<1&&w.contains(i))n= 1;if(n==1&&a.contains(i)){c++="pgtvkhjglmnbqrzdfwxs"(a.indexOf(i)).Q;n=2};if(n==2&&w.contains(i)){r++=c.Q+i+c.Q+i;return r.Q}};r.Q}

```

Ungolfed version. Try it online!

```
import scala.collection.mutable

object Main {
  def f(s: String): String = {
    val r = new StringBuilder
    var c = ""
    var n = 0
    val w = "aeiouy"
    val a = "bcdfghjklmnpqrstvwxz"

    for (i <- s) {
      if (n < 2) r += i
      if (n < 1 && w.contains(i)) n = 1
      if (n == 1 && a.contains(i)) {
        c = "pgtvkhjglmnbqrzdfwxs"(a.indexOf(i)).toString
        n = 2
      }
      if (n == 2 && w.contains(i)) {
        r ++= c + i + c + i
        return r.toString()
      }
    }
    r.toString()
  }

  def test(func: String => String, testcases: Map[String, String]): Unit = {
    for ((caseInput, caseOutput) <- testcases) {
      if (func(caseInput) != caseOutput) {
        throw new Exception(s"Function fails on testcase '$caseInput'.")
      }
    }
    println("Function passed all testcases.")
  }

  def main(args: Array[String]): Unit = {
    test(f, Map(
      "coverage" -> "covfefe",
      "example" -> "exxaxa",
      "programming" -> "progkaka",
      "code" -> "codtete",
      "president" -> "preszizi"
    ))

    println(f("creation"))
    println(f("coverage"))
    println(f("example"))
    println(f("programming"))
    println(f("code"))
    println(f("president"))
  }
}

```
> 0 votes

# Answer
# Lua, 128 bytes

```
w=...i,j,a,b=w:find'[aeiouy]+([^aeiouy]+)(.)'n=a:byte()-97g=('pgtevkhijglmnobqrzdufwxys'):sub(n,n)..b print(w:sub(1,j-#a)..g..g)

```

Try it online!

This is effectively Kyrio's Answer with a lot of minor optimizations, as well as completely swapping out the logic for finding the replacement consonant.
> 0 votes

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


title: Straight pen strokes for Prime Numbers

text:
# Question
Title: Straight pen strokes for Prime Numbers
### Challenge

You are supposed to output the series I recently designed which goes as follows which are pen stroke counts of ascending prime numbers:

```
2, 3, 2, 4, 3, 5, 6, 5, 7, 7, 7, 10, 4, 6, 7, 4, 4, 4, 7, 6, 8...

```

### Example

This is an illustration of how this series is formed, first, it takes a prime number from in sequence form, so it takes the first prime number `2`. It converts it to the Roman numeral of 2, which is `II`, here pen stroke is a straight long line, in this case, it is two so the first element in this series is `2`.

### Dictionary

It will really be confusing to explain the pen stroke for each letter, and we know all Roman numerals contain characters `I, V, X, L, C, D, M` only, here is already shown pen stroke value of each letter

```
0  C
1  I, L, D
2  V, X
3  [None]
4  M

```

For example `MMMMMMMCMXIX` is the Roman numeral `7919` so you compare it with the above dictionary `M` has 4 pen strokes and so on, they add to `37` pen strokes.

### Ambiguities

It can be queried why `M` is not assigned `2` strokes, and `L` is not assigned 2 strokes; it is because they are not written this way in numeral numbers. As M and L are written:

In standard Roman numerals, M makes 4 pen strokes and L as 1 because another line of L is too small to be considered a pen stroke.

### Task

Write the shortest code in the number of bytes that takes an input number, and outputs as many elements from the input as possible.

### Test Cases

```
5 => 2, 3, 2, 4, 3
10 => 2, 3, 2, 4, 3, 5, 6, 5, 7, 7
15 => 2, 3, 2, 4, 3, 5, 6, 5, 7, 7, 7, 10, 4, 6, 7

```

---

Do not forget that it is the implementation of pen stroke counts of Roman numerals of prime numbers in ascending order only!

# Answer
> 8 votes
# Vyxal,  ~~15~~  14 bytes

-1 thanks to lyxal (vectorisation).

```
ʁǎøṘC»ṫN»$%5%Ṡ

```

**Try it Online!**

### How?

```
ʁǎøṘC»ṫN»$%5%∑ - input a non-negative integer, N
ʁ               - range -> [0..N-1]
 ǎ              - ith prime -> [2,3,5,...p(N)]
   øṘ           - to roman numerals   :  I   V   X   L   C   D   M
     C          - cast to ordinals      73  86  88  76  67  68  77
      »ṫN»      - 39602
          $     - swap
           %    - modulo                36  42   2   6   5  26  24
            5%  - modulo five            1   2   2   1   0   1   4
              Ṡ - sums

```

# Answer
> 5 votes
# Factor \+ `math.primes math.unicode roman`, 63 bytes

```
[ nprimes [ >roman [ "c--ildvx----m"index 3 /i ] map Σ ] map ]

```

Try it online!

```
[                            ! start quotation (anonymous function)
    nprimes                  ! get a list of the first number of primes indicated by input
    [                        ! start map
        >roman               ! convert current prime to roman numerals
        [                    ! start map
            "c--ildvx----m"  ! push string to stack
            index            ! find the index of the current letter in the string
            3 /i             ! integer divide by 3
        ] map                ! map over each letter in the roman numerals of current prime
        Σ                    ! take sum of results of the letters
    ] map                    ! map over the first n primes
]                            ! end quotation

```

# Answer
> 5 votes
# Vyxal, ~~19~~ 18 bytes

```
ʀǎƛøṘkṘvḟ»øṪK»fvi∑

```

Try it Online!

```
ʀǎƛøṘkṘvḟ»øṪK»fvi∑
ʀǎƛ                 # map over each of the first n primes:
   øṘ               #   convert to roman numerals
     kṘvḟ           #   index of each character in "IVXLCDM"
         »øṪK»f     #   digits of compressed integer 1221014
               vi   #   index each into digit list
                 ∑  #   sum

```

# Answer
> 3 votes
# 05AB1E, 14 bytes

```
Åpε.XÇŽœ
s%5%O

```

Port of JonathanAllan's Vyxal answer, so make sure to upvote him as well!

Try it online.

**Outputting the infinite sequence without input would be 14 bytes as well:**

```
Žœ
∞<Ø.X€Ç%5%O

```

Try it online.

**Explanation:**

```
Åp               # Get a list of the first (implicit) input amount of primes
  ε              # Map over each prime number:
   .X            #  Convert it to a Roman number string
     Ç           #  Convert this string to a list of its codepoint integers
      Žœ\n       #  Push compressed integer 39602
          s      #  Swap so the list of lists of codepoint integers is at the top
           %     #  Modulo the 39602 by each of these codepoints
            5%   #  Modulo-5 that
              O  #  Take the sum of each inner list
                 # (after which the resulting list is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Žœ\n` is `39602`.

# Answer
> 2 votes
# Wolfram Language(Mathematica), ~~127~~ 101 bytes

Saved 26 bytes thanks to @att's comment.

---

Golfed version. Try it online!

```
f=Tr[<|"C"->0,"I"->1,"L"->1,"D"->1,"V"->2,"X"->2,"M"->4|>/@Characters@RomanNumeral@Prime@#]&~Array~#&

```

Ungolfed versrion. Try it online!

```
strokeCounts = <| "C" -> 0, "I" -> 1, "L" -> 1, "D" -> 1, "V" -> 2, "X" -> 2, "M" -> 4 |>;

penStrokeCount[n_] := Module[{romanNumeral, strokes},
    romanNumeral = IntegerString[Prime[n], "Roman"];
    strokes = Total[Lookup[strokeCounts, Characters[romanNumeral]]];
    strokes
]

primePenStrokes[n_] := Table[penStrokeCount[i], {i, 1, n}];

(* example usage *)
primePenStrokes[15]//Print (* outputs {2, 3, 2, 4, 3, 5, 6, 5, 7, 7, 7, 10, 4, 6, 7} *)
primePenStrokes[10]//Print (* outputs {2, 3, 2, 4, 3, 5, 6, 5, 7, 7} *)
primePenStrokes[5]//Print (* outputs {2, 3, 2, 4, 3} *)

```

# Answer
> 2 votes
# Excel, ~~142~~ 139 bytes

```
=LET(
    a,SEQUENCE(99),
    b,TOROW(a),
    MMULT(
        LOOKUP(
            MID(ROMAN(TAKE(FILTER(a,MMULT(N(MOD(a,b)=0),a^0)=2),A1)),b,1),
            {"","D","M","V"},
            {0,1,4,2}
        ),
        a^0
    )
)

```

Input in cell `A1`. The static `99` within the part `SEQUENCE(99)` has been arbitrarily chosen and will generate a valid output for `A1<26`.

# Answer
> 1 votes
# JavaScript (ES6), 155 bytes

Full answer with all the irrelevant stuff.

```
f=(k,n=1)=>k?(g=d=>n%d--?g(d):d)(n++)?f(k,n):["2345545673"[n%10]-(g=d=>n/d%10%9<4)(10)-g(100)+11%~(q=-~n/10%5)*2+(q-4?4*!q:6)+(n/1e3+.1<<2),...f(k-1,n)]:[]

```

Try it online!

## Core task (96 bytes)

Here is the interesting part for easier testing: a function taking an integer and returning the number of straight pen strokes in its Roman numeral representation.

```
n=>"2345545673"[n%10]-(g=d=>n/d%10%9<4)(10)-g(100)+11%~(q=-~n/10%5)*2+(q-4?4*!q:6)+(n/1e3+.1<<2)

```

Try it online!

### Commented

```
n =>           // n = input
"2345545673"   // hard-coded number of straight strokes + 2 in I's
[n % 10] -     // and V's, which can be computed modulo 10
(              // g is a helper function processing L's and D's,
  g = d =>     // which follow the same logic:
  n / d % 10   //   divide n by the argument and reduce modulo 10
  % 9          //   further reduce modulo 9
  < 4          //   is the result less than 4?
)(10) -        // first call to g with d = 10
g(100) +       // 2nd call to g with d = 100
11 %           // the number of X's can be computed modulo 50
~(             // we first evaluate the generic expression:
  q =          //   11 mod floor(q + 1)
  -~n / 10 % 5 //   with q = ((n + 1) / 10) mod 5
) * 2 +        // and double the result to get the number of strokes
(              // we then apply two corrections:
  q - 4 ?      //
    4 * !q     //   +4 strokes if q = 0, i.e. n = 49 (mod 50)
  :            //
    6          //   +6 strokes if q = 4, i.e. n = 39 (mod 50)
) +            //
(              //
  n / 1e3 + .1 // the number of M's is floor(n / 1000 + 1 / 10)
  << 2         // we multiply by 4 to get the number of strokes
)              //

```

---
Tags: code-golf, sequence, primes, subsequence, roman-numerals
---


title: Determine NBA conference seedings

text:
# Question
Title: Determine NBA conference seedings
Heading into the final day of regular season games for the 2023 NBA season, the fifth to ninth seeds in the Western Conference were still very undecided. Four games would determine the seeding:

* New Orleans (N) at Minnesota (M)
* Utah at LA Lakers (L)
* Golden State (G) at Portland
* LA Clippers (C) at Phoenix

Let the Boolean variables `M L G C` denote the event of the respective team winning. Then the seeding depends on these variables as follows (taken from this Twitter post):

```
M L G C | 5 6 7 8 9
0 0 0 0 | N G C L M
0 0 0 1 | C N G L M
0 0 1 0 | G N C L M
0 0 1 1 | C G N L M
0 1 0 0 | N C L G M
0 1 0 1 | C L N G M
0 1 1 0 | G N C L M
0 1 1 1 | C G L N M
1 0 0 0 | C G M L N
1 0 0 1 | C G M L N
1 0 1 0 | G C M L N
1 0 1 1 | C G M L N
1 1 0 0 | C L G M N
1 1 0 1 | C L G M N
1 1 1 0 | G C L M N
1 1 1 1 | C G L M N

```

## Task

Given the bits `M L G C`, output the corresponding permutation of `C G L M N`, with the fifth seed first. For example, the input `M L G C = 1 0 1 0` should give `G C M L N`. You may use any five distinct symbols for the teams and may format the permutation in any reasonable manner.

Instead of taking `M` you may take its inverse `N`, with results altered accordingly (so the input `N L G C = 1 0 1 0` gives the same result as `M L G C = 0 0 1 0`, i.e. `G N C L M`). You may also combine the Boolean inputs into a single four-bit integer, but in any case you must clearly indicate which bit or bit position corresponds to which game.

This is ; fewest bytes wins.

---

*The actual results had all bits set to 1, resulting in the seeding*

```
5 6 7 8 9
C G L M N

```

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

Expects a single 4-bit integer, where the least significant bit is `C`. Returns an array of letters.

```
n=>[...'MGNCL'].sort(_=>~(q/=2)%2,q=Buffer(')!-%*$-ESS[SCC+#')[n]*4)

```

Try it online!

### How?

We use `sort()` on the array `['M','G','N','C','L']` with a callback function which ignores its arguments. Given the input \\$n\in\[0\dots15\]\\$, the result of the sort solely depends on a seed \\$q\_n=4k\_n\\$ where \\$k\_n\in\[33\dots91\]\\$ is the code of a printable ASCII character picked from a lookup string.

At each iteration, the expression `~(q /= 2) % 2` in the callback function returns either \\$0\\$ or \\$-1\\$.

*(1) This code relies on the fact that `sort()` is stable (which is now a requirement of the ECMAScript specification) and that the array entries are processed in a specific order. This may fail on older engines.*

# Answer
> 1 votes
# Python, 72 bytes

```
lambda a:oct(ord('ʜٔќڌˢ܊ќڡڄڄӄڄܐܐӠڠ'[int(a,2)]))[2:]+a[0]

```

Attempt This Online!

Takes in a Python string of 0s or 1s corresponding to the wins/losses as described above; outputs a string of length 5 containing the digits 0 through 5, where the mapping is

```
{"1":"N",
 "2":"G",
 "3":"C",
 "4":"L",
 "0":"M"}

```

---

# Python, 74 bytes

```
lambda a:ord('卜綌〴稈孲薢〴窼祂祂㋲祂蔶蔶㑚窪'[int(a,2)])

```

Attempt This Online!

A simpler earlier approach, using a different mapping.

# Answer
> 0 votes
# Charcoal, 50 bytes

```
Ｎθ≔⪪⪫⟦§59θC§38ＮG⎇Ｎ§47θ¹L0⎇ＮN2M¦M6N⟧ω²θＷ⁻θυ⊞υ⌈ι⭆υ⌈ι

```

Try it online! Link is to verbose version of code. Takes input in the order `C G L M`. Explanation: Each team is given a rating depending on whether it wins or loses, except if the LA Lakers win then their rating also depends on whether the LA Clippers win or not. It then remains to output the teams in descending order of rating.

```
Ｎθ

```

Input `C`.

```
≔⪪⪫⟦§59θC§38ＮG⎇Ｎ§47θ¹L0⎇ＮN2M¦M6N⟧ω²θ

```

Build up a string of teams and ratings. First is `C`, which has a rating of either `5` or `9`, then `G` has a rating of `3` or `8`, then `L` has a rating of `1`, `4` or `7`, then either `N` has a rating of `0` and `M` has a rating of `2` or `M` has a rating of `0` and `N` has a rating of `6`. The string is then split into pairs of characters ready for sorting.

```
Ｗ⁻θυ⊞υ⌈ι

```

Sort the teams in descending order of rating.

```
⭆υ⌈ι

```

Output just the teams without the ratings.

# Answer
> 0 votes
# Scala, 94 bytes

Modified from @97.100.97.109's answer.

---

Golfed version. Try it online!

```
def f(a:String):Int="卜綌〴稈孲薢〴窼祂祂㋲祂蔶蔶㑚窪"(Integer.parseInt(a, 2))

```

Ungolfed version. Try it online!

```
import scala.collection.mutable

object Main {
  def main(args: Array[String]): Unit = {
    val f: String => Int = a => "卜綌〴稈孲薢〴窼祂祂㋲祂蔶蔶㑚窪"(Integer.parseInt(a, 2))
    val translateTable: Map[Char, Char] = Map('2' -> 'N', '1' -> 'G', '3' -> 'C', '4' -> 'L', '0' -> 'M')

    println("MLGC | 56789")
    for (i <- 0 until 16) {
      val x = Integer.toBinaryString(i).reverse.padTo(4, '0').reverse
      val o = f(x)
      val ox = o.toString.map(c => translateTable.getOrElse(c, c)).mkString
      println(s"$x | $ox")
    }
  }
}

```

---
Tags: code-golf
---


title: Hankel transform of an integer sequence

text:
# Question
Title: Hankel transform of an integer sequence
A **Hankel matrix** is a square matrix in which each ascending skew-diagonal from left to right is constant, e.g.:

$$\begin{bmatrix} a & b & c & d \\ b & c & d & e \\ c & d & e & f \\ d & e & f & g \end{bmatrix}.$$

Given a sequence of integers \\$\\{a\_n\\}\\$, we can construct a sequence of Hankel matrices \\$\\{H\_n\\}\\$, where \\$H\_n\\$ is the \\$n\times n\\$ Hankel matrix whose \\$(i,j)\\$ entry is \\$a\_{i+j-1}\\$ (1-indexed). The **Hankel transform** of \\$\\{a\_n\\}\\$ is defined as the sequence of determinants of the matrices \\$\\{H\_n\\}\\$, i.e. \\$\\{\det(H\_n)\\}\\$.

For example, the fourth Hankel matrix of the Catalan numbers \\$\\{1,1,2,5,14,42,132,\dots\\}\\$ is

$$H\_4 = \begin{bmatrix} 1 & 1 & 2 & 5 \\ 1 & 2 & 5 & 14 \\ 2 & 5 & 14 & 42 \\ 5 & 14 & 42 & 132 \end{bmatrix},$$

and the determinant of \\$H\_1\\$, \\$H\_2\\$, \\$H\_3\\$, and \\$H\_4\\$ are all \\$1\\$. The Hankel transform of the Catalan numbers is therefore \\$\\{1,1,1,1,\dots\\}\\$.

## Task

Given a finite sequence of integers \\$\\{a\_n\\}\\$, output its Hankel transform \\$\\{\det(H\_n)\\}\\$.

The length of the input sequence is always an odd number. If the length of the input sequence is \\$2n-1\\$, then the length of the output sequence should be \\$n\\$.

Input and output can be in any reasonable format, e.g., a list, an array, a polynomial, a function that takes \\$i\\$ and returns the \\$i\\$th term (0-indexed or 1-indexed), etc.

You may also take the input sequence and an integer \\$i\\$, and output the \\$i\\$th term (0-indexed or 1-indexed) of the output sequence.

This is , so the shortest code in bytes wins.

## Testcases

```
[1,1,2,3,5,8,13] -> [1,1,0,0]
[0,1,2,3,4,5,6,7,8] -> [0,-1,0,0,0]
[1,0,-1,0,1,0,-1,0,1] -> [1,-1,0,0,0]
[1,2,5,14,42,132,429,1430,4862] -> [1,1,1,1,1]
[1,2,5,15,51,188,731,2950,12235] -> [1,1,1,1,1]
[1,2,6,20,70,252,924,3432,12870] -> [1,2,4,8,16]
[1,1,2,4,10,26,76,232,764,2620,9496] -> [1,1,2,12,288,34560]

```

# Answer
# APL (Dyalog Extended), 10 bytes

Anonymous tacit infix function taking 1-indexed \\$i\\$ as left argument and the sequence \\$\\{a\_n\\}\\$ as right argument.

```
⌂det∘↑⊣↑,/

```

Try it online!

`,/` sliding windows in \\$\\{a\_n\\}\\$ of size \\$i\\$

`⊣↑` take the first \\$i\\$ of those

`∘↑` combine those lists as rows into a matrix, then…

`⌂det` compute the determinant
> 9 votes

# Answer
# Jelly, 5 bytes

```
ṡḣṛÆḊ

```

Try it online!

Port of Adám's APL answer, so go upvote that. Sequence on the left, index on the right.

```
 ḣṛ      First i
ṡ        overlapping length-i slices of the sequence.
   ÆḊ    Determinant.

```
> 5 votes

# Answer
# Excel, ~~104~~ ~~99~~ 86 bytes

*With thanks to **JvdV** for the 18-byte save.*

```
=MAP(
    SEQUENCE(ROWS(A1#)/2+1),
    LAMBDA(r,MDETERM(INDEX(A1#,SEQUENCE(,r)+SEQUENCE(r)-1)))
)

```

Input is spilled range `#A1`.
> 5 votes

# Answer
# Wolfram Language (Mathematica), ~~64~~ ~~52~~ 49 bytes

```
Det@Take[HankelMatrix@#,,]~Table~{,Length@#/2+1}&

```

Try it online!

Thanks to @alephalpha ana @att!
> 4 votes

# Answer
# , ~~46~~ 42 bytes

*Edit: -4 bytes thanks to @Dominic van Essen.*

```
\(v,i)det(t(matrix(v,sum(v|1)+1,i)[1:i,]))

```

Attempt This Online!

Takes input as vector `v` of the sequence and index `i`.
> 4 votes

# Answer
# Vyxal, 4 bytes

```
lẎÞḊ

```

Try it Online!

Takes 1 based index and then the sequence. Port of *@Adàm*'s APL answer.

```
l    # overlapping groups of length i
 Ẏ   # take first i
  ÞḊ # determinant

```
> 4 votes

# Answer
# Factor \+ `math.matrices.extras`, 35 bytes

```
[ [ clump ] keep head determinant ]

```

Attempt This Online!

Port of Adám's APL answer.
> 3 votes

# Answer
# Wolfram Language(Mathematica), ~~72~~ 54 bytes

Saved 18 bytes thanks to the comment of @alephalpha

Try it online!

```
f=Det[Partition[#,k,1]~Take~k]~Table~{k,Length@#/2+1}&

```
> 3 votes

# Answer
# 05AB1E, ~~36~~ ~~34~~ 30 bytes

*Given a list of integers \\$\\{a\_n\\}\\$ and integer \\$i\\$, outputs its \\$i^{th}\\$ Hankel transform \\$\det(H\_{n,i})\\$* **(30 bytes)**

```
ŒIùI£ā<sUœε©2.ÆíÆ.±Xε®Nèè}«P}O

```

Try it online or verify all test cases.

*Given a list of integers \\$\\{a\_n\\}\\$, outputs its Hankel transform \\$\\{\det(H\_n)\\}\\$* **(~~36~~ 34 bytes)**

```
gÅÉε£ŒN>ùā<sUœε©2.ÆíÆ.±Xε®Nèè}«P}O

```

Inspired by *@Adàm*'s APL answer, but without any matrix builtins available..

Try it online or verify all test cases.

**Explanation (of the program with list output):**

Step 1: Create a list of matrices from the input-list:

```
g               # Push the length of the (implicit) input-list
 ÅÉ             # Pop and push a list of odd numbers <= this input-length
   ε            # Map over each odd value:
    £           #  Keep the first value amount of items from the (implicit) input-list
     Œ          #  Get all sublists of that list
      N>        #  Push the (0-based) map-index, and increase it by 1
        ù       #  Only keep the sublists of that length

```

Try just this first step online.

Step 2: Get the determinant of each matrix, which I've done before in 05AB1E for the *Determinant of an Integer Matrix* challenge:

```
 ā              #   Push a list in the range [1, matrix-length] (without popping)
  <             #   Decrease it by 1 to make the range [0, matrix-length)
   sU           #   Swap to get the matrix again, and pop and store it in variable `X`
     œ          #   Get all permutations of the [0, matrix-length) list
      ε         #   Inner map over each permutation:
       ©        #    Store the current permutation in variable `®` (without popping)
        2.Æ     #    Get all 2-element combinations of this permutation
           í    #    Reverse each inner pair
            Æ   #    Reduce it by subtracting
             .± #    And get it's signum (-1 if a<0; 0 if a==0; 1 if a>0)
       X        #    Push the matrix from variable `X`
        ε       #    Map over each of its rows:
         ®      #     Push the current permutation of variable `®`
          Nè    #     Get the value in the permutation at the current map-index
            è   #     And use that to index into the current matrix-row
        }«      #    After the map of rows: merge it together with the signum list
          P     #    And take the product of this entire list
      }O        #   After the map of permutations: sum all values

```
> 3 votes

# Answer
# JavaScript (ES10), 152 bytes

*-1 thanks to @tsh*

```
f=(a,b=[D=m=>q=+m||m.reduce((s,[v],i)=>s+(-1)**i*v*D(m.flatMap(([,...r])=>i--?[r]:[])),0)])=>1/D(b.map((_,y)=>b.map(_=>a[y++])))?[q,...f(a,[...b,0])]:[]

```

Try it online!

## Commented

### Determinant function

```
D = m =>            // m[] = matrix
+m ||               // if m[] is a non-zero singleton, return it
m.reduce((          // otherwise, for each row:
  s,                //   given the accumulator s
  [v],              //   and the first value v
  i                 //   of the i-th row
) =>                //
  s +               //   add to s
  (-1) ** i * v     //   either v or -v depending on the parity of i
  *                 //   multiplied by
  D(                //   the result of a recursive call:
    m.flatMap(      //     for each row:
      ([, ...r]) => //       remove the first value of each row
      i-- ? [r]     //       and remove the i-th row entirely
          : []      //
    )               //     end of flatMap()
  ),                //   end of recursive call
  0                 //   start with s = 0
)                   // end of reduce()

```

### Wrapper function

```
f = (               // f is a recursive function taking:
  a,                //   a[] = input list
  b = [0],          //   b[] = vector, initially of size 1
  q = D(            //   q = determinant of:
    b.map((_, y) => //     the Hankel matrix built by iterating twice
      b.map(_ =>    //     over the vector b[]
        a[y++]      //     and setting each cell at (x, y) to a[x + y]
      )             //
    )               //
  )                 //
) =>                //
1 / q ?             // if q is defined:
  [ q,              //   append q
    ...f(           //   followed by the result of a recursive call:
      a,            //     pass a[] unchanged
      [...b, 0]     //     add a dummy item to b[]
    )               //   end of recursive call
  ]                 //
:                   // else:
  []                //   stop

```
> 2 votes

# Answer
# Charcoal, ~~54~~ 46 bytes

```
≔…⁰ηη⊞υ⟦⟧Ｆη≔ΣＥυＥ⁻⎇﹪λ²⮌ηηκ⁺κ⟦μ⟧υＩ↨Ｅ⮌υΠＥι§θ⁺λμ±¹

```

Attempt This Online! Link is to verbose version of code. Takes the sequence and index as inputs. Explanation:

```
≔…⁰ηη⊞υ⟦⟧Ｆη≔ΣＥυＥ⁻⎇﹪λ²⮌ηηκ⁺κ⟦μ⟧υ

```

Generate all of the permutations of `[0..i)`. This is based on my answer to 1 to N column and row sums but tweaked to alternate between even and odd permutations.

```
Ｉ↨Ｅ⮌υΠＥι§θ⁺λμ±¹

```

For each permutation, add each element to its index and use that to index into the original sequence, then take the alternating sum of products, which is the determinant of the Hankel matrix as required.

Previous 54-byte version:

```
≔⟦ＥηＥη§θ⁺ιλ⟧θＦθ¿⊖ＬιＦＥ⊟ιＥι×Φμ⁻πλ⎇ν¹×Ｘ±¹⁺Ｌιλκ⊞θκ⊞υ⊟⊟ιＩΣυ

```

Try it online! Link is to verbose version of code. Takes the sequence and index as inputs. Explanation:

```
≔⟦ＥηＥη§θ⁺ιλ⟧θ

```

Construct the Hankel matrix `Hᵢ`.

```
Ｆθ¿⊖ＬιＦＥ⊟ιＥι×Φμ⁻πλ⎇ν¹×Ｘ±¹⁺Ｌιλκ⊞θκ⊞υ⊟⊟ιＩΣυ

```

Calculate its determinant using the following algorithm:

* Remove the last row and iterate over its elements. (This was the golfiest out of the first and last row and column, the ease of removing the last row making up for the slightly more complicated parity calculation.)
* For each element, create a new matrix by also removing its column, and multiply the first row of it with the element, but with the sign changed according to the parity of the element's original position.
* Take the sum of the determinants of the resulting trivial matrices.
> 2 votes

# Answer
# Julia 0.7, 26 bytes

```
a*i=det(a[(s=1:i)'.+.~-s])

```

Try it online!

Accepts sequence `a` and `i`th term.
> 2 votes

# Answer
# , ~~11~~ 10 bytes

*-1 byte thanks to @Bubbler!*

```
[-/ .*@{.[\

```

Try it online! Input format from Adàm's APL answer, but the form, although basically equivalent to his answer, was discovered independently when I wrote the below answer to work with only a sequence as input.

# , ~~28~~ 27 bytes

*-1 byte thanks to @Bubbler!*

```
([-/ .*@$[\)"{~1+i.@>.@-:@#

```

Try it online!

The novel bit in this approach is doing more work! :P

```
([-/ .*@{.[\)"{~1+i.@>.@-:@#
                        -:      half
                          @#    the input size
                     >.@        rounded up
                  i.@           range [0, ^)
                1+              range [1, ^]
                                this gives us all the valid matrix sizes
(           )" ~                (equivalent to Adàm's answer) applied at
              {                 equiv. 0 _
                                every possible matrix size and the entire input sequence

```
> 1 votes

---
Tags: code-golf, math, sequence, linear-algebra
---