title: `lol` is an ambigram, `dad` isn't

text:
# Question
Title: `lol` is an ambigram, `dad` isn't
Given a word, decide if it is an ambigram.

When rotated:

```
b > q
d > p
l > l
n > u
o > o
p > d
q > b
s > s
u > n
x > x
z > z

```

Assume only lowercase letters as input.

---

Test input:

```
this,
another,
lll,
lol,
dad,
dab,
dap,
wow,
ooi,
lollpopdodllol,

```

---

Ones That Should Return Truthy Values:

```
lll,
lol,
lollpopdodllol,

```

---

Note that **input and output** can be taken in any format (except for Standard Loopholes).

# Answer
# Factor \+ `flip-text`, 34 bytes

```
[ dup flip-text "ʃ""l"replace = ]

```

Attempt This Online!

Factor has a vocabulary for ʇxǝʇ ᵷuᴉddᴉʃɟ, but for some reason it turns `l` into `ʃ`, so I have to change it back.
> 18 votes

# Answer
# Python, ~~70~~ 69 bytes

*-1 byte thanks to Kyle G*

```
lambda s:[i*(i in b'losxz')or b'dbq0pnu0'[i%8]for i in s][::-1]==[*s]
```

Attempt This Online!

Accepts a bytes object as input.

## Explanation

`[... for i in s]` Build an array mapping each letter `i` of `s` to...

`i*(i in b'losxz')` ... `i`, if `i` is one of the letters that should remain unchanged, `or`...

`b'dbq0pnu0'[i%8]` ... its rotation. Since the rotatable letters have unique code points *mod 8*, we can use that to index into a string of possible rotations. Note that multiple letters may map to a given letter (e.g. `u` and `e` both map to `n`), but that's fine since only the rotatable letters will form a reversible map (e.g. `b`-\>`q`-\>`b`)

`[...][::-1]==[*s]` Reverse the new array and compare to the original string, unpacked into an array.
> 12 votes

# Answer
# Charcoal, 28 bytes

```
θ⟲Ｔ⁴≔⪫ＫＡωη⎚⁼θΦη№bdlnopqsuxzι

```

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

```
θ

```

Print the input string to the canvas.

```
⟲Ｔ⁴

```

Rotate the canvas by 180°, transforming the characters as required.

```
≔⪫ＫＡωη

```

Read the transformed rotated string back from the canvas.

Clear the canvas.

```
⁼θΦη№bdlnopqsuxzι

```

Compare the two strings, and check that all of the letters in the string were valid. (This check costs half of the byte-count, ugh.)
> 10 votes

# Answer
# Vyxal, 23 bytes

```
ka«ƛG₈₀2ǔvȯF±ɾF)ǍrT«ĿṘ⁼

```

Try it online or verify all test cases.

## How?

```
ka«×¢₇}Ẇ₇]↲βjEβ&ɾṗµ«ĿṘ⁼
ka                      # Push the lowercase alphabet
  «×¢₇}Ẇ₇]↲βjEβ&ɾṗµ«    # Push compressed string "bqapaaaaaaalauodbasanaaxaz"
                    Ŀ   # Transliterate the (implicit) input from the lowercase alphabet to that
                     Ṙ  # Reverse
                      ⁼ # Is it equal to the (implicit) input?

```

A port of Kevin's 05AB1E answer is 23 bytes as well:

# Vyxal, 23 bytes

```
Ḃ«ƛ≠ȧ‹«:£ḂĿka¥«g₴Ṡ«JFF=

```

Try it Online!
> 9 votes

# Answer
# JavaScript (ES6), 68 bytes

*Saved 1 byte thanks to @Shaggy*

Returns \\$0\\$ or \\$1\\$.

```
s=>[...s].map(c=>o=S[S.search(c)^1]+o,S=o='bqdpnulloossxxzz')|o==s+S

```

Try it online!
> 7 votes

# Answer
# (gcc): ~~171~~ 143 bytes

**Edit**: Thanks to ceilingcat for shortening the code to *~~171~~ 160 bytes* by using some nifty tricks! I did some simple cleanups to reduce it further to 143 bytes.

Hello, first time posting code golf here! Criticism is welcome. :)

```
d[]=L"q.p.......l.uodb.s.n..x.z";main(c,v)int**v;{for(char*s,*e;--c;s>e&&puts(v[c]))for(e=index(s=v[c],0);s<e--&d[*e-98]-*s+d[*s-98]==*e;)s++;}

```

Try it online (with explanation)

**Explanation**:

```

/**
 * Thanks to ceilingcat for shortening the code to 160 bytes by using some nifty tricks!
 * Did some cleanups to reduce it to 143 bytes.
 */

/**
 * Stores the flipped equivalent of a character in ASCII (sorry to anyone using EBCDIC)
 * in an array represented as a string. To get the index of the flipped character simply
 * subtract 98 (ASCII for 'b') from the ASCII value of the character.
 * '.' is just padding.
 */
d[]=L"q.p.......l.uodb.s.n..x.z";
main(c,v)int**v;{
        // Prints string if the 2 pointers crossed the middle which would
        // mean the second loop never exited (is a palindrome) at the end.
        for(char*s,*e;--c;s>e&&puts(v[c]))
                // 'e=index(s=v[c],0)' gets the pointers for the first and last
                // character of the string.
                // Exits the loop when character '*s' is not equal to flipped character '*e' and
                // vice versa or the 2 pointers cross at the middle of the string.
                for(e=index(s=v[c],0);s<e--&d[*e-98]-*s+d[*s-98]==*e;)
                        s++;
}

```
> 6 votes

# Answer
# J-uby, ~~153~~ ~~148~~ ~~56~~ ~~55~~ 53 bytes

```
:=~&(:~|~:tr&"pq#{?p*9}lpuodbpspnppxpp"&[*?a..?z]*'')

```

Try it online!

Just learning J-uby so this definitely is terrible.

Edit: I knew it. -95 bytes thanks to Steffan
> 5 votes

# Answer
# , 56 bytes

```
\(s)all(chartr("a-y","AqCpE-KlMuodbRsTnVWxY",s)==rev(s))
```

Attempt This Online!

Takes input as a vector of characters.

Translates all characters from the dictionary in the question to their counterparts and all others to uppercase equivalents (comparison is case sensitive in R, so those will break the equality).
> 5 votes

# Answer
# Regex (Perl / PCRE2 / Boost / Python`regex`), 65 bytes

```
^(([losxz])((?1)\2|)|b(?1)q|q(?1)b|d(?1)p|p(?1)d|n(?1)u|u(?1)n|)$

```

Try it online! \- Perl
Try it online! \- PCRE2
Try it online! \- Boost
Attempt This Online! \- Python `import regex`

This is a straight port of my answer to Numbers with Rotational Symmetry.

```
^              # Assert this is the start of the string
(              # Define (?1) recursive subroutine call
    ([losxz])  # \2 = match a char that is its own rotation
    ((?1)\2|)  # Optionally match (?1) followed by \2
|
    b(?1)q
|
    q(?1)b
|
    d(?1)p
|
    p(?1)d
|
    n(?1)u
|
    u(?1)n
|
               # Match an empty string at the center of an even-length string
)
$              # Assert this is the end of the string

```

If there just one more matched pair of distinct characters, e.g. `a``e`, another method would win by 3 bytes:

```
^(([losxz])((?1)\2|)|a(?1)e|e(?1)a|b(?1)q|q(?1)b|d(?1)p|p(?1)d|n(?1)u|u(?1)n|)$
^((?=([losxz]|a.*e|e.*a|b.*q|q.*b|d.*p|p.*d|n.*u|u.*n)(?<=(.))).((?1)\3|)|)$

```

But instead it loses by 1 byte:

```
^(([losxz])((?1)\2|)|b(?1)q|q(?1)b|d(?1)p|p(?1)d|n(?1)u|u(?1)n|)$
^((?=([losxz]|b.*q|q.*b|d.*p|p.*d|n.*u|u.*n)(?<=(.))).((?1)\3|)|)$

```

## Regex (Ruby), 72 bytes

```
^((?=([losxz]|b.*q|q.*b|d.*p|p.*d|n.*u|u.*n)(?<=(.))).(\g<1>\k<3+0>|)|)$

```

Try it online!

In this port, unlike the Perl/PCRE2/Boost/Python`regex` version, the alternative method wins by 5 bytes:

```
^(([losxz])(\g<1>\k<2+0>|)|b\g<1>q|q\g<1>b|d\g<1>p|p\g<1>d|n\g<1>u|u\g<1>n|)$
^((?=([losxz]|b.*q|q.*b|d.*p|p.*d|n.*u|u.*n)(?<=(.))).(\g<1>\k<3+0>|)|)$

```

## Regex (.NET), 75 bytes

```
^((?=([losxz]|b.*q|d.*p|n.*u|p.*d|q.*b|u.*n)(?<=(.))).?)+(?<-3>\3)*(?(3)^)$

```

Try it online!

## Regex (Perl / PCRE / .NET), 79 bytes

```
^((?=([losxz]|b.*q|q.*b|d.*p|p.*d|n.*u|u.*n)(?<=(.))).?(?=.*(\3(?(4)\4))))*\4?$

```

Try it online! \- Perl
**Try it online! \- PCRE1**
Try it online! \- PCRE2
Try it online! \- .NET

## Regex (Perl / PCRE / Java / .NET), 86 bytes

```
^((?=([losxz]|b.*q|q.*b|d.*p|p.*d|n.*u|u.*n)(?<=(.))).?(?=.*(\3(\6\4|(?!\6))())))*\4?$

```

Try it online! \- Perl
Try it online! \- PCRE1
Try it online! \- PCRE2
**Try it online! \- Java**
Try it online! \- .NET
> 4 votes

# Answer
# PARI/GP, 70 bytes

s->Vecrev(s)==[Vec("`q`p```````l`uodb`s`n``x`z")[i-96]|i<-Vecsmall(s)]

Attempt This Online!
> 3 votes

# Answer
# APL+WIN, ~~44~~ 37 bytes

-7 bytes thanks to OVS

Prompts for text

```
t≡⌽'qpluodbsnxz '['bdlnopqsuxz'⍳t←,⎕]

```

Try it online! Thanks to Dyalog Classic APL
> 3 votes

# Answer
# 05AB1E, 23 bytes

```
Â.•1â‹ƒ•©Â‡A®.•(ÖÆ•«ммQ

```

Try it online or verify all test cases.

A port of *@Steffan*'s Vyxal answer is 23 bytes as well:

```
ÂA.•1ηλ¥nô[˜ζÕPζeí=Ω•‡Q

```

Try it online or verify all test cases.

**Explanation:**

```
Â          # Bifurcate the (implicit) input-string, short for Duplicate & Reverse
 .•1â‹ƒ•   # Push the compressed string "bdunpq"
  ©        # Store it in variable `®` (without popping)
   Â       # Bifurcate it
    ‡      # Transliterate all "bdunpq" to "qpnudb"
 A         # Push the lowercase alphabet
  ®        # Push string `®`
   .•(ÖÆ•« # Append compressed string "losxz"
    м      # Remove all those characters from the alphabet: "acefghijkmrtvwy"
     м     # Remove all those characters from the modified input
      Q    # Check if it's equal to the input-string
           # (after which the result is output implicitly)

Â          # Bifurcate the (implicit) input-string, short for Duplicate & Reverse
 A         # Push the lowercase alphabet "abcdefghijklmnopqrstuvwxyz"
  .•1ηλ¥nô[˜ζÕPζeí=Ω•
           # Push the compressed string  "bqapaaaaaaalauodbasanaaxaz"
   ‡       # Transliterate the alphabet to these characters
    Q      # Check if it's equal to the input-string
           # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•1â‹ƒ•` is `"bdunpq"`; `.•(ÖÆ•` is `"losxz"`; and `.•1ηλ¥nô[˜ζÕPζeí=Ω•` is `"bqapaaaaaaalauodbasanaaxaz"`.
> 3 votes

# Answer
# Rust, ~~135~~ 130 bytes

```
let m="bqdpnulloossxxzz";let f=|s:&str|!s.chars().zip(s.chars().rev()).any(|(a,b)|m.find(a).or(Some(99))!=m.rfind(b).map(|x|x^1));

```

I'm pretty new to golfing so I hope I did it alright.

I'm still pretty unhappy with how verbose the code to fix the options is.
> 3 votes

# Answer
# C (gcc), 835 bytes

I never was very good at golf...

```
#include "string.h"
#include "stdio.h"
char z[8][2] = {{'b','q'},{'d','p'},{'n','u'},{'l','l'},{'o','o'},{'s','s'},{'x','x'},{'z','z'},};
void main(int argc, char *argv[])
{
    int n = argc-1;
    for (int x = 1; x <= n; x++){
        int p = 0;
        int l = strlen(argv[x]);
        char r[l+1];
        for (int i = l; i > 0; i--){
            char c = argv[x][i-1];
            int v = 0;
            for (int a = 0; a < 8; a++){
                if (c == z[a][0]){
                    c = z[a][1];
                    v = 1;
                } else if (c == z[a][1]){
                    c = z[a][0];
                    v = 1;
                }
            }
            if (!v) {p = 1;}
            r[l-i] = c;
        }
        r[strlen(argv[x])+1] = '\0';
        printf("%d\n", memcmp(r, argv[x], l) == 0 && p == 0);
    }
}

```

Try it online!

**Original, much more readable version:**

# C (gcc), 1238 bytes

```
#include "string.h"
#include "stdio.h"

char letters_to_rotate[8][2] = {
{'b', 'q'},
{'d', 'p'},
{'n', 'u'},
{'l', 'l'},
{'o', 'o'},
{'s', 's'},
{'x', 'x'},
{'z', 'z'},
};

void main(int argc, char *argv[])
{
    int num_inputs = argc-1;
    for (int x = 1; x <= num_inputs; x++){
        int invalid_char_present = 0;
        int inputlength = strlen(argv[x]);
        char rotated[inputlength+1];
        for (int i = inputlength; i > 0; i--){
            char c = argv[x][i-1];
            int valid_char = 0;
            for (int a = 0; a < 8; a++){
                if (c == letters_to_rotate[a][0]){
                    c = letters_to_rotate[a][1];
                    valid_char = 1;
                }
                else if (c == letters_to_rotate[a][1]){
                    c = letters_to_rotate[a][0];
                    valid_char = 1;
                }
            }
            if (!valid_char) {invalid_char_present = 1;}
            rotated[inputlength-i] = c;
        }
        rotated[strlen(argv[x])+1] = '\0';
        if (memcmp(rotated, argv[x], inputlength) == 0 && invalid_char_present == 0){
            printf("%s: True\n", argv[x]);
        } else {
            printf("%s: False\n", argv[x]);
        }
    }
}

```

Try it online!
> 3 votes

# Answer
# T-SQL, 84 bytes

Returns 1 when palindrome, otherwise 0

```
PRINT IIF(translate(@,'bqdpnu','qbpdun')<>reverse(@)or
@ like'%[^qbpdunolsxz]%',0,1)

```

**Try it online**
> 3 votes

# Answer
# Oracle SQL, 68 bytes

```
o=reverse(translate(o,'bdlnopqsuxzacefghijkmnrstuvwy','qpluodbsnxz'))

```

Tested with

```
with w as (
   select column_value o
   from
   ku$_vcnt(
   'this',
   'another',
   'lll',
   'lol',
   'dad',
   'dab',
   'dap',
   'wow',
   'ooi',
   'lollpopdodllol'
))
select o from w
where
   o=reverse(translate(o,'bdlnopqsuxzacefghijkmnrstuvwy','qpluodbsnxz'));

```
> 3 votes

# Answer
# Bash, 71 bytes

```
f()(a=bdlnopqsuxz;[ "`echo $1|tr $a qpluodbsnxz|tr -dc $a|rev`" = $1 ])

```

Try it online!

---

Using a more compact tr command as inspired by pajonk's answer:

# Bash, 58 bytes

```
f()([ "`echo $1|tr a-y AqCpE-KlMuodbRsTnVWxY|rev`" = $1 ])

```

Try it online!
> 3 votes

# Answer
# PowerShell, ~~72~~ ~~68~~ 51 bytes

```
!(($s=$args)|?{'dbqspn  x z l uo'[$_%16]-$s[--$i]})

```

Try it online!

The script assumes an input does not contains space chars. I guess It is good constraint for a word.

The script takes a splatted string and performs double check for each symbol from the string.

The algorithm for the hash string `dbqspn x z l uo` is: Place an ambigram char at the position (ASCII % 16).

| Source char | ASCII | % 16 | Ambigram char |
| --- | --- | --- | --- |
| p | 112 | 0 | d |
| q | 113 | 1 | b |
| b | 98 | 2 | q |
| s | 115 | 3 | s |
| d | 100 | 4 | p |
| u | 117 | 5 | n |
| x | 120 | 8 | x |
| z | 122 | 10 | z |
| l | 108 | 12 | l |
| n | 110 | 14 | u |
| o | 111 | 15 | o |
> 3 votes

# Answer
# Retina 0.8.2, 56 bytes

```
$
¶$`
T`b\dl-qsuxzl`q\p\l_u\o\dbsnxz_`^.+
+`(.)¶\1
¶
^¶$

```

Try it online! Link includes test cases. Explanation:

```
$
¶$`

```

Duplicate the input.

```
T`b\dl-qsuxzl`q\p\l_u\o\dbsnxz_`^.+

```

Individually rotate the characters of the first copy, but delete characters that aren't rotatable. (`d`, `l`, `o` and `p` need to be quoted when not used as part of a range.)

```
+`(.)¶\1
¶

```

Compare the last character of the first copy with the first character of the second, removing both if they are equal. Repeat until either they don't match or there aren't any left.

```
^¶$

```

If there aren't any left then the original input was a rotational palindrome.
> 2 votes

# Answer
# K (ngn/k), 30 bytes

```
{x~|v(|v:"lnopqsxzxsbdoul")?x}

```

Try it online!

I took the shortest ambigram which contained all the possible characters and made it into a lookup string: locate where each character of the input is in the string, and then take one character from the reversed version to construct the rotated character. Finally, reverse it and compare against the original input.
> 2 votes

# Answer
# JavaScript, 88 bytes

```
s=>s==[...s].map(x=>'losxz'.includes(x)?x:(r='budpnq')[5-r.indexOf(x)]).reverse().join``

```

Try it online!
> 1 votes

# Answer
# Stax, 23 bytes

```
Ç╥Vⁿ2n♣¿æ∞╙♥>5H╜ÜN¡¼}╝î

```

Run and debug it
> 1 votes

# Answer
# Perl 5 `-pal`, 52 bytes

```
y/bqdpunloszx//dc;y/bqdpun/qbpdnu/;$_="@F"eq reverse

```

Try it online!
> 1 votes

# Answer
# Scala, 118 bytes

Golfed version. Try it online!

```
def f(s:Seq[Byte])=s.map(i=>if("losxz".contains(i.toChar))i else"dbq0pnu0".charAt(i%8).toByte).reverse.sameElements(s)

```

Ungolfed version.

```
object Main {

  def f(s: Array[Byte]): Boolean = {
    val result = s.map(i => if ("losxz".contains(i.toChar)) i else "dbq0pnu0".charAt(i % 8).toByte).reverse
    result.sameElements(s)
  }

  def main(args: Array[String]): Unit = {
    println(f("bq".getBytes))               // true
    println(f("lol".getBytes))              // true
    println(f("lollpopdodllol".getBytes))   // true
    println(f("dad".getBytes))              // false
    println(f("wow".getBytes))              // false
    println(f("eon".getBytes))              // false
    println(f("pppd".getBytes))             // false
  }
}

```
> 0 votes

# Answer
# Zsh, 41 bytes

```
<<<${1//$(tr "bdnpqu" "qpudbn"<<<$1|rev)}

```

Try it online!

Truthy/ambigram: returns empty string. Otherwise, the result is non-empty.
> 0 votes

---
Tags: code-golf, string, decision-problem
---


title: Is it stuck in a counting loop?

text:
# Question
Title: Is it stuck in a counting loop?
Given a list of non-negative integers the function \\$f\\$ replaces every integer with the number of identical integers preceding it (not necessarily contiguously). So

```
f [1,1,2,2,1,3,3] = [1,2,1,2,3,1,2]

```

We will say that a list, \\$X\\$, is *in a loop* if there is some positive integer \\$n\\$ such that \\$f^n X = X\\$. That is you can apply the function to \\$X\\$ some number of times to arrive at \\$X\\$.

Your task is to take a list as input and determine if that list is in a loop. You should output one of two consistent values, one if it is in a loop and the other if it is not.

This is code-golf. The goal is to minimize the size of your source code as measured in bytes.

---

A note: There are other ways to formulate this condition.

## Test cases

```
[2,2] -> False
[1,1] -> True
[1,2] -> True
[1,1,2,2,3,3] -> True
[1,2,3,1,4,2,5,3] -> True
[1,2,1,3,1,2] -> True
[1,2,1,3,1,3,4,6] -> False
[1,2,2,3] -> False

```

# Answer
# , 14 bytes

```
-:(1#.]=]\)^:2

```

Try it online!

This uses the fact I conjectured in the comments, which WheatWizard confirmed is true:

> It looks like the true ones all have a cycle length of 2, and the false ones converge to something with a cycle length of 2 also, just not including the original input.

So, we simply apply the transformation twice, and check if the result matches the input.
> 2 votes

# Answer
# Jelly, 7 bytes

```
ċṪ‘ƊƤ⁺⁼

```

Try it online!

A monadic link taking a list of integers and returning 1 if a loop and 0 if not. Uses @Jonah’s observation that we only need to apply the transformation twice and check whether we get back to where we started.

## Previous solution, 9 bytes

```
ċṪ‘ƊƤ⁺ÐL⁼

```

Try it online!

A monadic link taking a list of integers and returning 1 if a loop and 0 if not.

## Explanation

```
ċṪ‘ƊƤ     | For each prefix, count the number of times the popped tail appears and then increment by 1
     ⁺ÐL  | Repeat this again until a value is seen for the second time, returning the last value that has not been seen before
        ⁼ | Check whether equal to the original argument

```
> 1 votes

# Answer
# JavaScript (ES6), 59 bytes

Naive implementation. Returns a Boolean value.

```
a=>(g=a=>g[a]?a+""==b:g(g[a]=a.map(p=v=>p[v]=-~p[v])))(b=a)

```

Try it online!

### Commented

```
a => (                // a[] = input array
  g =                 // g is a recursive function taking ...
  a =>                // ... the current state a[] of the array
  g[a] ?              // if we've encountered a[] before:
    a + "" == b       //   stop and return true if this is the original array
  :                   // else:
    g(                //   do a recursive call:
      g[a] =          //     mark a[] as encountered
      a.map(p =       //     p is on object used to count 'preceding' values
      v =>            //     for each value v in a[]:
        p[v] = -~p[v] //       increment p[v]
      )               //     end of map()
    )                 //   end of recursive call
)(b = a)              // initial call to g with a[] saved in b[]

```

---

# JavaScript (ES6), 45 bytes

Optimized version using Jonah's conjecture.

```
a=>a+""==(g=a=>a.map(p=v=>p[v]=-~p[v]))(g(a))

```

Try it online!

---

# JavaScript (ES6), 41 bytes

Further optimized, knowing that we're actually looking for a stackable sequence as pointed out by xnor. This is basically a 1-indexed version of my answer to the other challenge.

```
a=>a.every(k=>a[a[-k]=-~a[-k--],-k]--|!k)

```

Try it online!
> 0 votes

# Answer
# Python3, 115 bytes

```
def f(a):
 q=[a]
 while(l:=[sum(k==j for k in q[-1][:i+1])for i,j in enumerate(q[-1])])not in q:q+=[l]
 return l==a

```

Try it online!
> 0 votes

---
Tags: code-golf, array, decision-problem
---


title: Yin-Yang Table Generator

text:
# Question
Title: Yin-Yang Table Generator
I want an n\*n table that is filled with black or white and the following conditions are satisfied in it:

1. All cells of a 2\*2 square in this table should not be the same color.
2. All black and white cells must be connected horizontally or vertically.

Acceptable examples:

*Can anyone design a function that takes n as input and generates an acceptable n\*n random table?*

* It is not necessary for the output to be an image, we can use symbols such as 0 and 1 in a two-dimensional array to display the result.

# Answer
> 2 votes
# Python 3, 45 bytes

```
lambda n:["1"*n]+[("10"*n)[:n]]*(n-2)+["0"*n]

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog Unicode), 12 bytes

Anonymous tacit prefix function, returning a matrix of 0s and 1s.

```
⊢↑1⍪2↓,⍨⍴2|⍳

```

Try it online!

**i**ndices 1…n

`2|` division remainder for those, when divided by 2 (gives `[1,0,1,0,…]`)

cyclically reshape into an array of the following dimensions:

`,⍨` the self-concatenation of n, i.e. `[n,n]`

`2↓` drop the first two rows

`1⍪` prepend a row of 1s

take the following number of rows, padding with all-0 rows:

n (lit. the identity function applied to n)

# Answer
> 1 votes
# 05AB1E, 10 bytes

Same output (based on input) on each run:

```
Å1āÉI<.Da)

```

Port of *@Somebody*'s Python answer.

Try it online or verify the first ten sizes.

# 05AB1E, 73 bytes

Random valid output on each run:

```
1ÝIãIãʒ€ü2ü2εøOO4Ö≠}˜P}ʒD_‚ε©˜ƶ®gäΔ2Fø0δ.ø}2Fø€ü3}®*εεÅsyøÅs«à}}}˜Ùg<}P}Ω

```

Try it online. (Slightly modified `ʒ...}Ω` to `.r.Δ...` to speed it up, but unfortunately it'll still time out for \\$n\geq4\\$.)

**Explanation:**

```
Å1            # Push a list of the (implicit) input amount of 1s
  ā           # Push a list in the range [1,length] (without popping)
   É          # Check for each whether it's odd: [1,0,1,0,1,0,...]
    I<        # Push the input-1
      .D      # Duplicate the [1,0,1,0,1,0,...]-list that many times
        a     # Change the top list to a list of 0s instead with an is_letter check
         )    # Wrap all lists on the stack into a list
              # (after which this matrix is output implicitly as result)

```

Step 1: Create a list of all possible input by input matrices with `0`s and `1`s:

```
1Ý            # Push pair [0,1]
  Iã          # Take the cartesian power of the input to get all input-sized lists using
              # 0s and 1s
    Iã        # And again, to get all possible matrices

```

Step 2: Filter this list of matrices to keep all where each overlapping 2x2 block contains at least one `1` and at least one `0`:

```
ʒ             # Filter this list of matrices by:
 €ü2ü2εø      #  Get all overlapping 2x2 blocks:
 €            #   Map over each row:
  ü2          #    Get its overlapping pairs
    ü2        #   Get the overlapping lists of lists of pairs
      ε       #   Map over each:
       ø      #    Zip/transpose; swapping rows/columns
 OO           #    Sum each inner 2x2 block
   4Ö≠        #    Check for each sum whether it's NOT divisible by 4
              #    (aka it's 1, 2, or 3, and NOT 0 or 4)
      }       #   Close the map
       ˜      #   Flatten this matrix of 2x2 block sum checks
        P     #   Check that all are truthy by taking the product
}             # Close the filter

```

Step 3: Filter it again to keep those where all matrices where both the `1`s and `0`s form a single island:

```
ʒ             # Filter this list of matrices again:
 D            #  Duplicate this matrix
  _           #  Invert each 0s to 1 and vice-versa in the copy
   ‚          #  Pair the two inverted matrices together
 ε            #  Map over this pair:
  ©           #   Store the current matrix in variable `®` (without popping)
   ˜          #   Flatten it to a single list
    ƶ         #   Multiply each value by its 1-based index
     ®gä      #   Convert it back to a matrix of size `®`
  Δ           #   Loop until the result no longer changes to flood-fill:
   2Fø0δ.ø}   #    Add a border of 0s around the matrix:
   2F     }   #     Loop 2 times:
     ø        #     Zip/transpose; swapping rows/columns
       δ      #     Map over each row:
      0 .ø    #      Add a leading/trailing 0
   2Fø€ü3}    #    Convert it into overlapping 3x3 blocks:
   2F    }    #     Loop 2 times again:
     ø        #      Zip/transpose; swapping rows/columns
      €       #      Map over each inner list:
       ü3     #       Convert it to a list of overlapping triplets
   ®*         #    Multiply each 3x3 block by the value in matrix `®`
              #    (so the 0s remain 0s)
   εεÅsyøÅs«à #    Get the largest value from the horizontal/vertical cross of each
              #    3x3 block:
   εε         #     Nested map over each 3x3 block:
     Ås       #       Pop and push its middle row
       y      #       Push the 3x3 block again
        ø     #       Zip/transpose; swapping rows/columns
         Ås   #       Pop and push its middle rows as well (the middle column)
           «  #       Merge the middle row and column together to a single list
            à #       Pop and push its maximum
   }}         #     Close the nested maps
  }           #   Close the changes-loop
   ˜          #   Flatten the flood-filled matrix
    Ù         #   Uniquify this list
     g<       #   Pop and push its length-1
              #   (only 1 is truthy in 05AB1E, so this checks if two islands remain)
 }            #  Close the map
  P           #  Check that both are truthy, for the regular and inverted matrix
}             # Close the filter
 Ω            # Pop and push a random matrix from this filtered list
              # (which is output implicitly as result)

```

---
Tags: code-golf, random, binary-matrix
---


title: Just another traffic jam!

text:
# Question
Title: Just another traffic jam!
One lane is closed, the vehicles have to thread their way in according to the zip-lock system: One car from one lane, the next car from the other lane, always taking turns.

**Input**: Two vehicle queues, represented e.g. as strings, in which short cars are represented by individual symbols, lorries by several identical symbols. The queues may be of different lengths and may even be empty. Symbols may appear more than once. If your language does not support strings, you can also use two lists (see second set of test data) or other forms of input as long as the purpose of the task is not lost.

**Output**: A vehicle queue in the same representation. The traffic jam is long enough, so at least the source code should be as short as possible!

**Test data:**

```
Nzzll,iaaee                   --> Nizzaallee
aabcddddeeeee,1112345555611   --> aa111b2c3dddd4eeeee5555611
foo+bar ooooooooooooooooooooo --> fooooooooooooooooooooooo+bar
feeeuve553iiiiiiiiiii,        --> feeeuve553iiiiiiiiiii
UvtMCaegIYuiet,poeyhllnefoLkI --> UpvoteMyChallengeIfYouLikeIt

```

**Test data for languages that do not support strings:**

```
[1,3,5,7,9,11],[2,4,6,7,7,7,7,7] --> [1,2,3,4,5,6,7,7,7,7,7,7,9,11]
[4,9,9,13,13],[41,41,41,1,11,44] --> [4,41,41,41,9,9,1,13,13,11,44]
[] [2,6,4,3,3,56,8,5,4,3]        --> [2,6,4,3,3,56,8,5,4,3]

```

# Answer
# Jelly, 3 bytes

```
ŒgZ

```

A full program that accepts a pair of the two strings as the first argument and prints the resulting single lane.

**Try it online!**

### How?

```
ŒgZ - Main Link: pair of lists of characters
Œg  - group runs of equal elements of each
  Z - transpose
    - implicit, smashing print

```
> 9 votes

# Answer
# Ruby, 33 bytes

```
f=->a,b{a[/(.)\1*/]?$&+f[b,$']:b}

```

Try it online!

### How it works:

If the first queue is not empty, extract the first vehicle, then exchange the queues, and repeat.

If the first queue is empty, return the whole second queue.
> 6 votes

# Answer
# Wolfram Language (Mathematica), 26 bytes

```
Flatten[Split/@#,{2,1,3}]&

```

Try it online!

Input and output lists of characters.
> 4 votes

# Answer
# 05AB1E, 5 bytes

```
€γõζS

```

Input as a pair of strings; output as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
€      # Map over both strings in the (implicit) input-pair:
 γ     #  Split them into equal adjacent groups of substrings
   ζ   # Zip/transpose this list of lists,
  õ    # using an empty string ("") as filler for unequal length lists
    S  # Convert this list of pairs of strings to a flattened list of characters
       # (which is output implicitly as result)

```
> 4 votes

# Answer
# Uiua, 16 bytes

```
⊐/⊂♭⍉⬚∘⊟□[]∩⊜□∩.

```

Try it!

Takes lists of postive integers as input (because this saves a few bytes over strings).

* `∩.` duplicate both inputs

* `∩⊜□` split both into contiguous equal elements

* `⬚∘⊟□[]` couple lists to matrix, filling with boxed empty list

* transpose

* deshape

* `⊐/⊂` join all
> 4 votes

# Answer
# , 32 bytes

```
[:;(,/:,&(#\))&(<;.1~2~:/\'_'&,)

```

Attempt This Online!

The 2nd part of this is the only interesting insight:

* `[:;...&(<;.1~2~:/\'_'&,)` This is the preprocessing step that breaks the lists down into the grouped sections. A standard J idiom which is unfortunately a bit verbose. I could save two bytes by using integers instead of strings as input.
* `,/:,&(#\)` The main logic. Since we can't zip uneven lists in J using `,.`, we just cat the lists `,` and then sort them `/:` by `1..n` catted with `1..m` (where `n` and `m` are the two list lengths). This works because sort is stable.
> 3 votes

# Answer
# JavaScript (Node.js), ~~52~~ 48 bytes

```
f=([c,...a],b)=>c?[c,...c==a[0]?f(a,b):f(b,a)]:b

```

Attempt This Online!

Array IO, though inputting string usually work
> 3 votes

# Answer
# Charcoal, 35 bytes

```
Ｆ²⊞υ⪪⮌Ｓ¹Ｗ∧⌊υ⊟§υ⁰«ι¿⌕⮌§υ⁰ι≔⮌υυ»Ｗ⌈υ⊟ι

```

Try it online! Link is to verbose version of code. Explanation: Seems to be a similar idea to @l4m2's answer, but it just took me that long to think of it after writing my Retina answer that he got there first.

```
Ｆ²⊞υ⪪⮌Ｓ¹

```

Input the two strings, reversing them and splitting them into characters so that they can be processed more easily.

```
Ｗ∧⌊υ⊟§υ⁰«

```

Until one queue is empty, remove the next character from the first queue, ...

```
ι

```

... print it, and...

```
¿⌕⮌§υ⁰ι

```

... if the next character in this queue is from a different vehicle, then...

```
≔⮌υυ

```

... switch the queues.

```
»Ｗ⌈υ⊟ι

```

Output the remaining vehicles from the other queue.
> 3 votes

# Answer
# C (clang), ~~61~~ 60 bytes

```
f(a,b)char*a,*b;{*a?putchar(*a)-*++a?f(b,a):f(a,b):puts(b);}

```

Try it online!

* saved 1 Byte thanks to @l4m2
> 3 votes

# Answer
# Perl 5 \+ `-p0`, 29 bytes

```
1while s/^(.)\1*/!print$&/gem
```

Try it online!
> 3 votes

# Answer
# Vyxal `s`, 22 bitsv2, 2.75 bytes

```
vĠ∩

```

Try it Online!

Bitstring:

```
1000110100011111100101

```

The footer inserts a newline for test case purposes. Port of the jelly answer.

## Explained

```
vĠ∩
vĠ   # Vectorise group-by
  ∩  # Transpose

```

Created with the help of Luminespire.
> 2 votes

# Answer
# JavaScript (ES11), 62 bytes

Expects `([str1, str2])`.

```
a=>[...a+a].map((_,i)=>a[i&1].match(/(.)\1*/g)?.[i>>1]).join``

```

Attempt This Online!
> 2 votes

# Answer
# Retina 0.8.2, 26 bytes

```
O$#`.(?<=(\2*(.))+)
$#1
¶

```

Try it online! Takes input on separate lines but link is to test suite that splits on commas for convenience. Explanation:

```
O$#`.(?<=(\2*(.))+)
$#1

```

Sort each character by its vehicle index in its queue. This is a stable sort so that the first vehicle of the first queue sorts first followed by the first vehicle of the second queue etc. The newline is not considered for the sort but it's used by the lookbehind to find the front of the second queue.

The vehicles were sorted without regard for the placement of the newline which is just unnecessary at this point.
> 2 votes

# Answer
# Noulith, 97 bytes

```
f:=\a,b->if (a.len<1)b else (c,d:=a.first,a.tail;c$if (d.len>0 and c==d.first)f(d,b)else f(b,d))

```

Try it online!

### Explanation

```
f:=\a,b ->                  # recursive function
if (a.len<1) b              # return early when first input is empty
else (                      # otherwise
c,d:=a.first,a.tail;        # get first c(h)ar and the rest
c $                         # concat the first c(h)ar with
if (d.len>0 and c==d.first) # if next is a truck
f(d,b)                      # the rest of the truck
else f(b,d))                # otherwise the next lane

```
> 2 votes

# Answer
# BQN, 12 bytes

```
∾∾○(+`»⊸≠)⊔∾

```

Try it online!

Input `F`. Assumes the leading character isn't a null character.

```
                            traffic jaaam
           ∾    join        trafficjaaam
          ⊔     group by
    +`»⊸≠        vehicle #s
 ∾○              (joined)   123445612223
                            tj raaa am ff i c
∾               join groups tjraaaamffic

```

Flattened group-by (`∾⊔`) is a little shorter than sort-by (`⍋⊸⊏`).
> 2 votes

# Answer
# x86-64 machine code, 21 bytes

```
AA 3A 06 74 03 48 87 D6 AC 84 C0 75 F3 52 5E 3A 06 A4 75 FB C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string, and in RSI and RDX, addresses of the inputs, as null-terminated byte strings. The starting point is after the first 8 bytes.

In assembly, rearranged for easier reading:

```
f:  lodsb           # Load a byte from address RSI into AL, advancing the pointer.
    test al, al     # Check the value of that byte.
    jnz r           # Jump if it's nonzero.

```

```
(This section actually comes first.)
r:  stosb           # Write that byte to the output string, advancing the pointer.
    cmp al, [rsi]   # Compare that byte to the next byte in the string.
    je f            # Jump if they are equal.
    xchg rsi, rdx   # (Otherwise) Swap the pointers (in RSI and RDX).
(From here, continue at the beginning.)

```

```
(When the byte is zero, continue to here.)
    push rdx; pop rsi   # Transfer the other pointer from RDX to RSI.
r1: cmp al, [rsi]       # Compare the value at that address to AL, which is 0.
    movsb               # Write the byte from address RSI to the output string,
                        #  advancing both pointers.
    jne r1              # Jump back if the byte was not equal to 0.
    ret                 # Return.

```
> 1 votes

# Answer
# Go, 133 bytes

```
func f(a,b string)string{if len(a)<1{return b}
c,a:=a[0],a[1:]
if len(a)>0&&c==a[0]{return string(c)+f(a,b)}
return string(c)+f(b,a)}

```

Attempt This Online!

Recursive function.

### Explanation

```
func f(a,b string)string{
if len(a)<1{return b}    // return early when first input is empty
c,a:=a[0],a[1:]          // get the current c(h)ar
if len(a)>0&&c==a[0]{    // if the next c(h)ar is the same...
return string(c)+f(a,b)} // recurse to get the truck
return string(c)+f(b,a)} // otherwise move on to the next lane

```
> 1 votes

# Answer
# Bash, 103 99 bytes

The function. Input is parameters 1 and 2. Output is variable o.

```
f(){
o=
while [ "$1$2" ]
do
c=`expr "$1" : "${1::1}*"`
o+=${1::$c}
set -- "$2" "${1:$c}"
done
}

```

Try it online!

Uses `expr` to determine the repeats of the first character, "outputs" the repeats, swaps the strings, and repeats until empty.

Due to limitations in `expr`, it can't handle characters `[`, `\`, or `^`, or trailing single parentheses. All of these cause infinite loops, possibly with errors spewing. See the TIO for details.

I could save two characters by removing the quotes on the while statement, but this would make space not be a valid character.
> 1 votes

# Answer
# Python, ~~160~~ 159 bytes

```
from itertools import*
c,g,l=chain.from_iterable,groupby,list;f=lambda a,b:''.join(c(c(zip_longest([l(t)for r,t in g(a)],[l(t)for r,t in g(b)],fillvalue=''))))

```

Attempt This Online!

Edit 1: removed an extra space
> 1 votes

# Answer
# Desmos, 96 bytes

```
C=sgn(L[2...]-L)^2
g(L)=∑_{n=1}^{[1...C.count]}C[n]
f(A,B)=sort(join(A,B),join(0,g(A),0,g(B)))

```

Ok this can probably be improved somehow but for now this is good enough.

Try It On Desmos!

Try It On Desmos! - Prettified
> 1 votes

# Answer
# GNU sed `-E`,  ~~63~~  59 bytes

The first approach did build a third string behind the two strings to be merged, but it turned out it's cheaper to invest in introducing a mark `_` in the first string marking the position where to insert the chars from the second string:

```
s/^/_/
:1
s/_((.?)\2*)(.*,)((.?)\5*)/\1\4_\3/
/_,/!b1
s///g

```

The magic mainly takes place in the third line: The ERE `(.?)\2*` (and the same with `5`) match zero or more occurences of the same character (using a backreference, which is not required for ERE by POSIX, but supported by the GNU implementation. Thus, we move those matches in front of the `_`.

We can't use `t` for looping, because an empty `s`ubstitution is always possible, but that's not too expensive, because the addess pattern `_,` can be reused for removing.

Try it online!
> 0 votes

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


# Question
Title: Translate the keitai input method into Japanese hiragana
The keitai input method is a method for writing Japanese kana on a 12-key phone keypad. Similar to Western keypads, each kana is assigned to a key; when the key is pressed multiple times, it cycles between all kana assigned to that key.

You will be using the following key-kana assignments, with this order of kana (based on this layout):

| Key | Kana |
| --- | --- |
| 1 | あいうえお |
| 2 | かきくけこ |
| 3 | さしすせそ |
| 4 | たちつてと |
| 5 | なにぬねの |
| 6 | はひふへほ |
| 7 | まみむめも |
| 8 | やゆよ |
| 9 | らりるれろ |
| 0 | わをん |
| * | ゛゜小 |

### Dakuten, Handakuten, and Small Kana

The `*` character (or some other non-digit character of your choice) will apply a dakuten () or handakuten (), or make small () the kana before it. If a form can't be applied to the kana before it, it is skipped in the cycle.

Kana with dakuten, handakuten, and small forms are in the table below.

| Key | Kana | Dakuten | Handakuten | Small |
| --- | --- | --- | --- | --- |
| 1 | あいうえお |  |  | ぁぃぅぇぉ |
| 2 | かきくけこ | がぎぐげご |  |  |
| 3 | さしすせそ | ざじずぜぞ |  |  |
| 4 | たちつてと | だぢづでど |  |  |
| 6 | はひふへほ | ばびぶべぼ | ぱぴぷぺぽ |  |
| 8 | やゆよ |  |  | ゃゅょ |

Note:  is the only t-series kana to have a small form. Input `4**` gives  because  cannot be shrunk; but the input `444**` gives small .

## Input

A list of strings, with each string containing a series of the same digit.

## Output

The hiragana represented by the input.

## Test Cases

```
['2','5'] => 'かな'
['222222','555555'] => 'かな'
['1','99','2','*','44444','111'] => 'ありがとう'
['4','*','2','*','22222','44444','0','999'] => 'だがことわる'
['11111','7','1111','00','33','000','4444', '***','999'] => 'おまえをしんでる'
['2','2','99','7','333'] => 'かかります'
['1','****'] => 'あ'
['4','**'] => 'た'
['444','**'] => 'っ'
['555','***********************'] => 'ぬ'
['22','*','88','*','111','55','88','*','111'] => 'ぎゅうにゅう'
['8','444','4'] => 'やつた'
['8','444','*','4'] => 'やづた'
['8','444','**','4'] => 'やった'
['6'] => 'は'
['6','*'] => 'ば'
['6','**'] => 'ぱ'
['6','***'] => 'は'

```

## Other Rules

* Input can be any reasonable method (list of strings, list of integers, a big string with delimiters, list of run-length-encoded strings, etc.)
* Output can be any reasonable method (printing to STDOUT, returning a string, etc.)
* This is , so shortest code wins!

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

Expects a list of strings, where `*` sequences are concatenated with digit sequences.

Returns a list of kana.

```
a=>a.map(s=>String.fromCharCode(Buffer("n *4>IN]bh")[n=+s[0]]+12321+(p=s.lastIndexOf(n),q=s.length+~p,p%=n%8?5:3)*(m=1855**n%79&3)+(n-4?p&&2*!n:q%(m+=p==2)>1?-2:p>1)+(q%m^n%7==1)))

```

Try it online!

## How?

### Interpreting the input string

Given the input string \\$s\\$, we compute:

* \\$p\\$: the 0-based position of the last digit in \\$s\\$
* \\$q\\$: the length of \\$s\\$, minus \\$p\\$ and minus \\$1\\$

### Base code point

We use a lookup Buffer and a fixed offset to get the base code point for the digit \\$n\\$:

```
Buffer("n *4>IN]bh")[n] + 12321

```

Try it online!

### Length of the digit cycle

The length of the digit cycle is \\$5\\$, except when \\$n=0\\$ or \\$n=8\\$, in which case it's \\$3\\$:

```
n % 8 ? 5 : 3

```

We reduce \\$p\\$ by the above modulo, which gives the 0-based index in the digit cycle.

### Length of the `*` cycle

For the length \\$m\\$ of the `*` cycle, we use the following formula:

```
1855 ** n % 79 & 3

```

which, with a couple of IEEE-754 approximation errors, gives:

```
[ 1, 2, 2, 2, 2, 1, 3, 1, 2, 1 ]

```

The 0-based index in the `*` cycle is \\$q \bmod m\\$.

### Final code point

The generic formula for the final code point is:

```
base_code_point + p * m + (q % m)

```

But there are several special cases which are detailed below.

### Case \\$n=4\\$, \\$p=2\\$

For the special case where the digit \\$4\\$ is pressed \\$3\\$ times to generate the small kana っ, we need to increment \\$m\\$ and to add a correction offset to the final result:

```
+ (n - 4 ? ... : q % (m += p == 2) > 1 ? -2 : p > 1)

```

### Case \\$n=0\\$

The code points for \\$n=0\\$ have a specific offset (\\$+2\\$) when \\$p\>0\\$:

```
+ (n - 4 ? p && 2 * !n : ...)

```

### Case \\$n=1\\$ or \\$n=8\\$

If \\$n=1\\$ or \\$n=8\\$, each pair of code points is reversed, leading to the sequence:

$$x+1,x,x+3,x+2,\dots$$

In this case, we add \\$(q \bmod m)\operatorname{XOR}1\\$ instead of \\$q \bmod m\\$:

```
+ (q % m ^ n % 7 == 1)

```
> 6 votes

# Answer
# Raku, ~~330~~ ~~295~~ ~~248~~ 240 bytes

```
*.map:{/(.)(\d)*(_)*/;uniparse 'hiragana letter '~({TR/ksth/gzdb/},{S/h/p/},'small '~*,~*)[flat
^4 Zxx($0 X~~2|3|4|6,6,1|8|{$_*9+$1%5==38},!0)][($2-1)%*]([<wa wo n>,|map((*X~
<a i u e o>),"",|'kstnhmr'.comb),<ya yu yo>][|^8,9,8][$0][$1%*])}

```

Try it online!

An underscore is used as the single non-digit character. A sequence of underscores is taken to be appended to the preceding digits rather than being its own element in the input array.

* `*.map: { ... }` converts each input element into a single Japanese character.
* `/(.)(\d)*(_)*/` matches the given pattern against each input element. The match is assumed to always succeed. Afterwards, `$0` is the first digit, `$1` is a list of succeeding digits, and `$2` is a list of underscores. In Raku, lists are treated as numbers equal to their length when used in an arithmetic context, so `$1` can be interpreted as one less than the number of initial digits, and `$2` as the number of trailing underscores.
* `[<wa wo n>,|map(...),<ya yo yu>]` constructs an array that maps digits to the list of romanized characters in the first "Kana" column given above. For example, 1 maps to the list `<a i u e o>`, 2 to the list `<ka ki ku ke ko>`, 8 to the list `<ya yu yo>`, etc. For brevity, the kana groups are generated out of order, so `[|^8,9,8]` slices the original list into the correct order. The given digit is used to look up the appropriate list of kana (`[$0]`), and the number of repetitions of the digit indexes into that list, wrapping around to the front of the list as needed (`[$1 % *]`).
* A list of anonymous transformation functions is consulted. That's the list `({ TR/ksth/gzdb/ }, { S/h/p/ }, 'small ' ~ *, ~*)`. The first function transforms a kana into its dakuten form (by translating "k" to "g", "s" to "z", etc), the second one transforms it into its handakuten form (by replacing "h" with "p"), the third one makes the kana small (by prepending "small " to it), and the last one `~*` is a string-identity function that circles back to the first version of the kana. Each function except the last is only conditionally included in the list by the following array slice. For example, if the first digit is 1, only the third and fourth transformations are applicable; if it's 6, all but the third are. The appropriate function for the number of trailing underscores is called, again wrapping around back to the beginning as needed with `[($2 - 1) % *]`.
* Finally the built-in `uniparse` function is called to convert the Unicode name of the character to the actual Unicode character, after prepending it with the common prefix "hiragana letter ".
> 5 votes

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

```
x=>[...x].map(t=>String.fromCharCode(12440+~U(U(X[u=t.split`*`,t[0]],u[0]),u)))
X=['854'];for(M=i=9;i;U=(x,y)=>x[~-y.length%x.length])for(Y=X[i--]=[j=i-7?5:3];j;)for(k of(Z=Y[--j]=[])+(i%7?i<4?M-49?21:213:i-5?1:321:12))Z[k-1]=++M

```

Try it online!

`0` is different from unicode-table so hardcoded
> 4 votes

# Answer
# C (GCC), ~~232~~ ~~228~~ 223 * bytes

```
f(char**s){for(;**s;){int c=**s-48,n=~-strlen(*s)%(c&7?5:3),a=**++s-42?0:strlen(*s),k='\x06v\xa9'>>2*c&3;s+=a>0;a%=c-4|n-2?k:3;printf("\xe3%c%c",(c&8||c<1)+129,"\x91\x82\x8B\x95\x9F\xAA\xAF\xBE\x84\x89"[c]+k*n-(c-4|n-2|a-2?c%7-1?-a:a:1)-(c-4||n<2)-(c+n?-1:1));}}

```

Attempt This Online!

\*: you have to encode each char in the hex string as a single byte instead of an escape code; I wasn't able to copy/paste it correctly on ATO.

How to test it: run `gcc a.c && ./a.out | grep -Eva '(\b.+) \1\b'`. Outputs each testcase for which the function outputs an incorrect string.
> 4 votes

# Answer
# Charcoal, 132 bytes

```
ＷＳ℅⁺¹²³¹⁵℅§§⪪§⪪”}∧﹪IC↗Ｔ″§×Ｋ_✳Y59G%⸿u-↷*f↨Ｖ±ＩFl⟲⦃⌊CψＲ^4ΦIhGＩT↧Ｐ{$ＱＴⅈZ?≕⌈⟧2EχＰP⊖▷ζＱ§⎇Ｚ∨⁰\`⪪k>+²γ～δïwⅈＶ-⦃ïＢ.｜←⁴Ｇ⭆!±Ｗ⁹✂φβＱ²1”¶Ｉ⌈ι №ι⌈ι№ι*

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated strings of digits and `*`s. Explanation:

```
ＷＳ                                  Loop over each line
               ”...”                Compressed look-up table
              ⪪     ¶               Split on newlines
             §                      Indexed by
                       ι            Current string
                      ⌈             Maximum i.e. first character
                     Ｉ              Cast to integer
            ⪪                       Split on spaces
           §                        Indexed by
                         №          Count of
                            ι       Current string
                           ⌈        Maximum i.e. first character
                          ι         In current string
          §                         Indexed by
                             №      Count of
                               *    Literal string `*`
                              ι     In current string
         ℅                          Take the ASCII code
   ⁺                                Plus
    ¹²³¹⁵                           Literal integer `12315`
  ℅                                 Convert to Unicode
                                    Implicitly print

```

The look-up table is adjusted for the 1-indexing of the button value and number of button presses, although the number of `*`s remains 0-indexed.
> 3 votes

# Answer
# Python 3 \+ `romkan`, 720 bytes

```
import romkan
def f(x):
	s="'"
	for i in range(len(x)):
		j=x[i]
		if j[0].isdigit():
			s+=["","","k","s","t","n","h","m","","r"][int(j[0])]
			if j[0]in"12345679":s+="oaiue"[len(j)%5]
			else:s+=[["n'","wa","wo"],["yo","ya","yu"]][int(j[0])%7][len(j)%3]
		else:
			if s[-2]in"aeiou'"and len(j)%2and s[-1]in"aeiou":s=s[:-1]+"ぁぃぅぇぉ"["aiueo".index(s[-1])]
			elif s[-2]in"ks"and len(j)%2:s=s[:-2]+"gz"["ks".index(s[-2])]+s[-1]
			elif s[-2:]=="tu"and len(j)%3:s=s[:-2]+"っ"if len(j)%3==2 else s[:-2]+"du"
			elif s[-2]=="h":s=s[:-2]+"hbp"[len(j)%3]+s[-1]
			elif s[-2]=="t"and len(j)%2:s=s[:-2]+"d"+s[-1]
			elif s[-2]=="y"and len(j)%2:s=s[:-2]+"ゃゅょ"["auo".index(s[-1])]
	return romkan.to_hiragana(s[1:])

```

Try it online! (without `romkan` and `romkan.to_hiragana`)
> 1 votes

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