title: Interpret /// (pronounced 'slashes')

text:
# Question
Title: Interpret /// (pronounced 'slashes')
Because we can't get enough of esoteric language golfs, can we?

///—pronounced *slashes*—is a fun little language based on the `s///` regex-replacement function of Perl fame. It contains only two special characters, slash `/` and backslash `\`. You can find a full article on it at the esolangs wiki, but I will reproduce a description of the language below, as well as some examples.

In short, it works by identifying `/pattern/repl/rest` in the program and making the substitution as many times as possible. No characters are special except `/` and `\`: `/` demarcates patterns and replacements in the program, while `\` allows you to insert literal `/` or `\` characters into your code. Notably, these are not regular expressions, just plain string substitutions.

*Your challenge* is to produce an interpreter for the /// language, as either a program reading STDIN or a function taking a string argument, in as few characters as possible.

You may use any language except for /// itself. You may not use any libraries that interpret ///; you may, however, use regexes, regex libraries, or string-matching libraries.

---

## Execution

There are four states, *print*, *pattern*, *replacement*, and *substitution*. In every state except *substitution*:

* If the program is empty, execution halts.
* Else, if the first character is `\`, do something with the next character (if present) and remove both from the program.
* Else, if the first character is `/`, remove it, and change to the next state.
* Else, do something with the first character and remove it from the program.
* Repeat.

The states cycle through *print*, *pattern*, *replacement*, and *substitution* in order.

* In *print* mode, 'do something' means output the character.
* In *pattern* mode, 'do something' means add the character to the current Pattern.
* In *replacement* mode, 'do something' means add the character to the current Replacement.

In *substitution* mode, you follow a different set of rules. Repeatedly substitute the first occurrence of the current Pattern with the current Replacement in the program, until no more substitutions are possible. At that point, clear the Pattern and Replacement and return to *print* mode.

In the program `/foo/foobar/foo foo foo`, the following happens:

```
/foo/foobar/foo foo foo
foo foo foo
foobar foo foo
foobarbar foo foo
foobarbarbar foo foo
...

```

This loops forever and never exits *substitution* mode. Similarly, if the Pattern is empty, then the first occurrence of the empty string—at the beginning of the program—always matches, so *substitution* mode loops forever, never halting.

---

## Examples

```
no

```

Output: `no`.

```
/ world! world!/Hello,/ world! world! world!

```

Output: `Hello, world!`.

```
/foo/Hello, world!//B\/\\R/foo/B/\R

```

Output: `Hello, world!`.

```
a/ab/bbaa/abb

```

Output: `a`. Program does not halt.

```
//

```

Output: none.

```
///

```

Output: none. Program does not halt.

```
/\\/good/\/

```

Output: `good`.

There is also a quine on the wiki you can try.

# Answer
## APL (133)

```
{T←''∘{(0=≢⍵)∨'/'=⊃⍵:(⊂⍺),⊂⍵⋄(⍺,N⌷⍵)∇⍵↓⍨N←1+'\'=⊃⍵}⋄⍞N←T⍵⋄p N←T 1↓N⋄r N←T 1↓N⋄''≡N:→⋄∇{⍵≡p:∇r⋄∨/Z←p⍷⍵:∇(r,⍵↓⍨N+≢p),⍨⍵↑⍨N←1-⍨Z⍳1⋄⍵}1↓N}

```

This is a function that takes the `///` code as its right argument.

Ungolfed, with explanation:

```
slashes←{
   ⍝ a function to split the input string into 'current' and 'next' parts,
   ⍝ and unescape the 'current' bit
   split←''∘{
       ⍝ if the string is empty, or '/' is reached,
       ⍝ return both strings (⍺=accumulator ⍵=unprocessed)
       (0=≢⍵)∨'/'=⊃⍵:(⊂⍺),⊂⍵
       ⍝ otherwise, add current character to accumulator,
       ⍝ skipping over '\'s. (so if '\/' is reached, it skips '\',
       ⍝ adds '/' and then processes the character *after* that.)
       idx←1+'\'=⊃⍵
       (⍺,idx⌷⍵)∇idx↓⍵
   }

   ⍞   next ← split ⍵      ⍝ output stage
   pat next ← split 1↓next ⍝ pattern stage, and eat the '/'
   rpl next ← split 1↓next ⍝ replacement stage, and eat the '/'

   ⍝ if there are no characters left, halt.
   ''≡next:⍬

   ⍝ otherwise, replace and continue.
   ∇{  ⍝ if the input string equals the pattern, return the replacement and loop
       ⍵≡pat:∇rpl

       ⍝ otherwise, find occurences, if there are, replace the first and loop
       ∨/occ←pat⍷⍵:∇(rpl, (idx+≢pat)↓⍵),⍨ (idx←(occ⍳1)-1)↑⍵

       ⍝ if no occurences, return string
       ⍵

   }1↓next
}

```
> 7 votes

# Answer
# J - ~~181~~ ~~190~~ 170 char

This was a nightmare. I rewrote it from scratch, twice, because it just kept bugging me. This is a function taking a single string argument, outputting to STDOUT.

```
(0&$`((2{.{:@>&.>)((j{.]),-i@=`p@.~:~/@[,]}.~#@p+j=.0{p I.@E.])i 5;@}.&,'/';"0;&.>)@.(2<#)@}.[4:1!:2~{:@>@p=.>@{.@[)@((0;(0,:~1 0,.2);'\';&<1 0)<;._1@;:'/'&,)i=. ::](^:_)

```

To explain, I will break it up into subexpressions.

```
i =. ::](^:_))
parse =: ((0;(0,:~1 0,.2);'\';&<1 0)<;._1@;:'/'&,)
print =: 4:1!:2~{:@>@p=.>@{.@[
eval  =: 0&$`((2{.{:@>&.>)sub 5;@}.&,'/';"0;&.>)@.(2<#)@}.
sub   =: ((j{.]),-i@=`p@.~:~/@[,]}.~#@p+j=.0{p I.@E.])i

interp =: (eval [ print) @ parse i

```
* `i` (short for *iterate*) is an adverb. It takes a verb argument on the left and returns a verb `(f)i`, which when applied to an argument, applies `f` repeatedly to the argument until one of two things happens: it finds a fixed point (`y = f y`), or it throws an error. The fixed-point behaviour is inherent to `^:_`, and `::]` does the error handling.
* `parse` tokenizes the input into what I call *half-parsed* form, and then cuts it up at the unescaped '/'. It binds escaping backslashes to their characters, but doesn't get rid of the backslashes—so we can either revert it or finish it depending on which we want.

The bulk of the interesting work occurs in `;:`. This is a sequential-machine interpreter primitive, taking a description of the machine (`(0;(0,:~1 0,.2);'\';&<1 0)`) on the left and something to parse on the right. This does the tokenizing. I will note that this specific machine actually treats the first character unspecial, even if it's a `\` and should bind. I do this for a few reasons: (1) the state table is simpler, so it can be golfed further; (2) we can easily just add a dummy character to the front to dodge the problem; and (3) that dummy-character gets half-parsed at no extra cost, so I can use it to set up for the cutting phase, next.

We also use `<;._1` to cut the tokenized result on unescaped `/` (which is what I choose to be the first char). This is handy for pulling out the output, pattern, and replacement from `out/patt/repl/rest` all in one step, but unfortunately also cuts up the rest of the program, where we need those `/` to stay untouched. I splice these back in during `eval`, because making `<;._1` leave them alone ends up costing a lot more.
* The fork `(eval [ print)` executes `print` on the result from `parse` for its side-effects, and then runs `eval`. `print` is a simple verb that opens up the first box (the one we know for sure is output), finishes parsing it, and sends it to STDOUT. However, we also take the chance to define a utility verb `p`.

`p` is defined as `>@{.@[`, so it takes its left arg (acts like the identity if given only one arg), takes the first item of that (identity when given a scalar), and unboxes it (identity if already unboxed). This will come in very handy in `sub`.
* `eval` evaluates the remainder of the processed program. If we don't have a full pattern or a full replacement, `eval` throws it out and just returns an empty list, which terminates evaluation by making `;:` (from `parse`) error out on the next iteration. Else, `eval` fully parses the pattern and replacement, corrects the remainder of the source, and then passes both to `sub`. By explosion:

```
                                              @}.  NB. throw out printed part
                                       @.(2<#)     NB. if we have a pattern and repl:
      2{.                                          NB.  take the first two cuts:
             &.>                                   NB.   in each cut:
         {:@>                                      NB.    drop escaping \ from chars
     (          )                                  NB.  (these are pattern and repl)
                                   &.>             NB.  in each cut:
                                  ;                NB.   revert to source form
                            '/';"0                 NB.  attach a / to each cut
                          &,                       NB.  linearize (/ before each cut)
                     5  }.                         NB.  drop '/pattern/repl/'
                      ;@                           NB.  splice together
    (            sub                  )            NB.  feed these into sub
   `                                               NB. else:
0&$                                                NB.  truncate to an empty list

```
* `sub` is where one (possibly infinite) round of substitutions happens. Because of the way we set up `eval`, the source is the right argument, and the pattern and replacement are bundled together in the left. Since the arguments are ordered like this and we know the pattern and replacement don't change within a round of substitutions, we can use another feature of `i`—the fact that it modifies only the right argument and keeps passing in the same left—to delegate to J the need to worry about keeping track of the state.

There are two spots of trouble, though. The first is that J verbs can have at most two arguments, so we don't have an easy way to access any that are bundled together, like pattern and replacement, here. Through clever use of the `p` utility we defined, this isn't that big of a problem. In fact, we can access the pattern in one character, just by using `p`, because of its `>@{.@[` definition: the Unbox of the First item of the Left arg. Getting the replacement is tricker, but the shortest way would be `p&|.`, 2 chars shorter than manually getting it out.

The second problem is that `i` exits on fixed points instead of looping forever, and if the pattern and replacement are equal and you make a substitution, that looks like a fixed point to J. We handle this by entering an infinite loop of negating 1 over and over if we detect they are equal: this is the `-i@=`p@.~:~/` portion, replacing `p&|.`.

```
                                    p    E.]    NB. string search, patt in src
                                      I.@       NB. indices of matches
                                  0{            NB. take the first (error if none)
                               j=.              NB. assign to j for later use
                           #@p+                 NB. add length of pattern
                       ]}.~                     NB. drop that many chars from src
                   /@[                          NB. between patt and repl:
                  ~                             NB.  patt as right arg, repl as left
              @.~:                              NB.  if equal:
        -i@=                                    NB.   loop forever
            `p                                  NB.  else: return repl
 (j{.])                                         NB. first j chars of src
       ,              ,                         NB. append all together
(                                           )i  NB. iterate

```
* This cycle repeats due to the use of `i`, until something outside of `sub` errors out. As far as I'm aware, this can only happen when we are out of characters, of when we throw out an incomplete set of pattern-and-replacement.

Fun facts about this golf:

* For once, using `;:` is shorter than manually iterating through the string.
* `0{` should have a chance to error out before `sub` goes into an infinite loop, so this it should work fine if the pattern matches the replacement but never shows up in the remainder of the source. However, this may or may not be unspecified behaviour, since I can't find a citation either way in the docs. Whoopsie.
* Keyboard interrupts are processed as spontaneous errors inside running functions. However, due to the nature of `i`, those errors get trapped too. Depending on when you hit Ctrl+C, you might:
    + Exit out of the negate-forever loop, error out of the `sub` loop by trying to concatenate a number to a string, and then go on interpreting /// as if you finished substituting a string with itself an infinite number of times.
    + Leave `sub` halfway through and go on interpreting a half-subbed /// expression.
    + Break out of the interpreter and return an unevaluated /// program to the REPL (not STDOUT, though).

Example usage:

```
   f=:(0&$`((2{.{:@>&.>)((j{.]),-i@=`p@.~:~/@[,]}.~#@p+j=.0{p I.@E.])i 5;@}.&,'/';"0;&.>)@.(2<#)@}.[4:1!:2~{:@>@p=.>@{.@[)@((0;(0,:~1 0,.2);'\';&<1 0)<;._1@;:'/'&,)i=. ::](^:_)
   f 'no'
no
   f '/ world! world!/Hello,/ world! world! world!'
Hello, world!
   f '/foo/Hello, world!//B\/\\R/foo/B/\R'
Hello, world!
   f '//'  NB. empty string

   f '/\\/good/\/'
good

```
> 13 votes

# Answer
# Pip, ~~100~~ 102 bytes

I hadn't ever proven Pip to be Turing-complete (though it's pretty obviously so), and instead of going the usual route of BF I thought /// would be interesting. Once I had the solution, I figured I'd golf it and post it here.

101 bytes of code, +1 for `-r` flag:

```
i:gJnf:{a:xW#i&'/NE YPOia.:yQ'\?POiya}W#iI'\Q YPOiOPOiEIyQ'/{p:VfY0s:VfIyQ'/WpNi&YviR:Xp{++y?ps}}E Oy

```

Here's my ungolfed version with copious comments:

```
; Use the -r flag to read the /// program from stdin
; Stdin is read into g as a list of lines; join them on newline and assign to c for code
c : gJn

; Loop while c is nonempty
W #c {
 ; Pop the first character of c and yank into y
 Y POc
 ; If y equals "\"
 I yQ'\
  ; Pop c again and output
  O POc
 ; Else if y equals "/"
 EI yQ'/ {
  ; Build up pattern p from empty string
  p : ""
  ; Pop c, yank into y, loop while that is not equal to "/" and c is nonempty
  W #c & '/ NE Y POc {
   ; If y equals "\"
   I yQ'\
    ; Pop c again and add that character to p
    p .: POc
   ; Else, add y to p
   E p .: y
  }

  ; Yank 0 so we can reliably tell whether the /// construct was completed or not
  Y0
  ; Build up substitution s from empty string
  s : ""
  ; Pop c, yank into y, loop while that is not equal to "/" and c is nonempty
  W #c & '/ NE Y POc {
   ; If y equals "\"
   I yQ'\
    ; Pop c again and add that character to s
    s .: POc
   ; Else, add y to s
   E s .: y
  }

  ; If the last value yanked was "/", then we have a complete substitution
  ; If not, the code must have run out; skip this branch, and then the outer loop
  ; will terminate
  I yQ'/ {
   ; While pattern is found in code:
   W pNc {
    ; Set flag so only one replacement gets done
    i : 0
    ; Convert p to a regex; replace it using a callback function: if ++i is 1,
    ; replace with s; otherwise, leave unchanged
    c R: Xp {++i=1 ? s p}
   }
  }
 }
 ; Else, output y
 E Oy
}

```

Try it online! (Note that TIO doesn't give any output when the program is non-terminating, and it also has a time limit. For larger examples and infinite loops, running Pip from the command line is recommended.)
> 6 votes

# Answer
# Perl - 190

```
$|=1;$/=undef;$_=<>;while($_){($d,$_)=/(.)(.*)/;eval(!$e&&({'/','$a++','\\','$e=1'}->{$d})||('print$d','$b.=$d','$c.=$d')[$a].';$e=0');if($a==3){while($b?s/\Q$b/$c/:s/^/$c/){}$a=0;$b=$c=''}}

```

Reads `///` program from stdin until EOF.
> 4 votes

# Answer
# C++ 347

**Edits:**

* **Thanks to @algorithmshark for lots of help making the original shorter**
* **Thanks to @Adalynn for a good suggestion to save bytes**
* **Thanks to @ceilingcat for many, many very nice pieces of golfing - now even shorter**

Here is the code:

```
#import<bits/stdc++.h>
#define N(x)o[i]);else if(n<x)o[i]==92?
#define O (o[++i]):o[i]==47?n++:
char p[198],*q=p,*s=p+99;int i,t;main(int n,char**m){for(std::string o=m[1];i<=o.size();++i){if(!N(3)putchar O putchar(N(4)*q++=O(*q++=N(5)*s++=O(*s++=o[i]);if(n>4){for(n=2;~(t=o.find(p,i+1));o=o.substr(0,t)+s+&o[t+strlen(p)])s=p+99;bzero(q=p,198);}}}

```

Try it online!
> 3 votes

# Answer
# Python 2 (236), Python 3 (198?)

```
from __future__ import print_function
def d(i):
 t=0;p=['']*3+[1]
 while i:
  if'/'==i[0]:t+=1
  else:
   if'\\'==i[0]:i=i[1:]
   p[t]+=i[0]
  i=i[1:]
  print(end=p[0]);p[0]=''
  if t>2:
   while p[1]in i:i=i.replace(*p[1:])
   d(i);i=0

```

Called as `d(r"""/foo/Hello, world!//B\/\\R/foo/B/\R""")`. The triple quotes are only needed if the `///` program contains newlines: otherwise simple quotes are ok.

EDIT: This interpreter now prints stuff as expected (previously it only printed at the very end, cf. comments). For Python 3, remove the first line (but I don't have Python 3 on my ancient install, so cannot be sure there is no other change).
> 2 votes

# Answer
# Cobra - 226

```
sig Z as String
def f(l='')
    m=Z(do=[l[:1],l=l[1:]][0])
    n as Z=do
        if'/'<>(a=m())>'',return if(a=='\\',m(),a)+n()
        else,return''
    print n()stop
    p,s=n(),n()
    if''<l
        while p in l,l=l[:l.indexOf(p)+1]+s+l[p.length:]
        .f(l)

```
> 2 votes

# Answer
# **BaCon, ~~391~~ ~~387~~ 395 bytes**

From the contributions on this page I only got the Python program to work. The others work for some /// samples, or do not work at all. Therefore, I decided to add my version, which is an implementation in BASIC.

To compete in a CodeGolf contest with BASIC is not easy, as BASIC uses long words as statements. The only abbreviation commonly found in BASIC is the '?' sign, which means PRINT.

So the below program may never win, but at least it works with all demonstration code on this Codegolf page and on the Esolangs Wiki. Including all versions of the "99 bottles of beer".

```
p$=""
r$=""
INPUT i$
WHILE LEN(i$)
t$=LEFT$(i$,1)
i$=MID$(i$,2)
IF NOT(e) THEN
IF t$="\\" THEN
e=1
CONTINUE
ELIF t$="/" THEN
o=IIF(o<2,o+1,0)
IF o>0 THEN CONTINUE
FI
FI
IF o=1 THEN
p$=p$&t$
ELIF o=2 THEN
r$=r$&t$
ELIF o=0 THEN
IF LEN(p$) THEN i$=REPLACE$(i$,p$,r$)
IF NOT(INSTR(t$&i$,"/")) THEN
?t$;
BREAK
ELSE
?LEFT$(i$,INSTR(i$,"/")-1);
i$=MID$(i$,INSTR(i$,"/"))
FI
p$=""
r$=""
FI
e=0
WEND
?i$

```
> 2 votes

# Answer
# Ruby, ~~119~~ 110 bytes

Terminates with exception

```
r=->s,o=$>{s[k=s[0]]='';k==?/?o==$>?s.gsub!([r[s,''],e=r[s,'']][0]){e}:t=o:o<<(k==?\\?s[0]+s[0]='':k);t||redo}

```

Try it online!

Terminates cleanly (116 bytes)

```
r=->s,o=$>{s[k=s[0]||exit]='';k==?/?o==$>?s.gsub!([r[s,''],e=r[s,'']][0]){e}:t=o:o<<(k==?\\?s[0]+s[0]='':k);t||redo}

```

Try it online!
> 2 votes

# Answer
# Python 2/3 (211 bytes)

The following code, based on Bruno Le Floch's answer, is Python 2 and Python 3 compatible.

Moreover, being iterative rather than recursive it does not risk hitting the maximum recursion depth of Python.

```
def S(c):
 while c:
  B=["","",1]
  for m in 0,1,2:
   while c:
    if"/"==c[0]:c=c[1:];break
    if"\\"==c[0]:c=c[1:]
    if m:B[m-1]+=c[0]
    else:yield c[0]
    c=c[1:]
  while c and B[0]in c:c=c.replace(*B)

```
> 1 votes

---
Tags: code-golf, string, interpreter, regular-expression
---


title: Cleaning the dishes

text:
# Question
Title: Cleaning the dishes
## Cleaning the dishes

In this task, you will be given a bar of soap with a width of 1 or more units. You will also be given a plate, which you will have to clean, using the soap as few times as you can. The plate will be at least 1 character. You will have to output a plate with the 'clean' character representing the plate, and a third unique character to represent in what positions the bar of soap was placed.

How much the soap cleans:

```
(n-1)//2 on each side for odd n
(n-1)//2 on the left side of the soap bar for even n
n//2   on the right side of the soap bar for even n

```

Note: `n//2` means `floor(n/2)`.

## Input

An integer greater than or equal to 1. A series of 2 unique characters to represent clean portions and dirty portions. Here, '=' represents a dirty portion, and '-' represents a clean portion. '+' represents where the soap was placed. Before the colon is what is the input, and after the colon is what is outputted.

**IN : OUT**

```
3 ===- : -+--
32 ================================ : ---------------+----------------
1 ==== : ++++
5 ----- : -----
4 -====- : --+---
3 -====- : --+-+-
7 === : +--
6 - : -
6 -==-===- : ---+----
5 -==--==- : ---+--+-
3 -==--==- : --+--+--

```

## Rules

* There are multiple solutions. Any one of them are acceptable, as long as they use the soap the minimum amount of times possible.
* This is a contest, so the shortest answer in bytes wins!
* Input may be whatever you want, as long as the plate and soap are specified, and clean/dirty portions of the plate are different. For example, strings and arrays of integers are allowed.
* Output is of your choosing. You just need to make sure clean and soap portions of the output plate are different, but consistent. The plate and where the soap was placed should be shown.
* Standard loopholes are not allowed.

Sandbox: Sandbox for Proposed Challenges

# Answer
> 4 votes
# JavaScript (ES6),  ~~92 90 86~~  85 bytes

*Saved 1 byte thanks to @Grimy*

Takes input as `(n)(string)`. Uses `1` as the soap character.

```
n=>s=>s.replace(eval(`/=.{0,${n-1}}/g`),s=>(g=n=>'-'.repeat(s.length-n>>1))(1)+1+g``)

```

Try it online!

### How?

To get the widths of the cleaning areas, the helper function \\$g\\$ uses the expression \\$\lfloor(n-k)/2\rfloor\\$, which gives the left width for \\$k=1\\$ and the right width for \\$k=0\\$:

$$\lfloor (n-1)/2\rfloor=\cases{ (n-1)/2,&\text{if $n$ is odd}\\ n/2-1,&\text{if $n$ is even}\\ }$$

$$\lfloor (n-0)/2\rfloor=\cases{ (n-1)/2,&\text{ if $n$ is odd}\\ n/2,&\text{ if $n$ is even}\\ }$$

### Commented

```
n =>                           // n = soap width
s =>                           // s = plate string
  s.replace(                   // find in s all patterns consisting of
    eval(`/=.{0,${n - 1}}/g`), //   '=' followed by 0 to n-1 characters (greedily)
    s =>                       //   for each pattern s:
      ( g = n =>               //     g is a function taking n = 0 or 1
          '-'.repeat(          //       and outputting a string of
            s.length - n >> 1  //       floor((s.length - n) / 2) hyphens
          )                    //
      )(1) +                   //     replace s with g(1) (left part)
      1 +                      //     followed by '1' (the soap)
      g``                      //     followed by g(0) (right part)
  )                            // end of replace()

```

# Answer
> 1 votes
# Python 3, 86 bytes

```
def f(n,s):i=s.find('1');return~i and'0'*i+f'{2:0^{min(n,len(s)-i)}}'+f(n,s[n+i:])or s

```

Try it online!

Uses `0` for empty plate, `1` for dirt and `2` for soap. Takes an integer `n` and a string `s` as input.

The function searches for the first dirt character `1` in the string `s`. Starting at that point, it will format a string of emtpy plate characters `0` with a soap character `2` as the center character. Because of Python's string formatting rules, the soap character `2` will be in the center-left position when `n` is even. This piece of string will be of length `n` *or* the remaining number of characters in the input string `s`, whichever is shorter. The rest of the string `s` is evaluated recursively.

# Answer
> 1 votes
**VBA, 157bytes**

```
Sub a(s, p):z=Len(p):Q=s\2+s Mod 2-1
While instr(x+1,p,1)<>0
F=instr(x+1,p,1)
f=f+2/s
If f>Z then f=z
Mid(p,f)=2
X=f+q
Wend
P=replace(p,1,0)
Msgbox p
End sub

```

I think there are lots of bytes to save but couldn't get rid of the if Statement without causing some cases to fail

is Expecting the plate to be 0 clean and 1 dirty (2 is soap)

# Answer
> 0 votes
# Perl 5 (`-p`), ~~86~~, 59 bytes

-27 bytes thanks to Grimy,

```
$m=$_-1;s`=.{0,$m}`$_=$&;y/=/-/;s/(-*)-\1/$1+$1/r`ge;s;.* ;

```

TIO

* `$m=$_-1;` input coerced to integer -1 which will be used as maximum number of character to be matched after `=`
* `s{=.{0,$m}}{...}e` : subsitution of longest match of `=` followed by at most m characters
* `$_=$&;y/=/-/;s/(-*)-\1/$1+$1/r` : to replace all `=` by `-` and then; to find the largest sequence of repeated `-` followed by a `-` and followed by the backreference \1
* `s;.* ;;` : to remove the number and space from input

Previous answer

```
/ /;$m=$`-1;$p="{0,$m}";$_=$';s`=.$p`$l=length$&;"-"x(-!($l%2)+$l/2)."+"."-"x($l/2)`ge

```

TIO

other solution doesn't pass all tests because doesn't match clean parts within dirty.

~~67 bytes~~

~~```
/ /;$n=$`;$_=$';s/(=*)=(=?)\1(??{length$&>$n&&"^"})/$1+$2$1/g;y;=;-

```~~

~~TIO~~

# Answer
> 0 votes
# Jelly, ~~29~~ 22 bytes

```
+þ_H}ḞFṬo³Ạ
JŒPçƇḢṬ+Ị{

```

Try it online!

A full program taking the dish as a string as its first argument and the size of the soap as an integer as its second argument. Prints a string representing the clean dish with the soap in place. For both, `0` is dirty, `1` is clean and `2` is soap.

# Answer
> 0 votes
# Retina 0.8.2, 69 bytes

```
\d+
$*-
^(-*)-\1
$1#$1
+`((((-)|#)+)-*,.*)(?<-4>.)*(?(4)$)=
$1$2
.+,

```

Try it online! Link includes test cases. Uses `#` to represent soap. Explanation:

```
\d+
$*-

```

Convert `n` into a template string of clean plate.

```
^(-*)-\1
$1#$1

```

Change the middle character of the template to soap.

```
+`

```

Repeatedly clean the plate until it cannot be cleaned any more.

```
((((-)|#)+)-*,.*)(?<-4>.)*(?(4)$)=

```

Match as much template and soap as possible. Keep track of the amount of template matched for later. The match starts as early as possible, so it will never start after the soap (since it could have matched starting at the soap in that case). Then optionally consume some clean template plate (meaning that the match must contain the soap) and an arbitrary amount before some dirty plate of exactly the same length as the template previously matched.

```
$1$2

```

Replace the dirty plate with the clean template and soap.

```
.+,

```

Delete the clean template and soap.

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


title: Where are they calling from?

text:
# Question
Title: Where are they calling from?
When making phone calls internationally, phone numbers are prefixed with a code indicating what country the number is located in. These codes are prefix codes, meaning that no code is a prefix of another.

Now, earlier today you missed a call, and you're kind of curious where that call might have come from. So you want to look up the calling code. But, being a prefix code, you're not quite sure where it ends, so you decide to write a program to separate the calling code from the rest of the number.

# Input

As input, you will recieve a string consisting of the digits `0-9`. The first few digits will be one of the country calling codes listed below (this means the first digit will never be `0`). After the country calling code, the rest of the input will contain zero or more digits in any order - it is *not* guaranteed to be a valid phone number. Your program must be able to handle inputs containing at least 15 digits

# Output

Your program should output the unique country calling code that is a prefix of the number. The valid outputs are as follows:

```
1
20
211
212
213
216
218
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
260
261
262
263
264
265
266
267
268
269
27
290
291
297
298
299
30
31
32
33
34
350
351
352
353
354
355
356
357
358
359
36
370
371
372
373
374
375
376
377
378
379
380
381
382
383
385
386
387
389
39
40
41
420
421
423
43
44
45
46
47
48
49
500
501
502
503
504
505
506
507
508
509
51
52
53
54
55
56
57
58
590
591
592
593
594
595
596
597
598
5993
5994
5997
5999
60
61
62
63
64
65
66
670
672
673
674
675
676
677
678
679
680
681
682
683
685
686
687
688
689
690
691
692
7
800
808
81
82
84
850
852
853
855
856
86
870
875
876
877
878
879
880
881
882
883
886
888
90
91
92
93
94
95
960
961
962
963
964
965
966
967
968
970
971
972
973
974
975
976
977
979
98
991
992
993
994
995
996
998

```

This list is based on the codes listed on Wikipedia's list of country calling codes page as of revision 915410826, with a few modifications

* All codes listed as unassigned or discontinued and some codes listed as reserved for future use were omitted
* If a code listed on Wikipedia is a prefix of another, the latter was omitted
* If a single country or territory would have more than one code, and if those codes would have a common prefix, those codes are omitted in favour of their common prefix.

This may result in independent countries being lumped together, or disputed territories being lumped in with a particular claimant. This is not intended as a political statement, and decisions about the inclusion or omission of territories and states were made based on the codes, not any beliefs I hold regarding the ownership or sovereignty of the entities using them.

If given an input that does not begin with any of these codes, your program's behaviour is undefined.

And finally:

# Test cases

| input | output |
| --- | --- |
| 5292649259 | 52 |
| 3264296721 | 32 |
| 1550 | 1 |
| 33121394 | 33 |
| 7 | 7 |
| 2542112543 | 254 |
| 2005992972 | 20 |
| 350 | 350 |
| 360 | 36 |
| 8505234469 | 850 |
| 9795586334 | 979 |
| 148985513598795 | 1 |
| 222222 | 222 |
| 5999995 | 5999 |

# Answer
# JavaScript (ES6),  ~~75 73~~  71 bytes

*Saved 1 byte thanks to @Shaggy*
*Saved 2 bytes thanks to @Neil*

```
s=>/1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.)./.exec(s)[0]

```

Try it online!
> 11 votes

# Answer
# 05AB1E, ~~28~~ ~~25~~ 24 bytes

```
η•Aó¾«¸tEΓ∞ζ∊u½d•.¥¤ØªKн

```

Try it online!

```
η                            # prefixes of the input
 •Aó¾«¸tEΓ∞ζ∊u½d•            # compressed integer 211112166111113621489811655218129
                 .¥          # undelta: [0, 2, 3, 4, 5, 6, 8, 9, 15, 21, 22, 23, 24, 25, 26, 29, 35, 37, 38, 42, 50, 59, 67, 68, 69, 75, 80, 85, 87, 88, 96, 97, 99, 108]
                   ¤         # last element of that list: 108
                    Ø        # nth prime: 599
                     ª       # append it to the list
                      K      # remove all those values from the list of prefixes
                       н     # get the first prefix left

```
> 10 votes

# Answer
# Retina 0.8.2, 60 bytes

```
!`^(2[1-69]?|3[578]?|42?|599?|50?|6[789]?|8[578]?|9[679]?)?.

```

Try it online!
> 6 votes

# Answer
# Bash, 328 ~~341~~ ~~410~~ bytes

Not very competitive for a golfing score, but each of these helps my bash skills!

Saved 13 bytes by eliminating handling 2 byte run-length values; storing only 3 bytes adds 8 bytes to T, but makes the case statement much simpler.

Saved 69 bytes by changing approach from bash expansion to storing deltas. The previous TIO link is at the bottom of my answer.

```
T='16D73r423112r62r72r6F1224r53-03511322rZr32r9L1611-01Fr9BrD2112V12-025r9-029r8-0202rB2r7-0308-162121E5r832-02082r72Cr52-3UR132'
A(){
V=$[V+36#$1]
S="$S $V"
}
R(){
read -n$1 d
}
while read -n1 c;do
case $c in -)R 3;A $d;;r)R 1;for((i=1;$i<=36#$d;i++)){ A 1;};;*)A $c;;esac;done<<<$T
for s in $S;do [[ $1 =~ ^$s ]]&&echo $s;done

```

Try it online!

* Sorted the list of prefixes numerically
* T is a "sort of" run-length encoded string showing the delta from the previous value. Each character is one of the following:
    + A base36 value showing the increase from the previous value
    + 'r': indicates that the next character indicates the the base36 encoded number of repeated delta values of 1.
    + '-': indicates that the next 3 characters are the next delta value

The string T="16D73r42 \[...\] -3UR132" following the rules above becomes a list of deltas: "1 6 D 7 3 r4 2 \[...\] 4995 1 3 2"

Could save 2-3 more bytes by using a higher radix than 36 (like 62-64) but Excel only natively supports up to 36, and that's what used to do the list of deltas and their conversions.

* On running, T is parsed and expanded into the string S used for the comparison of the phone number given in command line argument 1.

Expanding T, S becomes: "1 7 20 27 30 31 32 33 34 36 \[...\] 5993 5994 5997 5999"

~~Try it online!~~
> 6 votes

# Answer
# Python 3, ~~120~~ 78 bytes

```
f=lambda n:{n//10+3}-{*b'	 &()-5>FGHSXZ[cdf',602}and f(n//10)or n

```

Try it online!

Contains some unprintables:

```
00000000: 663d 6c61 6d62 6461 206e 3a7b 6e2f 2f31  f=lambda n:{n//1
00000010: 302b 337d 2d7b 2a62 2705 0306 0708 090b  0+3}-{*b'.......
00000020: 0c18 191a 1b1c 1d20 2628 292d 353e 4647  ....... &()-5>FG
00000030: 4853 585a 5b63 6466 272c 3630 327d 616e  HSXZ[cdf',602}an
00000040: 6420 6628 6e2f 2f31 3029 6f72 206e       d f(n//10)or n

```

Somewhat ungolfed (earlier) version:

```
f=lambda n:{n/10}-{0,2,3,4,5,6,8,9,21,22,23,24,25,26,29,35,37,38,42,50,59,599,67,68,69,80,85,87,88,96,97,99}and f(n/10)or n

```

Try it online!
> 5 votes

# Answer
# Perl 5 (-p), 44 bytes

```
$\=chop until/^599$/+vec"\x7D\x03\xE0\x27\x68\x04\x04\x08\x38\x00\xA1\x01\x0B",$_,1

```

Try it online!

Both TIO and SO have troubles with unprintable chars, so the program is shown with escape sequences. Here's a hexdump of the actual 44 bytes:

```
0000000: 245c 3d63 686f 7020 756e 7469 6c2f 5e35  $\=chop until/^5
0000010: 3939 242f 2b76 6563 227d 03e0 2768 0404  99$/+vec"}..'h..
0000020: 0838 00a1 010b 222c 245f 2c31            .8....",$_,1

```
> 3 votes

# Answer
# PHP, 219 bytes

I feel like there's a lot of room for improving the regex - golfed it as far as I can go but I'll bet it can be way shorter....

```
preg_match('/(1|7|2(0|1[12368]|[2346].|5[^9]|7|9[01789])|3[578]?.|42?[013]|5([1-8]|0.|99?[3479])|6([0-6]|7[^1]|8[^4]|9[012])|8(0[08]|[1246]|5[02356]|7[05-9]|8[0-368])|9([0-58]|6[^9]|7[^8]|9[1-8]))/',$argn,$r);echo$r[0];

```

Try it online!
> 1 votes

# Answer
# Java 8, 84 bytes

```
s->s.replaceAll("(1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.).).*","$1");

```

Port of *@Arnauld*'s JavaScript regex, so make sure to upvote him!

Try it online.

**Explanation:**

```
s->                    // Method with String as both parameter and return-type
  s.replaceAll("(1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.).).*",
                       //  Replace this regex-match
               "$1");  //  With this replacement

```

*Regex explanation:*

```
(1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.).).*  // MATCH:
 1                                                           //  a 1
  |7                                                         //  or a 7
    |(                                                )      //  or:
      2[^07]                                                 //   a 2 not followed 0 nor 7
            |3[578]                                          //   or a 3 followed by 5, 7, or 8
                   |42                                       //   or a 42
                      |599?                                  //   or a 59 or a 599
                           |50                               //   or a 50
                              |6[789]                        //   or a 6 followed by 7, 8, or 9
                                     |8[0578]                //   or an 8 followed by 0, 5, 7, or 8
                                             |9[679]         //   or a 9 followed by 6, 7, or 9
                                                    |.       //   or any single digit
                                                       .     //  followed by any single digit
(                                                       )    //  All captured in capture group 1
                                                         .*  //  With 0 or more digits following

$1                                                           // REPLACEMENT:
$1                                                           //  The match of capture group 1,
                                                             //  (effectively removing the
                                                             //   remaining digits of `.*`)

```
> 1 votes

# Answer
# Python 3, 96 bytes

```
lambda s:re.sub('(1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.).).*',r'\1',s)
import re

```

Try it online!

Port of Arnauld's JavaScript answer.
> 0 votes

# Answer
# Scala, 411 402 330 bytes

This is assuming that the argument only contains digits.

```
"(1|(2(0|(1[12368])|([2346]\\d)|(5[^9])|7|(9[^2-6])))|(3(([0-4])|([57]\\d)|6|(8[^48])|9))|(4([^2]|(2[013])))|(5((0\\d)|[^09]|(9([^9]|(9[3479])))))|(6([0-6]|(7[^1])|(8[^4])|(9[0-2])))|7|(8((0[08])|[1246]|(5[02356])|(7[05-9])|(8[^4579])))|(9([0-58]|(6[^9])|(7[^8])|(9[^079]))))(.*)".r.unapplySeq(args(0)).foreach(l=>println(l.head))

```

Try it online!
> 0 votes

---
Tags: code-golf, string, kolmogorov-complexity, subsequence
---


title: Escape the labyrinth!

text:
# Question
Title: Escape the labyrinth!
You are trapped in this 5x5 labyrinth - each room is labelled from 1 to 25 and the exit is in room 1.

You are given as input the room you are currently in. Your task is to output the shortest sequence of moves (north, east, south, west) needed to reach room 1.

Moves can be output in any format you wish (list, string, array...) as long as you use the characters `n,w,e,s`.

**Here are all the test cases:**

```
1 => empty string/list
2 => w
3 => ww
4 => swwnw
5 => wswwnw
6 => seenwnw
7 => nw
8 => wnw
9 => wwnw
10 => swwnwnw
11 => eenwnw
12 => enwnw
13 => nwnw
14 => wnwnw
15 => wwnwnw
16 => enenwnw
17 => nenwnw
18 => wnenwnw
19 => nwnwnw
20 => wnwnwnw
21 => nenenwnw
22 => enwnenwnw
23 => nwnenwnw
24 => wnwnenwnw
25 => nwnwnwnw

```

Shortest answer in bytes wins!

# Answer
> 21 votes
# Python 2, 64 bytes

```
def f(n):d=0x1211252b5375>>2*n-4&3;print"nwes"[d];f(n+d*3+d%2-5)

```

Try it online!

A function that prints one direction per line, terminating with error.

The constant `0x1211252b5375` encodes in base 4 the direction `d` we travel from each room number as a number 0 through 3. The extraction digit `>>2*n-4&3` is also designed to give a negative shift error when `n=1`, terminating the code. We update the room number `n` via an offset that's computed from the direction `d` as `d*3+d%2-5`, which maps:

```
d   d*3+d%2-5
0  -> -5
1  -> -1
2  ->  1
3  ->  5

```

# Answer
> 10 votes
# Python 2, ~~95~~ 93 bytes

```
f=lambda n:n>1and Q[n]+f(n+[-5,5,1,-1]['nsew'.find(Q[n])])or''
Q='  wwswsnwwseenwwenwnwnenwn'

```

Try it online!

Could shave off ~~3~~ 2 bytes if 0-indexed room labeling is allowed.

# Answer
> 6 votes
# 05AB1E, ~~30~~ 29 bytes

*-1 byte thanks to a miraculous coincidence with prime numbers*

```
[Ð#•θzƶ‰`Ó•4вsè<DˆØ·5-+}'‹™¯è

```

Try it online!

```
[                      }    # infinite loop:
 Ð                          #  triplicate the room number (initially, the input)
  #                         #  break if room number == 1
   •θzƶ‰`Ó•4в               #  compressed list 202232302231102210202010
             sè             #  use the room number to index into that list
               <            #  decrement
                Dˆ          #  add a copy to the global array
                  Ø         #  nth prime (-1 => 0, 0 => 2, 1 => 3, 2 => 5)
                   ·        #  double
                    5-      #  subtract 5
                      +     #  add that to the room number
'‹™                         # dictionary string "western"
   ¯                        # push the global array
    è                       # index (wraps around, so -1 => n, 0 => w, 1 => e, 2 => s)

```

# Answer
> 5 votes
# Ruby, ~~72~~ 62 bytes

```
f=->n{n<2?'':' en  sw'[x=4*18139004[n]+6*4267088[n]-5]+f[n+x]}

```

Try it online!

### How?

The trick here is to use 2 constants to build the next step for each cell, then recursively solve the problem.

The 2 constants 18139004 and 4267088 are binary strings giving the direction of the next move, by extracting a single bit from both for each cell, we can get:

```
"n" = 4*0+6*0-5 = -5
"w" = 4*1+6*0-5 = -1
"e" = 4*0+6*1-5 = +1
"s" = 4*1+6*1-5 = +5

```

Easier than shifting around and masking a single big binary number IMHO.

When we get the direction, we extract the corresponding letter from the string " en sw":

```
  1   5
  |   |
" en  sw"
   |   |
  -5  -1

```

And proceed recursively on the cell \[n+x\]

# Answer
> 4 votes
# JavaScript (ES7),  ~~62~~  58 bytes

Port of xnor's answer.

```
f=n=>--n?"nwes"[d=79459389361621/4**n&3]+f(n+d*3+d%2-4):''

```

Try it online!

# Answer
> 3 votes
# Perl 5 (`-n`), 94 bytes

-5 bytes thanks to Grimy

```
@A=map/./g,__wwswsnwwseenwwenwnwnenwn;%H=(n,-5,s=>5,e,1,w,-1);$_+=$H{$,=$A[$_]},say$,until$_<2

```

TIO

# Answer
> 3 votes
# Perl 5, 79 bytes

```
say$,while$_+={n,-5,s=>5,e,1,w,-1}->{$,=substr _wwwswsnwwseenwwenwnwnenwn,$_,1}

```

Try it online!

# Answer
> 2 votes
# JavaScript, ~~80~~ ~~73~~ 71 bytes

Adapted from Chas' Python solution so please `+1` him, too.

```
f=n=>--n?(d=" wwswsnwwseenwwenwnwnenwn"[n])+f(n+~~{n:-4,s:6,e:2}[d]):``

```

Try it Online!

1 byte saved thanks to Arnauld.

# Answer
> 2 votes
# PHP, 110 bytes

A solution which isn't a port of Chas Brown's great answer or xnor's great answer. I know this is longer but I wanted to have a different solution!

```
for($n=$argn;$n>1;$n=ord($s[$n*2+1])%30)echo($s='0000w<w sEw"s)n w%w&s-e*e+n&w+w,e/n*w/n,w1n.e5n0w5n2')[$n*2];

```

Try it online!

I have created a mapping string which has 2 characters for every cell in the board. First character for each cell is a move (n/e/s/w) or `0` and the second character's ASCII code mod 30 will return another cell number which we should follow its move in recursive mode until we get to exit cell (`cell < 2`).

For example for input of 8:

* 2 characters for cell `8` are: `w%`
* It means print `w` and continue with moves for cell of `%`
* ASCII code of `%` is 37 which mod 30 will be 7, so next cell to follow is `7`.
* 2 characters for cell `7` are: `n`  (last character is space, ASCII code = 32)
* It means print `n` and continue with moves for cell of 32 mod 30 which is `2`.
* 2 characters for cell `2` are: `w<` (last character ASCII code = 60)
* It means print `w` and continue with moves for cell of 60 mod 30 which is `0`.
* If cell number is less than `2`, loop stops!
* Final printed result: `wnw`

---

# PHP, 75 bytes

This version is written by Grimy, it is 35 bytes shorter than my original answer because he/she is smarter! Grimy's comment: *"4 * 25 \< 256, so you only need 1 byte per cell, not 2"*

```
for($n=$argn;$n=ord("0\0~f;6o4R:s%ql&rup*@^tIDbx"[$n%25]);)echo news[$n%4];

```

Try it online!

---

# PHP, 71 bytes

This port of Arnauld's answer which is port of xnor's answer, but as a loop instead of recursive function, since it turns out to be shorter in PHP.

```
for($n=$argn;--$n;$n+=$d*3+$d%2-4)echo nwes[$d=79459389361621/4**$n&3];

```

Try it online!

# Answer
> 2 votes
# Charcoal, ~~43~~ 40 bytes

```
ＮθＷ⊖θ«≔Ｉ§”)“⊞x⟧∧⎚⁵2”ιι§nwesι≧⁺⁻⁺﹪ι²×³ι⁵θ

```

Try it online! Link is to verbose version of code. Based on both @ChasBrown's and @xnor's answers. Explanation:

```
Ｎθ

```

Input the room.

```
Ｗ⊖θ«

```

Set the loop variable `i` to one less than the room number and repeat while it is non-zero.

```
«≔Ｉ§”)“⊞x⟧∧⎚⁵2”ιι

```

Extract the direction from the compressed string `0113130113220112010102010`. (The leading `0` is just a filler digit.)

```
§nwesι

```

Print the direction.

```
≧⁺⁻⁺﹪ι²×³ι⁵θ

```

Use @xnor's formula to calculate the new room number.

# Answer
> 2 votes
# Jelly, ~~30~~ 29 bytes

```
“þ&ƊĿñ÷°e’b6Ḥ_5Ż⁸+ị¥ƬI‘ị“®ȯẹ»

```

Try it online!

A monadic link taking the starting cell and returning a string with the directions.

I love the fact that Jelly’s dictionary has a word like ‘Kennesaw’ (a city northwest of Atlanta, Georgia), used here because indexing into it with `[5, 1, -5, -1] + 1` gives `nesw`!

## Explanation

```
“þ...e’                    | Base-250 integer 1962789844189344852
       b6                  | Convert to base 6 (2, 2, 5, 2, 5, 0, 2, 2, 5, 3, 3, 0, 2, 2, 3, 0, 2, 0, 2, 0, 3, 0, 2, 0)
         Ḥ                 | Double
          _5               | Subtract 5
            Ż              | Prepend 0
             ⁸  ¥Ƭ         | Using this as the right argument and the original link argument as the left argument, loop the following as a dyad until there is no change, collecting up results
              +            | - Add the left argument to:
               ị           |   - The left argument indexed into the right argument
                  I        | Differences between consecutive numbers
                   ‘       | Increment by 1
                    ị“®ȯẹ» | Index into "Kennesaw"

```

# Answer
> 2 votes
# C (clang), 81 bytes

```
v;f(p){p-1&&putchar(v="00wwswsnwwseenwwenwnwnenwn"[p])+f(p+=v%5?6-v%8:v%2?5:-5);}

```

Try it online!

Thanks to @Tommylee2k suggestion -8! \+ recursive call

# C (clang), 90 bytes

```
v;f(p){for(char*l="00wwswsnwwseenwwenwnwnenwn";p-1;p+=v%5?6-v%8:v%2?5:-5)putchar(v=l[p]);}

```

Try it online!

Similar to all not compressed solutions.

# Answer
> 1 votes
# 05AB1E, ~~45~~ 43 bytes

```
õ?[Ð#.•DUo¢ê`Ω÷‰₂¡)R€ûK•¦sè©?Ž₁9₂в6-'€Ã®kè+

```

Port of *@ChasBrown*'s Python 2 answer.

Try it online or verify all test cases.

**Explanation:**

```
õ?               # Output an empty string
                 # (to overwrite the implicit output if the input is 1)
[                # Start an infinite loop:
 Ð               #  Triplicate the top of the stack
                 #  (which is the (implicit) input in the first iteration)
  #              #  If it's exactly 1: stop the infinite loop
  .•DUo¢ê`Ω÷‰₂¡)R€ûK•
                 #  Push compressed string "a  wwswsnwwseenwwenwnwnenwn"
   ¦             #  Remove the first character
    sè           #  Swap to get the number, and use it to index into the string
      ©          #  Store it in variable `®` (without popping)
       ?         #  Print it without trailing newline
  Ž₁9            #  Push compressed integer 22449
     ₂в          #  Convert to base-26 as list: [1,7,5,11]
       6-        #  Subtract 6 from each: [-5,1,-1,5]
         '€Ã    '#  Push dictionary string "news"
            ®k   #  Get the index in this string of character `®`
              è  #  And use that to index into the integer-list
               + #  And add it to the originally triplicated integer

```

See this 05AB1E tip of mine (all four sections) to understand why `.•DUo¢ê`Ω÷‰₂¡)R€ûK•` is `"a wwswsnwwseenwwenwnwnenwn"`; `Ž₁9` is `22449`; `Ž₁9₂в` is `[1,7,5,11]`; and `'€Ã` is `"news"`.

# Answer
> 1 votes
# Bash, 120 bytes

```
S=__wwswsnwwseenwwenwnwnenwn
N=n-5w-1s05e01
for((i=$1;$i>1;i+=$j)){ d=${S:$i:1};j=${N:`expr index $N $d`:2};printf $d; }

```

Try it online!

I toyed for a while with trying to bit-pack the string as nibbles, but the decoding would require more characters than the number saved.

### How it works:

```
S=__wwswsnwwseenwwenwnwnenwn

```

String $S holds a single character (n,w,s,e) for each room showing which direction to take to move one room towards the exit, skipping rooms 0 and 1.

```
N=n-5w-1s05e01

```

String $N has the delta to add to/subtract from the current room number for each direction change (n: -5, w: -1, s: +5, e: +1)

```
for((i=$1;$i>1;i+=$j)){ d=${S:$i:1};j=${N:`expr index $N $d`:2};printf $d; }

```

Start with $i equal to the room number given on the command line ($1). Assign the character at index $i in string $S to $d. Retrieve the delta value from $N for the direction to take to the next room, assigning it to $j.

Print the next direction to take in $d.

Add/subtract the delta in $j to/from $i.

Loop until we leave room #2 (while $i\>1).

# Answer
> 1 votes
# Stax, 31 bytes

```
α-J╒Θ▀╣ô¥$v╞||T←]┬yΣ╨z§£sU╕τR"┌

```

Run and debug it

# Answer
> 1 votes
# Kotlin, 112 bytes

```
val d="  113130113220112010102010"
fun p(r:Int):String=if(r>1)"nwes"[d[r]-'0']+p("046:"[d[r]-'0']-'5'+r)
else ""

```

Try it online!

---
Tags: code-golf, kolmogorov-complexity
---


# Question
Title: How to reduce EXE size of x86 ASM compiled with FASM?
As an exercise, I've created a simple solution for this challenge, in x86 Assembly Language. I'm running this with FASM on Windows. Here's my source code:

```
format PE console
entry start

include 'WIN32A.inc'

section '.text' code executable
start:
    push    char            ; Start at 'A'
    call    [printf]        ; Print the current letter 4 times
    call    [printf]
    call    [printf]
    call    [printf]
    inc     [char]          ; Increment the letter
    cmp     [char], 'Z'     ; Compare to 'Z'
    jle     start           ; char <= 'Z' --> goto start

section 'r.data' data readable writeable
    char    db  'A', 10, 0  ; Stores the current letter

section '.idata' data readable import
    library  msvcrt,   'msvcrt.dll'
    import   msvcrt, printf, 'printf'

```

When I compile this, I get an executable larger than I expected. Here's a hexdump:

https://pastebin.com/W5sUTvTe

I notice there's a lot of empty space between the code section and the data and library import sections, as well as a message saying "This program cannot be run in DOS mode" embedded in the code. How can I assemble my source code to a small file, suitable for Code Golf?

As a side note, suggestions for better ways to print to `stdout` without importing `msvcrt` and calling `printf` are welcome.

# Answer
Quite a bit general tip, but

# Use COM file format instead of PE EXE.

PE EXE has a few flaws making the format pretty much useless in code-golf. First one is the image aligning (Windows won't run the EXE file if it's not aligned properly), and the second one is the header size. There are a few factors that aren't this important (dividing the executable into sections).

Advantages of using COM file format (that is pretty much equivalent to flat binary) are:

* Zero header code, file isn't divided into sections
* No image aligning (so the image size might not be divisible by a strictly defined power of two, but it has to be smaller than 65K. It doesn't change much though, because if your submission is larger than 65K, you're doing something wrong).
* You can't use external libraries - this is actually a plus, because you without doubt have other way to perform I/O. That's where BIOS interrupts come handy.
* You have direct control over the memory and devices linked up to the system, therefore there is no paging, no access violations, no memory protection, no concurrency, so on and so forth. These *features* make it easier to golf really creative programs.

I've revised your code to work as flat binary. It's dead simple:

```
ORG 100H

MOV DX, P
MOV AH, 9

L:
    INT 21H
    INT 21H
    INT 21H
    INT 21H

    INC BYTE [P]
    CMP BYTE [P], 'Z'
    JLE L

MOV AX, 4C00h
INT 21h

P DB "A", 10, "$"

```

The output binary is just 32 bytes big. I believe, it's possible to reduce the size even further, but this is just a starting point.

Assemble with `nasm -fbin file.asm -o file.com`. Note, this example has been made for NASM, but you can translate it freely to FASM, and it will work flawlessly.
> 3 votes

---
Tags: code-golf, tips, assembly
---


title: Fix my stuttered words

text:
# Question
Title: Fix my stuttered words
Stuttering is a problem which many of us might have experienced or at least seen it. Although most of famous speech recognition softwares have serious issues with stuttered speaking, let's imagine a software which understands stuttering, but cannot fix them and only writes them as is.

An example written text by such a software can be like this: ***"please be ca ca careful"***. In this example ***"careful"*** is the original word and ***"ca ca"*** are the stuttered words.

## Challenge

Write a program or function that fixes stuttered words by removing them from the input while keeping the original words. For example fixed version of ***"please be ca ca careful"*** would be ***"please be careful"***.

This is , shortest answer in every language wins!

## What are stuttered words?

Stuttering has many different variations. But for simplicity of this challenge, we are going to limit it to the following rules:

* Stuttered words can be an uncompleted part or whole of the original word. By "uncompleted part" I mean that the original word should start exactly with the stuttered word. For example ***"ope"*** and ***"open"*** both can be a stuttered word for ***"open"***, but ***"pen"*** cannot be one since ***"open"*** doesn't start with ***"pen"***.
* Stuttered words must contain at least one of the ***"aeiou"*** vowels. For example ***"star"*** can be a stuttered word for ***"start"*** as it contains ***"a"***, but ***"st"*** cannot be a stuttered word as it doesn't contain any of the mentioned vowels.
* Stuttered words can only appear before the original word and should be repeated at least two times to be valid (the original word doesn't count in the repeats). For example ***"o o open"*** has stuttered words but ***"o open o"*** doesn't, because the ***"o"*** after the original word doesn't count and ***"o"*** before the original word is not repeated at least two times. ***"go go go go go go"*** has five repeats of stuttered words before the original word and is valid.
* A single set of repeated stuttered words cannot contain mixed forms and the words should be exactly like each other. For example ***"op o op open"*** doesn't count as stuttered words. On the other hand ***"o op op open"*** has stuttered words because the first ***"o"*** is seen as a whole different word here and the two ***"op"s*** are counted as stuttered words of ***"open"***.
* In case of multiple valid sets of repeated stuttered words right after each other, only the last original word stays. For example, in ***"o o o op op op open"***, the ***"o o o"*** part is seen as stuttered words of the first ***"op"***, so they should be removed and then ***"op op op"*** is seen as stuttered words of ***"open"*** and they should be removed too, so only the ***"open"*** will be left after removal of stuttered words. You can assume that multiple valid sets of repeated stuttered words only happen from left to right, so fixing ***"op op o o o open"*** would result in ***"op op open"*** (a.k.a. we do not fix again after fixing once).

## Input

* Input is a single line string containing only ASCII English letters (a-z), digits (0-9) and space characters. Letter casing is not important and you can decide to accept lowercase or uppercase or both of them, but the casing should stay the same and you cannot change it in the output.
* You can use a list of letters (like `["l","i","s","t"," ","o","f"," ","l","e","t","t","e","r","s"]`) instead of the string, but you cannot use a list of words. If your language has a different input structure, use it. The point is that input shouldn't be separated by words, so cost of separating words in some languages might actually trigger other creative solutions.
* The input might contain none, one or multiple stuttered words in it.
* Words and or numbers are separated by a single space and input will not contain double spaces right next to each other.

## Output

* A string or a list of letters or the appropriate structure in your language with all stuttered words removed from the input.
* Output words should be separated by exactly one space (same as input).
* Single leading and trailing newline or space are allowed.

Standard loopholes are forbidden.

## Test cases

No stuttered words:

```
"hello world" => "hello world"

```

A single instance of repeated stuttered words:

```
"ope ope ope ope open the window" => "open the window"

```

Multiple instances of repeated stuttered words:

```
"there is is is is something un un under the the the table" => "there is something under the table"

```

No stuttered words, not repeated enough:

```
"give me the the book" => "give me the the book"

```

No stuttered words, don't have any of the mentioned vowels:

```
"h h help m m m me" => "h h help m m m me"

```

Numbers aren't stuttered words, they don't have any of the mentioned vowels:

```
"my nu nu number is 9 9 9 9876" => "my number is 9 9 9 9876"

```

But a word with both vowels and numbers can have stuttered words:

```
"my wi wi windows10 is slow" => "my windows10 is slow"

```

Different forms of stuttered words in same repeat group aren't counted:

```
"this is an ant antarctica does not have" => "this is an ant antarctica does not have"

```

For multiple continuous sets of stuttered words right after each other, only keep the last original word:

```
"what a be be be beauti beauti beautiful flower" => "what a beautiful flower"

```

This isn't a case of multiple continuous sets of stuttered words right after each other:

```
"drink wat wat wa wa water" => "drink wat wat water"

```

Empty input:

```
"" => ""

```

More cases from comments:

```
"a ab abc" => "a ab abc"
"a ab ab abc" => "a abc"
"ab ab abc abcd" => "abc abcd"
"a a ab a able" => "ab a able"
"i have ave ave average" => "i have average"
"my wi wi windows 10 is cra cra crap" => "my windows 10 is crap"

```

### An easy to copy list of the above test cases:

```
"hello world",
"ope ope ope ope open the window",
"there is is is is something un un under the the the table",
"give me the the book",
"h h help m m m me",
"my nu nu number is 9 9 9 9876",
"my wi wi windows10 is slow",
"this is an ant antarctica does not have",
"what a be be be beauti beauti beautiful flower",
"drink wat wat wa wa water",
"",
"a ab abc",
"a ab ab abc",
"ab ab abc abcd",
"a a ab a able",
"i have ave ave average",
"my wi wi windows 10 is cra cra crap"

```

# Answer
## C (gcc), ~~183~~ ~~180~~ 178 bytes

```
f(s,t,u,T,e,r)char*s,*t,*u,*r;{for(;s=index(u=s,32);T>1&strpbrk(u,"aeiou")-1<s&&memmove(s=u,t-e,r-t-~e))for(e=++s-u,r=u+strlen(t=u),T=0;(t+=e)<r&!memcmp(u,t,e-1)&t[-1]==32;++T);}

```

Try it online!

Well, C certainly can't compete with the brevity of regex...

This one's particularly tough to read because I ended up collapsing the entire function into a single nested pair of `for` loops (with no body!). That makes the evaluation order all wonky -- the code near the beginning actually executes last.

My favorite trick here is `strpbrk(u,"aeiou")-1<s`. This is used to check whether the repeated word contains vowels. `u` points to the start of the repeated word, and `s` points to the second repetition of the word; for example:

```
"my nu nu number is 9 9 9 9876"
    ^  ^
    u  s

```

`strpbrk` then finds the first character in `"aeiou"` that appears after `u`. (In this case, it is the `'u'` immediately after.) Then we can check that this comes before `s` to verify the word contains a vowel. But there's a slight issue - `strpbrk` returns `NULL` (i.e. `0`) if there's no vowel in the entire string. To fix this, I simply subtract 1, which turns `0` into `0xffffffffffffffff` (on my machine) due to overflow. Being the maximum value of a pointer, this is decidedly greater than `s`, causing the check to fail.

Here's a slightly older version (before the transformation that muddled up control flow) with comments:

```
f(s,t,u,c,n,e)char*s,*t,*u,*e;{
    // set s to the position of the *next* check; u is the old position
    for(;s=index(u=s,32);) {
        // count the length of this word (incl. space); also fix s
        n=++s-u;
        // find the end of the string; assign temp pointer to start
        e=u+strlen(t=u);
        // count repetitions of the word
        for(c=0;                // number of repetitions
            (t+=n)              // advance temp pointer by length of word
            <e&&                // check that we haven't hit the end...
            !strncmp(u,t,n-1)&& // ...and the word matches...
            t[-1]==32;          // ...and the previous character was space
            ++c);               // if so, increment count
        // decide whether to remove stuttering
        c>1&&                    // count must be at least 2
        strpbrk(u,"aeiou")-1<s&& // word must contain a vowel
        // if so, move everything after the last occurrence back to the
        // beginning, and also reset s to u to start scanning from here again
        memmove(s=u,t-n,e-t+n+1);
    }
}

```

Thanks to @user1475369 for 3 bytes and @ceilingcat for 2 bytes.
> 6 votes

# Answer
# Perl 5 (-p), 34 bytes

*Based on Arnauld's deleted answer.*

```
s/(\b(\w*[aeiou]\w*) )\1+(?=\2)//g

```

Try it online!
> 4 votes

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

*-1 byte thanks to Kevin Cruijssen*

```
#Rγε®y¬©žMÃĀiнkĀDygαΘ+∍]R˜ðý

```

Try it online!

05AB1E, having no regexes, definitely doesn't look like the best tool for this task. Still, it somehow manages to just barely beat Retina.

```
#                     # split on spaces
 R                    # reverse the list of words
  γ                   # group consecutive identical words together

ε                   ] # for each group of words y:
 ®                    #  push the previous word on the stack (initially -1)
  y                   #  push another copy of y
   ¬                  #  push the first element without popping
    ©                 #  save the current word for the next loop
     žM               #  built-in constant aeiou
       ÃĀi          ] #  if the length of the intersection is non-zero:
           н          #   take the first element of y
            kĀ        #   0 if the previous word starts with this word, 1 otherwise
              D       #   duplicate
               yg     #   length of y (the number of consecutive identical words)
                 α    #   subtract the result of the startsWith check
                  Θ   #   05AB1E truthify (1 -> 1, anything else -> 0)
                   +  #   add the result of the startsWith check
                    ∍ #   set the length of y to that value
                      #  otherwise leave y unchanged

˜                     # flatten the modified list of groups of words
 R                    # reverse the list of words
  ðý                  # join with spaces

```
> 3 votes

# Answer
# Perl 6, 45 bytes

```
{S:g/<|w>(\S*<[aeiou]>\S*)\s$0+%%\s{}<?$0>//}

```

Try it online!

A simple regex answer that substitutes all matches of stutters with the empty string.
> 1 votes

# Answer
# Stax, 26 bytes

```
å╬↓<▀.₧▀"╦n▐∞↨vß%ù:Qa3@=↔_

```

Run and debug it

Direct port from @Grimy's perl answer. Stax is able to shrink the regex pattern literal, and it has a vowels constant which is able to shrink `[aeiou]`.
> 1 votes

# Answer
# Clean, 184 bytes

```
import StdEnv,Data.List,Text
$s=join[' '](f(group(split[' ']s)))
f[[a]:t]=[a:f t]
f[h=:[a:_]:t=:[[b:_]:_]]|intersect['aeiou']a==[]=h++f t|isPrefixOf a b=f t=if(h>[a,a])[a]h++f t
f[]=[]

```

Try it online!

Defines `$ :: [Char] -> [Char]`, which splits the input string on spaces and groups identical elements which are then collapsed by the helper `f :: [[[Char]]] -> [[Char]]`, joining before returning.
> 1 votes

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


title: Irish Snap: Variant Rules

text:
# Question
Title: Irish Snap: Variant Rules
# Introduction

Recently, me and a couple of my friends decided to play some cards, and one of them suggested the game 'Irish Snap', which was the inspiration for this challenge. However, I later learnt that the game has a lot of different rules that you can play with, some of which are listed here. The rules that are in this challenge aren't currently listed on that page, hence the name, 'Variant Rules'

# The Challenge

Given an array of 3 cards, output a truthy or falsey value depending on if they make a valid snap in a game of Irish snap.

# Input

The input will be an array of 3 numbers, ranging from 1-13 inclusive, with 1 representing an ace, 11 representing a jack, 12 representing a queen and 13 representing a king. The input can be in any order of top, middle, bottom.

# Rules

The 4 different criteria for if cards make an Irish snap are:

* The top and middle cards are the same
* The top and middle cards have a difference of one
* The top and bottom cards are the same
* The top and bottom cards have a difference of one

If any of these criteria are met, you must output a truthy value. As well as this, for the two criteria that require the cards to have a difference of one, it 'wraps around', meaning that an ace and a king are considered to have a difference of one, and vice versa.

# Test Cases

```
Input (Bottom, Middle, Top) -> Output
1 13 7 -> False
1 4 13 -> True
9 3 6 -> False
8 9 7 -> True
2 6 5 -> True
12 5 11 -> True
10 4 8 -> False
12 13 7 -> False
9 7 10 -> True
7 3 1 -> False
4 2 3 -> True

```

# Answer
> 4 votes
# Perl 6, 16 bytes

```
3>(*-(*|*)+1)%13

```

Try it online!

Anonymous whatever lambda that takes input as `top, middle, bottom` and returns a Junction that evaluates to True or False

# Answer
> 4 votes
# Python 3, 38 bytes

```
lambda x,y,z:{x-y,x-z}&{0,1,12,-1,-12}

```

Try it online!

Returns a non-empty set (truthy) if valid, empty set (falsey) if not. Takes input in order top-middle-bottom, but can be rearranged for same code size.

# Answer
> 3 votes
# 05AB1E, ~~7~~ 6 bytes

```
α12%ß!

```

Try it online!

Takes inputs as `[middle, bottom], top`.

```
α        # absolute difference
 12%     # mod 12
    ß    # minimum
     !   # factorial

```

Only 1 is truthy in 05AB1E. 0! and 1! are both 1, while no other number has a factorial of 1.

# Answer
> 2 votes
# , 12 bytes

```
1 e.2>12||@-

```

Try it online!

Taking bottom middle as left arg, top as right arg.

# original answer taking input as one list

# , 24 bytes

```
1 e.2>#:@3 5(12||@-/)@#]

```

Try it online!

* `#:@3 5` The numbers 3 and 5 in binary are `0 1 1` and `1 0 1` which are the masks for the middle/top and bottom/top cards respectively
* `(12||@-/)@#` We filter the input with those masks, take the abs value of the resulting differences, then the remainder when divided by 12 (for the ace-king case)
* `1 e.2>` are either of the resulting numbers less than 2, ie, 0 or 1?

# Answer
> 2 votes
# JavaScript (ES6), 29 bytes

Takes input as `([bottom, middle])(top)`.

The output is inverted.

```
a=>c=>a.every(n=>(n-c)/2%6|0)

```

Try it online!

---

# JavaScript (ES6),  ~~37~~  30 bytes

*Saved 1 byte thanks to @Grimy*

Takes input as `([bottom, middle])(top)`.

```
a=>c=>a.some(n=>(n-=c)*n%72<2)

```

Try it online!

# Answer
> 2 votes
# Charcoal, 12 bytes

```
›²⌊﹪↔⁻Ｅ²ＮＮ¹²

```

Try it online! Port of @Grimy's answer. Takes input as three separate values bottom, middle, top, and outputs using Charcoal's default Boolean format of `-` for true, nothing for false. Explanation:

```
 ²              Literal 2
›               Is greater than
  ⌊             Minimum of
    ↔            Absolute value of (vectorised)
      Ｅ²Ｎ       First two numeric inputs as a list ([bottom, middle])
     ⁻          Minus (vectorised)
         Ｎ      Third input (top)
   ﹪            Modulo (vectorised)
          ¹²    Literal 12

```

# Answer
> 1 votes
# Pyth, ~~12~~ 11 bytes

Takes input as `[bottom, top, middle]` or `[middle, top, bottom]` (both work). Outputs `[]` (Falsy in Pyth) if there's no valid snap, a non-empty array otherwise.

```
f>2%.aT12.+

```

Try it online!

If a consistent truthy/falsy value is required, add `.A` in front for +2 bytes. Then output will be `True` or `False`.

## Explanation

```
  f             # Filter on lambda T:
   >2           # 2 >
      .aT       #     abs(T)
     %   12     #            % 12
           .+   # the list of deltas (difference between consecutive elements)

.A (if required)# Any truthy values in the above list?

```

Edit: -1 with a different approach

# Answer
> 1 votes
# Perl 5 `-ap`, 31 bytes

```
$t=<>}{$\|=abs($t-$_)%12<2for@F

```

Try it online!

### Input:

```
bottom middle
top

```

Actually, the order of the middle and bottom doesn't matter.

### Output:

`0` for false; `1` for true

# Answer
> 1 votes
# Jelly, 6 bytes

```
ạ%12ṠƑ

```

Try it online!

# Answer
> 1 votes
# C (gcc), 47 43 bytes

```
f(b,m,t){return(1<<t-m|1<<t-b)&0x80101003;}

```

Try it online!

# Answer
> 1 votes
# Japt, 7 bytes

```
d_aV <2

```

Try it

# Answer
> 1 votes
# T-SQL 2008, 40 bytes

```
PRINT 1/-~abs((@-@2)%12/2*((@-@3)%12/2))

```

**Try it online**

# Answer
> 1 votes
# Jelly, 6 bytes

```
I%12ỊẸ

```

Try it online!

A monadic link taking the list of `[middle, top, bottom]` as its argument and returning `1` for snap and `0` for no snap.

# Answer
> 0 votes
# \[R\], 23 bytes

takes input as a=c(bottom,top,middle):

`any(abs(diff(a))%%12<2)`

---
Tags: code-golf, decision-problem, card-games
---


title: Local periods of strings

text:
# Question
Title: Local periods of strings
## Local periods

Take a non-empty string **s**. The *local period* of **s** at index **i** is the smallest positive integer **n** such that for each **0 ≤ k \< n**, we have **s\[i+k\] = s\[i-n+k\]** whenever both sides are defined. Alternatively, it is the minimal length of a nonempty string **w** such that if the concatenation **w w** is placed next to **s** so that the second copy of **w** begins at index **i** of **s**, then the two strings agree wherever they overlap.

As an example, let's compute the local period of **s = "abaabbab"** at (0-based) index 2.

* Try **n = 1**: then **s\[2+0\] ≠ s\[2-1+0\]**, so this choice is not correct.
* Try **n = 2**: then **s\[2+0\] = s\[2-2+0\]** but **s\[2+1\] ≠ s\[2-2+1\]**, so this is also not correct.
* Try **n = 3**: then **s\[2+0-3\]** is not defined, **s\[2+1\] = s\[2-3+1\]** and **s\[2+2\] = s\[2-3+2\]**. Thus the local period is 3.

Here is a visualization of the local periods using the second definition, with semicolons added between the two copies of **w** for clarity:

```
index      a b a a b b a b      period
 0       a;a                     1
 1       b a;b a                 2
 2       a a b;a a b             3
 3             a;a               1
 4     b b a b a a;b b a b a a   6
 5                 b;b           1
 6               a b b;a b b     3
 7                   b a;b a     2

```

Note that **w** is not necessarily a substring of **s**. This happens here in the index-4 case.

## The task

Your input is a nonempty string **s** of lowercase ASCII characters. It can be taken as a list of characters if desired. Your output shall be the list containing the local period of **s** at each of its indices. In the above example, the correct output would be **\[1,2,3,1,6,1,3,2\]**.

The lowest byte count in each language wins. Standard rules apply.

## Test cases

```
a -> [1]
hi -> [1, 2]
www -> [1, 1, 1]
xcxccxc -> [1, 2, 2, 5, 1, 3, 2]
abcbacb -> [1, 4, 7, 7, 7, 3, 3]
nininini -> [1, 2, 2, 2, 2, 2, 2, 2]
abaabbab -> [1, 2, 3, 1, 6, 1, 3, 2]
woppwoppw -> [1, 4, 4, 1, 4, 4, 4, 1, 4]
qwertyuiop -> [1, 10, 10, 10, 10, 10, 10, 10, 10, 10]
deededeededede -> [1, 3, 1, 5, 2, 2, 5, 1, 12, 2, 2, 2, 2, 2]
abababcabababcababcabababcaba -> [1, 2, 2, 2, 2, 7, 7, 7, 7, 2, 2, 2, 19, 19, 5, 5, 2, 5, 5, 12, 12, 2, 2, 2, 7, 7, 5, 5, 2]

```

# Answer
# Java 8, ~~167~~ ~~154~~ 152 bytes

```
s->{int l=s.length,r[]=new int[l],i=0,n,k;for(;i<l;r[i++]=n)n:for(n=0;;){for(k=++n;k-->0;)if(i+k<l&i+k>=n&&s[i+k]!=s[i-n+k])continue n;break;}return r;}

```

-2 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
s->{                          // Method with char-array parameter and int-array return-type
  int l=s.length,             //  Length of the input-array
      r[]=new int[l],         //  Result-array of the same size
      i=0,n,k;                //  Integers `i`, `n`, and `k` as defined in the challenge
  for(;i<l;                   //  Loop `i` in the range [0, `l`):
      r[i++]=n)               //    After every iteration: Add `n` to the array
    n:for(n=0;;){             //   Inner loop `n` from 0 upwards indefinitely
      for(k=++n;k-->0;)       //    Inner loop `k` in the range [`n`, 0]:
                              //    (by first increasing `n` by 1 with `++n`)
        if(i+k<l&i+k>=n)      //     If `i+k` and `i-n+k` are both within bounds,
           &&s[i+k]!=s[i-n+k])//     and if `s[i+k]` is not equal to `s[i-n+k]`:
          continue n;         //      Continue loop `n`
                              //    If we haven't encountered the `continue n` in loop `k`:
      break;}                 //     Break loop `n`
  return r;}                  //  Return the result

```
> 4 votes

# Answer
# Retina, ~~89~~ 86 bytes

```
.
$`¶$<'¶
/(^|.+)¶.+/_(Lw$`^(.+)?(.*)(.+)?¶(?(1)|(.*))\2(?(3)$)
$2$3$4
G`.
%C`.
N`
0G`

```

Try it online! Edit: Saved 3 bytes thanks to @MartinEnder. Explanation:

```
.
$`¶$<'¶

```

Split the input at each character, creating a pair of lines, one for the prefix and one for the suffix of the prefix.

```
/(^|.+)¶.+/_(

```

Run the rest of the script on each resulting pair.

```
Lw$`^(.+)?(.*)(.+)?¶(?(1)|(.*))\2(?(3)$)
$2$3$4

```

Find all overlapping matches and list the results. (See below.)

```
G`.

```

Discard the empty match.

```
%C`.

```

Take the length of each match.

```
N`

```

Sort numerically.

```
0G`

```

Take the smallest.

The matching works by splitting the prefix and suffix into three parts. There are four valid cases to consider:

```
AB|BC   B matches B to the left and B to the right
B|ABC   AB matches [A]B to the left and AB to the right
ABC|B   BC matches BC to the left and B[C] to the right
BC|AB   ABC matches [A]BC to the left and AB[C] to the right

```

The regex therefore only allows A and C to match on one side at a time.
> 4 votes

# Answer
# JavaScript (ES6), 84 bytes

Takes input as an array of characters.

```
s=>s.map((_,i)=>s.some(_=>s.every(_=>k<j|!s[k]|s[k-j]==s[k++]|k-i>j,++j,k=i),j=0)*j)

```

### Test cases

```
let f =

s=>s.map((_,i)=>s.some(_=>s.every(_=>k<j|!s[k]|s[k-j]==s[k++]|k-i>j,++j,k=i),j=0)*j)

console.log(JSON.stringify(f([...'a']))) // [1]
console.log(JSON.stringify(f([...'hi']))) // [1, 2]
console.log(JSON.stringify(f([...'www']))) // [1, 1, 1]
console.log(JSON.stringify(f([...'xcxccxc']))) // [1, 2, 2, 5, 1, 3, 2]
console.log(JSON.stringify(f([...'abcbacb']))) // [1, 4, 7, 7, 7, 3, 3]
console.log(JSON.stringify(f([...'nininini']))) // [1, 2, 2, 2, 2, 2, 2, 2]
console.log(JSON.stringify(f([...'abaabbab']))) // [1, 2, 3, 1, 6, 1, 3, 2]
console.log(JSON.stringify(f([...'woppwoppw']))) // [1, 4, 4, 1, 4, 4, 4, 1, 4]
console.log(JSON.stringify(f([...'qwertyuiop']))) // [1, 10, 10, 10, 10, 10, 10, 10, 10, 10]
console.log(JSON.stringify(f([...'deededeededede']))) // [1, 3, 1, 5, 2, 2, 5, 1, 12, 2, 2, 2, 2, 2]
console.log(JSON.stringify(f([...'abababcabababcababcabababcaba']))) // [1, 2, 2, 2, 2, 7, 7, 7, 7, 2, 2, 2, 19, 19, 5, 5, 2, 5, 5, 12, 12, 2, 2, 2, 7, 7, 5, 5, 2]
```
> 1 votes

# Answer
# Ruby, ~~104~~ 102 bytes

```
->s{l=s.size-1
(0..l).map{|i|n=0
loop{n+=1
(n-i..l-i).all?{|k|k<0||k>=n||s[i+k]==s[i-n+k]}&&break}
n}}

```

Try it online!

A lambda accepting a string and returning an array.

-2 bytes: Swap range endpoints with index bound guards

Ungolfed:

```
->s{
  l=s.size-1                # l is the maximum valid index into s
  (0..l).map{ |i|           # i is the current index
    n=0                     # n is the period being tested
    loop{                   # Repeat forever:
      n+=1                  # Increment n
      (n-i..l-i).all?{ |k|  # If for all k where i+k and i-n+k are valid indexes into s
        k<0 || k>=n ||      #   We need not consider k OR
          s[i+k]==s[i-n+k]  #   The characters at the relevant indexes match
      } && break            # Then stop repeating
    }
  n                         # Map this index i to the first valid n
  }
}

```
> 1 votes

# Answer
# Japt, ~~33~~ 32 bytes

*Saved 1 byte thanks to @Shaggy*

```
¬Ë@¯E f'$iUtED ú.D r."($&|^)"}aÄ

```

Test it online!

### Explanation

```
¬Ë@¯E f'$iUtED ú.D r."($&|^)"}aÄ   Implicit: U = input string
¬Ë                                 Split the input into chars, and map each index E to
  @                          }aÄ     the smallest positive integer D where
   ¯E                                  the first E chars of U
      f                                matches the regex formed by
          UtED                         taking D chars of U from index E,
                ú.D                     padding to length D with periods,
                    r."($&|^)"          replacing each char C with "(C|^)",
        '$i                             and placing a '$' at the very end.

```

My first thought was to just compare each character in the left substring with the corresponding char in the right substring, as in the JS answer. That wouldn't work, however, as Japt's method to get a character just wraps to the other end of the string if the index is negative or too large.

Instead, my solution builds a regex out of the second substring and tests it on the first substring. Let's take the 5th item in test-case `abaabbab` as an example:

```
abaabbab
    ^ split point -> abaa for testing regex, bbab for making regex

   slice  regex                              matches abaa
1. b      /(b|^)$/                           no
2. bb     /(b|^)(b|^)$/                      no
3. bba    /(b|^)(b|^)(a|^)$/                 no
4. bbab   /(b|^)(b|^)(a|^)(b|^)$/            no
5. bbab.  /(b|^)(b|^)(a|^)(b|^)(.|^)$/       no
6. bbab.. /(b|^)(b|^)(a|^)(b|^)(.|^)(.|^)$/  yes: /^^ab..$/

```

The main trick is that `^` can match infinitely, up until an actual character is matched. This lets us ignore any number of characters from the start of the regex, while ensuring that the rest are all matched consecutively, finishing at the end of the test string.

I'm not sure I've explained this very well, so please let me know if there's anything you'd like clarified, or anything else that should be explained.
> 1 votes

# Answer
# C (gcc), ~~143~~ ~~142~~ ~~140~~ ~~139~~ ~~128~~ ~~126~~ ~~123~~ 119 bytes

* Saved a byte. Golfed `!b&&printf` to `b||printf`.
* Saved two bytes thanks to Kevin Cruijssen. Removed the `for` loop body parentheses by juggling the `printf` placement.
* Saved a byte. Golfed `b+=S[i+k]!=S[i-n+k]` to `b|=S[i+k]-S[i-n+k]`.
* Saved eleven bytes. Removed the need of `l=strlen(S)` by conditioning both string handling loop to break when reaching the string's end (a null byte `'\0'`).
* Saved two bytes. Golfed `i-n+k>~0` to `i-n>~k`.
* Saved three bytes thanks to ceilingcat; `b||printf("|"),n++` is equivalent to `n+=b||printf("|")`.
* Saved four bytes thanks to ceilingcat.

```
i,b,k,n;f(char*S){for(i=~0;S[++i];)for(b=n=1;b;n+=b||printf("%d,",n))for(b=0,k=i;k<n+i&&S[k];k++)b|=n>k?0:S[k]-S[k-n];}

```

Try it online!
> 1 votes

# Answer
# Python 2, 115 bytes

```
lambda s:[min(j+1for j in R(len(s))if all(s[k+~j]==s[k]for k in R(i,i-~j)if len(s)>k>j))for i in R(len(s))]
R=range

```

Try it online!
> 0 votes

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


title: Golf (6-card) Golf!

text:
# Question
Title: Golf (6-card) Golf!
# Golf Golf!

This is my first challenge, so please be gentle! The challenge is to write a program that will output the correct score for a layout in the card game "Golf."

The card game Golf has many variations. The house rules I use follow the standard rules for Six-Card Golf given by Pagat, with one slight difference. There is already a similar challenge here but I think this one is more interesting because it requires you to take the orientation of the cards into account.

Each player has a 2x3 layout of cards. By the end of each round all cards are turned face up and scored as follows:

* Each ace counts 1 point.
* Each two counts minus two points.
* Each numeral card from 3 to 10 scores face value.
* Each Jack or Queen scores 10 points.
* Each King scores zero points.
* A pair of equal cards *in the same column* scores zero points for the column (even if the equal cards are twos).
* A set of three equal cards *in the same row* scores zero points for the row (even if the equal cards are twos).

## Input

The input can be a string or array of any kind.

## Output

An integer representing the score of the Golf hand.

## Examples

These examples use the notation `A23456789TJQK` but you need not use that notation in your answer.

```
Layout
AK3
J23

Score
9
-----------------------
Layout
25Q
25J

Score
20
-----------------------
Layout
T82
T8A

Score
-1
-----------------------
Layout
QQQ
234

Score
5
-----------------------
Layout
TJQ
QTJ

Score
60
-----------------------
Layout
888
382

Score
1
-----------------------
Layout
888
888

Score
0

```

This is code golf, so the shortest answer in bytes wins!

# Answer
# Jelly, 9 bytes

```
n/aEÐḟẎḞS

```

Try it online!

-1 thanks to Jonathan Allan.

Takes input in the form of `[[A, B, C], [D, E, F]]`, where each of `A`, ..., `F` are elements in \\$(1,-2,3,4,5,6,7,8,9,10,10.1,10.2,0)\\$, representing values \\$A,2,3,4,5,6,7,8,9,T,J,Q,K\\$ respectively.
> 5 votes

# Answer
# Haskell, ~~107~~ ~~103~~ 98 bytes

```
f m=sum[min 10k|r<-m,o<-m,any(/=r!!0)r,(j,x)<-zip o r,j/=x,(k,c)<-zip[-2..]"2 KA 3456789TJQ",c==x]

```

Try it online!

Takes advantage of the fact there are only two rows. We double iterate over the rows taking a row `r` and a row `o`. When they are the same row the result will always be zero (due to the "columns" matching) so we will only consider the two iterations in which `r` and `o` refer to distinct rows. I zero out rows by first checking whether any entries in the row are not equal to the first. If the row is all equal this will be false and the list will be empty, with a sum of 0. Otherwise I zip this row with the other and iterate over the pairs that aren't equal (this zeroes out equal columns in a similar manner). Finally I index a list of card ranks starting with -2 padding with spaces as necessary to map each rank to its score. I just have to use `min 10` to clamp that index to make jacks and queens cost 10 rather than 11 and 12.

EDIT: thanks to @xnor for taking off 4 bytes! I didn't know you could put identifiers directly after number literals that's really cool!

EDIT2: Thanks again to @xnor for another 5 bytes! Great idea to iterate over the rows like that
> 4 votes

# Answer
# Charcoal, 50 bytes

```
Ｆ²⊞υＳ≔⁰ζＦ⭆υΦι∧⊙ι¬⁼λν⊙υ¬⁼λ§νμ≡ι2≧⁻²ζA≦⊕ζKω≧⁺∨ΣιχζＩζ

```

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

```
Ｆ²⊞υＳ

```

Read the layout into an array.

```
≔⁰ζ

```

Initialise the score to zero.

```
Ｆ⭆υΦι∧⊙ι¬⁼λν⊙υ¬⁼λ§νμ

```

Filter on the input, removing characters that equal all of the characters in its row or column.

```
≡ι

```

Switch over each remaining character.

```
2≧⁻²ζ

```

`2` scores `-2`.

```
A≦⊕ζ

```

`A` scores `1`. (These 4 bytes could be removed if `1` was used to denote `1`, but IMHO that's an abuse of the input format.)

Do nothing for `K`.

```
≧⁺∨Σιχζ

```

Otherwise digits score their value and other letters score `10`.

```
Ｉζ

```

Cast the sum to string for implicit print.
> 3 votes

# Answer
# JavaScript (ES6),  ~~97 95~~  93 bytes

Takes input as an array of 2 arrays of 3 characters.

```
a=>a.map((r,i)=>r.map((c,j)=>t-=c!=a[i^1][j]&r!=c+[,c,c]?{K:[],2:2,A:-1}[c]||-c||~9:0),t=0)|t

```

Try it online!

### Commented

```
a =>                        // a[] = input
  a.map((r, i) =>           // for each row r[] at position i:
    r.map((c, j) =>         //   for each card c at position j in r[]:
      t -=                  //     update t:
        c != a[i ^ 1][j] &  //       if c is not equal to the sibling card in the other row
        r != c + [, c, c] ? //       and r is not made of 3 times the same card:
          { K: [],          //         add 0 point for a King (but [] is truthy)
            2: 2,           //         subtract 2 points for a Two
            A: -1           //         add 1 point for an Ace
          }[c]              //
          || -c             //         or add the face value
          || ~9             //         or add 10 points (Jack or Queen)
        :                   //       else:
          0                 //         add nothing
    ),                      //   end of inner map()
    t = 0                   //   start with t = 0
  ) | t                     // end of outer map; return t

```
> 2 votes

# Answer
# , <sup>~~39~~</sup> 28 bytes

```
[:+/@,]<.@*]+:&(1=#@~.)"1/|:

```

Try it online!

Credit to Erik the Outgolfer and Jonathan Allen for the input encoding idea.

## explanation

A very "J" solution. I'll explain by example...

Let's take the input:

```
AK3
J23

```

and apply this encoding:

```
┌─┬──┬─┬─┬─┬─┬─┬─┬─┬──┬────┬────┬─┐
│A│2 │3│4│5│6│7│8│9│T │J   │Q   │K│
├─┼──┼─┼─┼─┼─┼─┼─┼─┼──┼────┼────┼─┤
│1│_2│3│4│5│6│7│8│9│10│10.1│10.2│0│
└─┴──┴─┴─┴─┴─┴─┴─┴─┴──┴────┴────┴─┘

```

which produces:

```
   1  0 3
10.1 _2 3

```

Let's look at the first part of the solution, eliding some detail to start:

```
] (...)"1/ |:

```

This says take the input `]` and its transpose `|:` and create a "multiplication table" of all the combinations, except instead of multiplication we'll apply the verb in parenthesis. The rank `"1` specifier ensures that we take all combinations of rows from both arguments, but since the rows of the transpose are the columns of the original matrix, this means we'll be taking all combinations of rows and columns. That is, we'll be doing:

```
  Rows                            Cols
┌─────────┐                     ┌──────┐
│1 0 3    │                     │1 10.1│
├─────────┤  "times" table      ├──────┤
│10.1 _2 3│                     │0 _2  │
└─────────┘                     ├──────┤
                                │3 3   │
                                └──────┘

which produces:

┌───────────────────────┬─────────────────────┬────────────────────┐
│┌─────┬────┬──────┐    │┌─────┬────┬────┐    │┌─────┬────┬───┐    │
││1 0 3│verb│1 10.1│    ││1 0 3│verb│0 _2│    ││1 0 3│verb│3 3│    │
│└─────┴────┴──────┘    │└─────┴────┴────┘    │└─────┴────┴───┘    │
├───────────────────────┼─────────────────────┼────────────────────┤
│┌─────────┬────┬──────┐│┌─────────┬────┬────┐│┌─────────┬────┬───┐│
││10.1 _2 3│verb│1 10.1│││10.1 _2 3│verb│0 _2│││10.1 _2 3│verb│3 3││
│└─────────┴────┴──────┘│└─────────┴────┴────┘│└─────────┴────┴───┘│
└───────────────────────┴─────────────────────┴────────────────────┘

```

Now the `verb` we apply to each of these combos is `+:&(1=#@~.)` and this verb returns false if "either argument consists of a single repeated item" and true otherwise. It does this by taking the nub, or uniq `~.`, asking if its length is one `1=#`, and taking the nor of the result `+:`.

That is, this will return a boolean mask with the same shape as the input matrix, but with zeros for any item in a row or column of all equal items.

```
1 1 0
1 1 0

```

Now we simply mutliply the original matrix by this mask and take the floor `]<.@*`:

```
1   0 0
10 _2 0

```

and then flatten and sum the result of that: `+/@,`

```
9

```
> 2 votes

# Answer
# PHP, ~~145~~ 109 bytes

After using the default `A23456789TJQK` coding for inputs and not getting a good result, I switched to using this coding similar to other answers:

```
A |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |  T |    J |    Q | K
1 | -2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 10.1 | 10.2 | 0

```

Input is a two dimensional array in this format: `[[1,0,3],[10.1,-2,3]]`. Basically checks the row (using `min` and `max`) and the column for each card to not contain equal values and then adds card value to the total score and at the end prints integer portion of the total score.

```
function($a){for(;$x++<2;)for($i=3;$i--;)min($r=$a[$x-1])-max($r)&&$r[$i]-$a[$x%2][$i]&&$s+=$r[$i];echo$s^0;}

```

Try it online! *(Note: TIO for PHP is broken at the moment, because of a wrong version upgrade, but should come back OK)*
> 0 votes

# Answer
# Japt, 22 bytes

```
c xÈf *YgUïUÕ me_â Ê>1

```

Try it
> 0 votes

# Answer
# Python 3, 79 bytes

```
lambda d:sum([({*a}!={x}!={y})*int(x)for a,b in(d,d[::-1])for x,y in zip(a,b)])

```

Try it online!

Uses the same input format as some other answers, values \\$1,-2,3,4,5,6,7,8,9,10,10.1,10.2,0\\$ for the cards.

---

# Python 3, 118 bytes

More readable input format

```
lambda d:sum([({*a}!={x}!={y})*[10,10,10,1,0,-2,int(x,36)]['TJQAK2'.find(x)]for a,b in(d,d[::-1])for x,y in zip(a,b)])

```

Try it online!
> 0 votes

# Answer
# Kotlin, 159 bytes

Lambda takes 1.3456789TJQ0 as input. The outer code takes A23456789TJQK as input, converts the ace, two, and king so the math works out, and displays the cards & score.

```
{d:List<String>->Int
var s=0
for(r in 0..1)for(c in 0..2)if((d[r][0]!=d[r][1]||d[r][1]!=d[r][2])&&d[0][c]!=d[1][c]){
val n=d[r][c]-'0'
s+=if(n>9)
10
else
n}
s}

```

Try it online!
> 0 votes

---
Tags: code-golf, card-games
---


title: Reorder a matrix, twice

text:
# Question
Title: Reorder a matrix, twice
You are given a square \\$n \times n\\$ matrix \\$A\\$, and a list (or vector) \\$u\\$ of length \\$n\\$ containing the numbers \\$1\\$ through \\$n\\$ (or \\$0\\$ through \\$n-1\\$). Your task is to reorder the columns **and** rows of the matrix \\$A\\$ according to the order specified in \\$u\\$.

That is, you will construct a matrix \\$B\\$ where the \\$(i,j)\\$-th element is the \\$(u(i),u(j))\\$-th element of \\$A\\$. You should also output the inverse of this action; that is, the (i,j)-th element of \\$A\\$ will end up at position \\$(u(i),u(j))\\$ in a new matrix \\$C\\$.

For example, given $$A = \begin{bmatrix} 11 &12& 13 \\ 21& 22& 23 \\ 31& 32& 33 \end{bmatrix},\quad u=\begin{bmatrix}3 & 1 & 2\end{bmatrix}$$

the output should be $$B = \begin{bmatrix}33 & 31 & 32 \\ 13 & 11 & 12 \\ 23 & 21 & 22 \end{bmatrix},\quad C= \begin{bmatrix}22 & 23 & 21 \\32 & 33 & 31 \\ 12 & 13 & 11 \end{bmatrix}$$

You may take input and output through any of the default I/O methods. You do not have to specify which matrix is \\$B\\$ or \\$C\\$, as long as you output both. You may assume \\$A\\$ only contains positive integers, and you may use 1- or 0-based indexing for \\$u\\$. You must support matrices up to at least size \\$64 \times 64\\$.

## Example

```
===== Input =====
A =
 35     1     6    26    19    24
  3    32     7    21    23    25
 31     9     2    22    27    20
  8    28    33    17    10    15
 30     5    34    12    14    16
  4    36    29    13    18    11
u=
  3 5 6 1 4 2

==== Output =====
B =
  2    27    20    31    22     9
 34    14    16    30    12     5
 29    18    11     4    13    36
  6    19    24    35    26     1
 33    10    15     8    17    28
  7    23    25     3    21    32
C =
 17    15     8    10    28    33
 13    11     4    18    36    29
 26    24    35    19     1     6
 12    16    30    14     5    34
 21    25     3    23    32     7
 22    20    31    27     9     2

```

# Answer
> 6 votes
# MATL, ~~15~~ 13 bytes

```
t3$)&Gw&St3$)

```

Inputs `u`, then `A`.

Outputs `B`, then `C` without a separator, as there is no ambiguity.

Try it online!

### Explanation

```
t     % Take input u implicitly. Duplicate u
3$)   % Take input A implicitly. Index A with u as row and column indices
&G    % Push the two inputs again: u, A
w     % Swap
&S    % Push indices that would make u sorted. Call that v
t     % Duplicate v
3$)   % Index A with v as row as column indices. Display implcitly

```

# Answer
> 6 votes
# , 42 bytes

```
function(A,o)list(A[o,o],A[I<-order(o),I])

```

Try it online!

Takes `A` as a `matrix` and 1-based indexes `o`.

# Answer
> 5 votes
# Octave, 33 bytes

```
@(A,u){A(u,u) A([~,v]=sort(u),v)}

```

Try it online!

Thanks to Luis for correcting an error and saving several bytes!

Basic indexing works here for both tasks, by defining a vector \\$ v \\$ equal to the permutation that undoes \\$ u \\$. That is, if \\$ u = ( 3, 1, 2 ) \\$ then the first element of \\$ v \\$ is 2, since 1 is in the second position of \\$ u \\$. This is accomplished with Octave's sort function.

# Answer
> 5 votes
# Python 3 with numpy, ~~51~~ 45 bytes

```
lambda m,p:[m[x][:,x]for x in(p,p.argsort())]

```

Try it online!

*-6 bytes thanks to @xnor*

The function takes two arguments: a `numpy` matrix and a permutation vector having values from \\$0\\$ to \\$n-1\\$.

# Answer
> 4 votes
# Wolfram Language (Mathematica), 30 bytes

```
ii[[#,#]]&/@{#,Ordering@#}&

```

Try it online!

Input as `f[A][u]`.

# Answer
> 4 votes
# PowerShell, ~~78~~ ~~73~~ 71 bytes

```
($A,$u=$args)|%{$A[$u]|%{''+$_[$u]}
$u=1..$u.count|%{$u.indexof($_-1)}}

```

Try it online.

# Answer
> 3 votes
# Jelly, 13 bytes

```
ŒJṁ⁸ịⱮ⁹,Ụ¤œị⁸

```

Try it online!

# Answer
> 3 votes
# , 19 bytes

```
(]/:~"1/:)"_ 1],:/:

```

Try it online!

* Main verb `]/:~"1/:`
    + The right most `/:` sorts the left arg (matrix) according to the order that would sort the right arg (specified order). This sorts rows.
    + Now that result get sorted `/:~"1` again according to the order specified `]`. But this time we're sorting with rank 1, ie, we're sorting each row, which has the effect of sorting columns.
* `],:/:` We apply the above using both the order specified `]` and the *grade up* of the order specified `/:`. This gives us the 2 results we want.

# Answer
> 3 votes
# , ~~17 16 15~~ 14 bytes

-1 thanks to @Jonah

```
([{"1{)~(,:/:)

```

Try it online!

# Answer
> 3 votes
# JavaScript (Node.js), ~~77~~ ~~70~~ 68 bytes

```
a=>g=(u,v=[])=>[u.map((i,x)=>u.map(j=>a[i][j],v[i]=x)),v&&g(v,0)[0]]

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog Extended), 12 bytesSBCS

Full program. Prompts for \\$u\\$ and then \\$A\\$. Prints \\$C\\$ next to \\$B\\$, separated by two spaces

```
⌷∘⎕¨⍋¨⍛⍮⍨⍮⍨⎕

```

Try it online!

prompt for \\$u\\$; `[3,1,2]`

`⍮⍨` juxtaposition-selfie; `[[3,1,2],[3,1,2]]`

`⍋¨` permutation-inversion of each; `[[2,3,1],[2,3,1]]`
then
`⍮⍨` juxtapose with itself `[[[2,3,1],[2,3,1]],[[3,1,2],[3,1,2]]]`

reorder
the value of
\\$A\\$ as inputted
`¨` using each pair as a set of orders, one order per axis

# Answer
> 2 votes
# Charcoal, 24 bytes

```
Ｅ⟦ηＥη⌕ηκ⟧Ｅθ⪫Ｅθ§§θ§ιμ§ιξ

```

Try it online! Link is to verbose version of code. 0-indexed. Note: Trailing space. Explanation:

```
    η                       Input `u`
   Ｅ                        Map over elements
     ⌕                      Index of
       κ                    Current index in
      η                     Input `u`
  η                         Input `u`
Ｅ⟦      ⟧                   Map over `u` and its inverse
          θ                 Input `A`
         Ｅ                  Map over elements
             θ              Input `A`
            Ｅ               Map over elements
                θ           Input `A`
               §            Indexed by
                  ι         Current vector
                 §          Indexed by
                   μ        Row index
              §             Indexed by
                     ι      Current vector
                    §       Indexed by
                      ξ     Column index
           ⪫                Join with spaces for readability
                            Implicitly print

```

# Answer
> 2 votes
# Kotlin, 213 bytes

```
{a:List<List<Int>>,u:List<Int>->val s=u.size
for(l in List(s){r->List(s){c->a[u[r]][u[c]]}})println(l.joinToString(" "))
for(l in List(s){r->List(s){c->a[u.indexOf(r)][u.indexOf(c)]}})println(l.joinToString(" "))}

```

Try it online!

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

Prompts for input of u followed by a. Outputs b immediately over the top of c with no separator:

```
(a←⎕)[u;u←⎕]⋄a[⍋u;⍋u]

```

Try it online! Courtesy of Dyalog Classic

# Answer
> 1 votes
# Perl 5, 79 bytes

```
sub{$[=1;($A,$u)=@_;@$v[@$u]=(1..@$u);map{$x=$_;[map[@$_[@$x]],@$A[@$x]]}$u,$v}

```

Try it online!

# Answer
> 1 votes
# Jelly,  ~~12 11~~  13 bytes

+2 :( to fix cases when B = C

```
ṭþ`œị¥@Ƭị@2,0

```

A dyadic Link accepting a list of lists, `A` (`n` by `n`), on the left and a list of the first `n` integers on the right, `u`, which yields a list of lists of lists, `[B, C]`.

**Try it online!**

### How?

```
ṭþ`œị¥@Ƭị@2,0 - Link: A, u
       Ƭ      - collect up while the results are no longer unique, applying:
     ¥@       -   last two links as a dyad with swapped arguments:
  `           -     use left (u) as both arguments of:
 þ            -       outer product with:
ṭ             -         tack
   œị         -     multi-dimensional index into last result (starting with A)
                ...at the end of the Ƭ-loop we have [A,B,...,C]
                                                 or [A] if A=B=C
                                                 or [A,B] if B=C but A!=B
          2,0 - literal pair [2,0]
         @    - with swapped arguments:
        ị     -   index into (1-based & modular) -> [B,C]
                                                 or [A,A]=[B,C] if A=B=C
                                                 or [B,B]=[B,C] if B=C

```

# Answer
> 1 votes
# C++ (gcc), ~~148~~ 142 bytes

```
#import<queue>
#define q[o[i/z]*z+o[i%z]]
using V=std::vector<int>;int f(V m,V o,V&r,V&R,int z){int i=z*z;for(r=R=V(i);i--;r[i]=m q)R q=m[i];}

```

Try it online!

Thanks to @ceilingcat suggestion to use #import \<queue\> instead of \<vector\> which mysteriously brings std::vector

# Answer
> 1 votes
# q, 26 bytes

```
{Y:iasc y;(x[y;y];x[Y;Y])}

```

`iasc` returns indexes to sort it's argument.

# Answer
> 1 votes
# Clean, 91 bytes

```
import StdEnv
$a u=map(\l={{a.[i,j]\\j<-l}\\i<-l})[u,[k\\i<-[0..]&_<-u,j<-u&k<-[0..]|j==i]]

```

Try it online!

Defines `$ :: {{a}} [Int] -> [{{a}}]` (used with `a = Int`) taking an array of arrays and a list of zero-based indices, returning a list of arrays of arrays containing B and C.

# Answer
> 1 votes
# Python 3, 91 bytes

```
lambda a,u:[[[a[y][x]for x in t]for y in t]for t in[u,[u.index(i)for i in range(len(u))]]]

```

Try it online!

Takes parameters as a 2D and 1D list and returns a list containing two 2D lists B and C. I'm not sure if there's a cleaner way to do all the for-loops.

---
Tags: code-golf, matrix, linear-algebra
---