title: Tips for golfing in Sesos

text:
# Question
Title: Tips for golfing in Sesos
If you have any tips regarding golfing in Sesos, a language made by Dennis, and nobody else has covered them yet, please post them here! Only one tip is allowed per answer. Your tip should be at least somewhat specific to Sesos itself, and not just brainfuck. If your tip is relevant to brainfuck in general, you should post it here instead.

# Answer
> 3 votes
# What's different in Sesos?

Golfing in Sesos is similar to golfing in brainfuck in that it has limited control flow, and that you have to grapple with the specifics of memory layout.

However, this does *not* mean you should write brainfuck code first and then translate it instruction-by-instruction to Sesos!

Here are some things that are different:

* You barely pay for repeated commands. For example, `add 1` is a 1-byte Sesos program. `add 100` is a 3-byte Sesos program. `add 1000` is *still* a 3-byte Sesos program. This means that things that would have been prohibitively expensive in brainfuck (e.g. `++++++++++`) are fine in Sesos.
* Unless you have `set mask` on, cells are not 8-bit unsigned integers—they are signed bignums. This means that you can do things like store an offset into an array as a cell without having to worry about the possibility of the array being more than 256 elements and causing overflow.
* Control flow is a bit more flexible: you have do-while loops that are guaranteed to execute at least once (with the use of `nop`). You also have `jne`, which is the equivalent of `,]` in a single instruction.

# Answer
> 1 votes
# Omit what you can

In Sesos, you can omit some instructions, specifically:

* You can omit a `jmp` instruction at the start of the program, if its corresponding exit point is not omitted.
* You can omit a `jnz` instruction at the end of the program, if its corresponding entry point is not omitted.

This example program prints numbers from `10` to `1`:

```
set numout
add 10
jmp
    sub 1
    put
jnz

```

However, we can reduce the SBIN file's size by a triad, therefore potentially reducing it by 1 byte, by removing the `jnz`:

```
set numout
add 10
jmp
    sub 1
    put

```

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


title: Sheffle tho vawols ureund!

text:
# Question
Title: Sheffle tho vawols ureund!
Given an input string, output that string with all vowels `a`, `e`, `i`, `o` and `u` swapped at random between each other.

For example, in the string `this is a test`, there are 4 vowels: `[i, i, a, e]`. A valid shuffling of those vowels could be `[a, i, e, i]` therefore yielding the output `thas is e tist`.

### About shuffling

All shuffles shall be equally likely **if we consider equal vowels to be distinct**. For the example above, those 24 shuffles are possible:

```
[i<sub>1</sub>, i<sub>2</sub>, a, e]    [i<sub>1</sub>, i<sub>2</sub>, e, a]    [i<sub>1</sub>, a, i<sub>2</sub>, e]    [i<sub>1</sub>, a, e, i<sub>2</sub>]
[i<sub>1</sub>, e, i<sub>2</sub>, a]    [i<sub>1</sub>, e, a, i<sub>2</sub>]    [i<sub>2</sub>, i<sub>1</sub>, a, e]    [i<sub>2</sub>, i<sub>1</sub>, e, a]
[i<sub>2</sub>, a, i<sub>1</sub>, e]    [i<sub>2</sub>, a, e, i<sub>1</sub>]    [i<sub>2</sub>, e, i<sub>1</sub>, a]    [i<sub>2</sub>, e, a, i<sub>1</sub>]
[a, i<sub>1</sub>, i<sub>2</sub>, e]    [a, i<sub>1</sub>, e, i<sub>2</sub>]    [a, i<sub>2</sub>, i<sub>1</sub>, e]    [a, i<sub>2</sub>, e, i<sub>1</sub>]
[a, e, i<sub>1</sub>, i<sub>2</sub>]    [a, e, i<sub>2</sub>, i<sub>1</sub>]    [e, i<sub>1</sub>, i<sub>2</sub>, a]    [e, i<sub>1</sub>, a, i<sub>2</sub>]
[e, i<sub>2</sub>, i<sub>1</sub>, a]    [e, i<sub>2</sub>, a, i<sub>1</sub>]    [e, a, i<sub>1</sub>, i<sub>2</sub>]    [e, a, i<sub>2</sub>, i<sub>1</sub>]

```

Each one should be equally as likely.

You may not try random shuffles of the entire string until finding one where all vowels are in the right place. In short, your code's running time shall be constant if the input is constant.

### Inputs and outputs

* You may assume that all letters in the input will be lowercase or uppercase. You may also support mixed casing, though this won't give you any bonus.
* The input will always consist of printable ASCII characters. All characters that are in the input shall be in the output, only the vowels must be shuffled around and nothing else.
* The input can be empty. There is no guarantee that the input will contain at least one vowel or at least one non-vowel.
* You may take the input from `STDIN`, as a function parameter, or anything similar.
* You may print the output to `STDOUT`, return it from a function, or anything similar.

### Test cases

The first line is the given input. The second line is one of the possible outputs.

```
<empty string>
<empty string>

a
a

cwm
cwm

the quick brown fox jumps over the lazy dog.
tho qeuck brewn fax jumps ovir the lozy dog.

abcdefghijklmnopqrstuvwxyz
abcdefghujklmnipqrstovwxyz

programming puzzles & code golf
pregromming pezzlos & coda gulf

fatalize
fitaleza

martin ender
mirten ander

```

### Scoring

This is , *sa tho shirtist enswer en bytes wons*.

# Answer
# Jelly, 15 bytes

```
f€“¡ẎṢɱ»ðœpżFẊ¥

```

Try it online!

### How it works

```
f€“¡ẎṢɱ»ðœpżFẊ¥  Main link. Argument: s (string)

  “¡ẎṢɱ»         Yield "aeuoi"; concatenate "a" with the dictionary word "euoi".
f€               Filter each character in s by presence in "aeuoi".
                 This yields A, an array of singleton and empty strings.
        ð        Begin a new, dyadic chain. Left argument: A. Right argument: s
         œp      Partition s at truthy values (singleton strings of vowels) in A.
            FẊ¥  Flatten and shuffle A. This yields a permutation of the vowels.
           ż     Zip the partition of consonants with the shuffled vowels.

```
> 13 votes

# Answer
## R, 92 91

Can't comment yet so I'm adding my own answer albeit very similar to @Andreï Kostyrka answer (believe it or not but came up with it independently).

```
s=strsplit(readline(),"")[[1]];v=s%in%c("a","e","i","o","u");s[v]=sample(s[v]);cat(s,sep="")

```

### Ungolfed

```
s=strsplit(readline(),"")[[1]]    # Read input and store as a vector
v=s%in%c("a","e","i","o","u")     # Return TRUE/FALSE vector if vowel
s[v]=sample(s[v])                 # Replace vector if TRUE with a random permutation of vowels
cat(s,sep="")                     # Print concatenated vector

```

---

Saved one byte thanks to @Vlo

```
s=strsplit(readline(),"")[[1]];s[v]=sample(s[v<-s%in%c("a","e","i","o","u")]);cat(s,sep="")

```
> 17 votes

# Answer
# R, ~~99~~ ~~98~~ 89 bytes

```
x=el(strsplit(readline(),""))
z=grepl("[aeiou]",x)
x[z]=x[sample(which(z))]
cat(x,sep="")

```

Seems to be the first human-readable solution! Thanks to Giuseppe for saving 9 bytes!

Test cases:

```
tho qaeck bruwn fux jemps over tho lozy dig.
progremmang pozzlos & cide gulf

```

Seems that there is no way to make an internal variable assignment (inside, like, `cat`), and again some people are going to prove I am wrong...
> 11 votes

# Answer
## CJam, 23 bytes

```
lee_{"aeiou"&},_mrerWf=

```

Try it online!

### Explanation

```
l            e# Read input, e.g. "foobar".
ee           e# Enumerate, e.g. [[0 'f] [1 'o] [2 'o] [3 'b] [4 'a] [5 'r]].
_            e# Duplicate.
{"aeiou"&},  e# Keep those which have a non-empty intersection with this string
             e# of vowels, i.e. those where the enumerated character is a vowel.
             e# E.g. [[1 'o] [2 'o] [4 'a]].
_            e# Duplicate.
mr           e# Shuffle the copy. E.g. [[2 'o] [4 'a] [1 'o]].
er           e# Transliteration. Replaces elements from the sorted copy with
             e# the corresponding element in the shuffled copy in the original list.
             e# [[0 'f] [2 'o] [4 'a] [3 'b] [1 'o] [5 'r]].
Wf=          e# Get the last element of each pair, e.g. "foabor".

```
> 10 votes

# Answer
# 05AB1E, 17 bytes

```
žMÃ.r`¹vžMyå_iy}?

```

**Explanation**

```
žMÃ                # get all vowels from input
   .r`             # randomize them and place on stack
      ¹v           # for each in input
        žMyå_i }   # if it is not a vowel
              y    # push it on stack
                ?  # print top of stack

```

Try it online!
> 5 votes

# Answer
# Python 3, 109 bytes

Only supports lowercase vowels.

Thanks to @Alissa for saving an extra byte.

```
import re,random
def f(s):r='[aeiou]';a=re.findall(r,s);random.shuffle(a);return re.sub(r,lambda m:a.pop(),s)

```

**Ideone it!**
> 5 votes

# Answer
# TSQL, 275 bytes

**Golfed:**

```
DECLARE @ VARCHAR(99)='the quick brown fox jumps over the lazy dog.'

;WITH c as(SELECT LEFT(@,0)x,0i UNION ALL SELECT LEFT(substring(@,i+1,1),1),i+1FROM c
WHERE i<LEN(@)),d as(SELECT *,rank()over(order by newid())a,row_number()over(order by 1/0)b
FROM c WHERE x IN('a','e','i','o','u'))SELECT @=STUFF(@,d.i,1,e.x)FROM d,d e
WHERE d.a=e.b PRINT @

```

**Ungolfed:**

```
DECLARE @ VARCHAR(max)='the quick brown fox jumps over the lazy dog.'

;WITH c as
(
  SELECT LEFT(@,0)x,0i
  UNION ALL
  SELECT LEFT(substring(@,i+1,1),1),i+1
  FROM c
  WHERE i<LEN(@)
),d as
(
  SELECT
    *,
    rank()over(order by newid())a,
    row_number()over(order by 1/0)b
  FROM c
  WHERE x IN('a','e','i','o','u')
)
SELECT @=STUFF(@,d.i,1,e.x)FROM d,d e
WHERE d.a=e.b
-- next row will be necessary in order to handle texts longer than 99 bytes
-- not included in the golfed version, also using varchar(max) instead of varchar(99)
OPTION(MAXRECURSION 0)

PRINT @

```

**Fiddle**
> 4 votes

# Answer
# Java 7, ~~243~~ 241 bytes

```
import java.util.*;String c(char[]z){List l=new ArrayList();char i,c;for(i=0;i<z.length;i++)if("aeiou".indexOf(c=z[i])>=0){l.add(c);z[i]=0;}Collections.shuffle(l);String r="";for(i=0;i<z.length;i++)r+=z[i]<1?(char)l.remove(0):z[i];return r;}

```

Yes, this can probably be golfed quite a bit, but Java doesn't have any handy built-ins for this a.f.a.i.k... Also, I kinda forgot the codegolfed array-variant for `Collections.shuffle`..

**Ungolfed & test cases:**

Try it here.

```
import java.util.*;
class M{
  static String c(char[] z){
    List l = new ArrayList();
    char i,
         c;
    for(i = 0; i < z.length; i++){
      if("aeiou".indexOf(c = z[i]) >= 0){
        l.add(c);
        z[i] = 0;
      }
    }
    Collections.shuffle(l);
    String r = "";
    for(i = 0; i < z.length; i++){
      r += z[i] < 1
               ? (char)l.remove(0)
               : z[i];
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c("".toCharArray()));
    System.out.println(c("a".toCharArray()));
    System.out.println(c("cwm".toCharArray()));
    System.out.println(c("the quick brown fox jumps over the lazy dog.".toCharArray()));
    System.out.println(c("abcdefghijklmnopqrstuvwxyz".toCharArray()));
    System.out.println(c("programming puzzles & code golf".toCharArray()));
    System.out.println(c("fatalize".toCharArray()));
    System.out.println(c("martin ender".toCharArray()));
  }
}

```

**Possible output:**

```
a
cwm
tha queck brown fox jumps evor tho lezy dig.
ebcdifghujklmnopqrstavwxyz
prigrommeng puzzlos & cade golf
fatelazi
mertan inder

```
> 3 votes

# Answer
# MATL, 15 bytes

```
tt11Y2m)tnZr7M(

```

Try it online!

### Explanation

```
tt      % Take input string implicitly. Duplicate twice
11Y2    % Predefined string: 'aeiou'
m       % Logical index that contains true for chars of the input that are vowels
)       % Get those chars from the input string. Gives a substring formed by the
        % vowels in their input order
tnZr    % Random permutation of that substring. This is done via random sampling
        % of that many elements without replacement
7M      % Push logical index of vowel positions again
(       % Assign the shuffled vowels into the input string. Display implicitly

```
> 3 votes

# Answer
## Javascript (ES6), ~~78~~ 76 bytes

```
s=>s.replace(r=/[aeiou]/g,_=>l.pop(),l=s.match(r).sort(_=>Math.random()-.5))

```

*Saved 2 bytes thanks to apsillers*

### Alternate version proposed by apsillers (76 bytes as well)

```
s=>s.replace(r=/[aeiou]/g,[].pop.bind(s.match(r).sort(_=>Math.random()-.5)))

```

### Test

```
let f =
s=>s.replace(r=/[aeiou]/g,_=>l.pop(),l=s.match(r).sort(_=>Math.random()-.5))

console.log(f("the quick brown fox jumps over the lazy dog."))
```
> 3 votes

# Answer
# Perl, 38 bytes

Includes +1 for `-p`

Run with the sentence on STDIN

```
vawols.pl <<< "programming puzzles & code golf"

```

`vawols.pl`:

```
#!/usr/bin/perl -p
@Q=/[aeiou]/g;s//splice@Q,rand@Q,1/eg

```
> 3 votes

# Answer
# Perl 6, 65 bytes

```
{my \v=m:g/<[aeiou]>/;my @a=.comb;@a[v».from]=v.pick(*);@a.join}

```

Anonymous function. Assumes lower-case input.

(try it online)
> 3 votes

# Answer
# Ruby 45 + 1 = 46 bytes

+1 byte for `-p` flag

```
a=$_.scan(e=/[aeiou]/).shuffle
gsub(e){a.pop}

```
> 3 votes

# Answer
# Bash, 75 bytes

```
paste -d '' <(tr aeoiu \\n<<<$1) <(grep -o \[aeiou]<<<$1|shuf)|paste -sd ''

```

Takes the string as an argument and prints the result to stdout.

Eg

```
for x in "" "a" "cwm" \
         "the quick brown fox jumps over the lazy dog." \
         "abcdefghijklmnopqrstuvwxyz" \
         "programming puzzles & code golf" \
         "fatalize" "martin ender"; do
  echo "$x";. sheffle.sh "$x"; echo
done

```

prints

```
<blank line>
<blank line>

a
a

cwm
cwm

the quick brown fox jumps over the lazy dog.
tho quuck brown fix jamps ever the lozy dog.

abcdefghijklmnopqrstuvwxyz
ibcdefghajklmnopqrstuvwxyz

programming puzzles & code golf
progremmong pazzlus & cedo gilf

fatalize
fetilaza

martin ender
mertan endir

```
> 3 votes

# Answer
# Brachylog, 39 bytes

```
@eI:1aToS,I:2f@~:LcS,Tc
.'~e@V;
e.~e@V,

```

Try it online!

### Explanation

* Main predicate:

```
@eI        I is the list of chars of the input.
:1aT       T is I where all vowels are replaced with free variables.
oS,        S is T sorted (all free variables come first).
I:2f       Find all vowels in I.
@~         Shuffle them.
:LcS,      This shuffle concatenated with L (whatever it may be) results in S.
             This will unify the free variables in S with the shuffled vowels.
Tc         Output is the concatenation of elements of T.

```
* Predicate 1:

```
.          Input = Output…
'~e@V      …provided that it is not a vowel.
;          Otherwise Output is a free variable.

```
* Predicate 2:

```
e.         Output is an element of the input…
~e@V,      … and it is a vowel.

```
> 3 votes

# Answer
# Japt v2.0a0, ~~14~~ 13 bytes

```
ō²f\v
NÌr\v@o

```

Try it

---

## Explanation

```
           :Implicit input of string U.
ö²         :Generate a random permutation of U.
  f\v      :Get all the vowels as an array.
\n         :Assign that array to U.
NÌ         :Get the last element in the array of inputs (i.e., the original value of U)
  r\v      :Replace each vowel.
     @o    :Pop the last element from the array assigned to U above.

```
> 3 votes

# Answer
# PHP, ~~144~~ 129 bytes

Using lowercase input

```
$r=Aaeiou;$v=str_shuffle(preg_replace("#[^$r]+#",'',$a=$argv[1]));for(;$i<strlen($a);)echo strpos($r,$a[$i++])?$v[$j++]:$a[$i-1];

```

Explanation:

```
$r="aeiou"; // set vowels

preg_replace("#[^$r]+#",'',$argv[1]) // find all vowels in input

$v=str_shuffle() // shuffle them

for(;$i<strlen($a);) // run through the text

strpos($r,$a[$i++])?$v[$j++]:$a[$i-1]; // if it's a vowel print the j-th shuffled vowel else print original text

```
> 2 votes

# Answer
## PowerShell v3+, ~~155~~ 99 bytes

```
param([char[]]$n)$a=$n|?{$_-match'[aeiou]'}|sort{random};-join($n|%{if($_-in$a){$a[$i++]}else{$_}})

```

*Big props to @Ben Owen for the 56-byte golf*

Takes input `$n`, expecting all lowercase, immediately casts it as a `char`-array.

We pipe that into a `Where-Object` clause to pull out those elements that `-match` a vowel, pipe them to `Sort-Object` with `{Get-Random}` as the sorting mechanism. Calling `Get-Random` without qualifiers will return an integer between `0` and `[int32]::MaxValue` -- i.e., assigning random weights to each element on the fly. We store the randomized vowels into `$a`.

Finally, we loop through `$n`. For each element, `|%{...}`, if the current character is somewhere `-in` `$a`, we output the next element in `$a`, post-incrementing `$i` for the next time. Otherwise, we output the current character. That's all encapsulated in parens and `-join`ed together into a string. That string is left on the pipeline, and output is implicit at program conclusion.

### Test cases

```
PS C:\Tools\Scripts\golfing> 'a','cwm','the quick brown fox jumps over the lazy dog.','abcdefghijklmnopqrstuvwxyz','programming puzzles & code golf','fatalize','martin ender'|%{.\vawols.ps1 $_}
a
cwm
thu qaeck brown fix jomps ovor thu lezy deg.
abcdofghejklmnupqrstivwxyz
prugrammong pizzles & code golf
fitaleza
mertin endar

```
> 2 votes

# Answer
# Pyth, 26 bytes

```
J"[aeiou]"s.i:QJ3.Sf}TPtJQ

```

A program that takes input of a quoted string and prints the shuffled string.

Try it online

**How it works**

```
J"[aeiou]"s.i:QJ3.Sf}TPtJQ  Program. Input: Q
J"[aeiou]"                  J="[aeiou]"
             :QJ3           Split Q on matches of regex J, removing vowels
                      PtJ   J[1:-1], yielding "aeiou"
                   f}T   Q  Filter Q on presence in above, yielding vowels
                 .S         Randomly shuffle vowels
           .i               Interleave non-vowel and vowel parts
          s                 Concatenate and implicitly print

```
> 2 votes

# Answer
## Actually, 24 bytes

```
;"aeiou";╗@s@`╜íu`░╚@♀+Σ

```

Try it online!

Explanation:

```
;"aeiou";╗@s@`╜íu`░╚@♀+Σ
;                         dupe input
 "aeiou";╗                push vowels, store a copy in reg0
          @s              split one copy of input on vowels
            @`╜íu`░       take characters from other copy of input where
              ╜íu           the character is a vowel (1-based index of character in vowel string is non-zero)
                   ╚      shuffle the vowels
                    @♀+   interleave and concatenate pairs of strings
                       Σ  concatenate the strings

```
> 2 votes

# Answer
# Bash, 89

Assumes all input to be lowercase.

```
a=`tee z|grep -o [aeiou]`
[ -n "$a" ]&&tr `tr -d \ <<<$a` `shuf -e $a|tr -d '
'`<z||cat z

```
> 2 votes

# Answer
# Python 3, 106 bytes

Lowercase only.

```
import re,random
def f(s):s=re.split('([aeiou])',s);v=s[1::2];random.shuffle(v);s[1::2]=v;return''.join(s)

```
> 2 votes

# Answer
# PHP \>= 5.3, ~~139~~ 136 bytes (and no errors thrown)

```
array_map(function($a,$b){echo$a.$b;},preg_split("/[aeiou]/",$s=$argv[1]),str_split(str_shuffle(implode(preg_split("/[^aeiou]/",$s)))));

```
> 1 votes

# Answer
# K (oK), 29 bytes

**Solution:**

```
{x[a:&x in"aeiou"]:x@(-#a)?a}

```

Try it online!

**Examples:**

```
"pregrommeng pizzlas & codo gulf"
{x[a:&x in"aeiou"]:x@(-#a)?a}"programming puzzles & code golf"
"pregremmong puzzlos & coda gilf"
{x[a:&x in"aeiou"]:x@(-#a)?a}"programming puzzles & code golf"
"pregrommeng pazzlos & cidu golf"

```

**Explanation:**

Find locations of the vowels and replace with the vowels drawn in a random order.

```
{x[a:&x in"aeiou"]:x@(-#a)?a} / the solution
{                           } / anonymous function with input x
 x[              ]            / index into x at these indices
      x in"aeiou"             / is character a vowel
     &                        / indices where true
   a:                         / assign to add
                  :           / assign
                          ?a  / draw randomly from a
                     (   )    / do this together
                       #a     / count length of a
                      -       / negate (draws from list, no duplication)
                   x@         / apply these indices to input

```
> 1 votes

# Answer
# APL (Dyalog Unicode), 21 bytes

```
{⍵[?⍨≢⍵]}@{⍵∊'AEIOU'}

```

Try it online!

Assumes uppercase.
> 0 votes

# Answer
# Kotlin, ~~122~~ 118 bytes

```
x->val v=x.filter{"aeiuo".contains(it)}.toList().shuffled()
x.split(Regex("[aeiou]")).reduceIndexed{i,a,s->a+v[i-1]+s}

```

Try it online!
> 0 votes

---
Tags: code-golf, string, random, permutations
---


title: 'A' to Ä converter

text:
# Question
Title: 'A' to Ä converter
I'm currently scanning a bunch of handwritten documents and converting them to `.txt` files. Since I have a terrible handwriting the `.jpg`-\>`.txt` converter converts some of my umlauts to the *"normal"* letter encased by `'`

## Task

Write a program or a function that:

* Is given a string
    + you can choose any I/O codepage as long as
        - it supports the characters `AEIOUaeiouÄËÏÖÜäëïöü'`.
        - the Input and Output codepages are the same.
    + the input will (beside spaces) only contain printable characters from your codepage.
        - There will only be one solution, thus things like `'a'e'` won't appear
* Converts all characters in the following set `AEIOUaeiou` to `ÄËÏÖÜäëïöü`
    + If, and only if, they are surrounded by `'` characters:
        - ***Example***: `'a''e' -> äë`
    + If the ***from*** string is a single letter.
        - for example `'AE'` does not change at all, outputting as-is.
    + If the ***from*** character is not a character out of `AEIOUaeiou` that character won't change.

Note: The ***from character / from string*** is the one between `'`.

## Testcases

```
Input
Output
<empty line>

'A'sthetik
Ästhetik

Meinung ist wichtig!
Meinung ist wichtig!

Ich sagte: "Er sagte: 'Ich habe Hunger'"
Ich sagte: "Er sagte: 'Ich habe Hunger'"

Ich sagte: "Er sagte: ''A'sthetik'"
Ich sagte: "Er sagte: 'Ästhetik'"

Hämisch rieb er sich die H'a'nde
Hämisch rieb er sich die Hände

H'a''a'slich isn't a German word
Hääslich isn't a German word

since it's really called h'a'sslich
since it's really called hässlich

```

# Answer
> 11 votes
# JavaScript (ES6), ~~81~~ ~~70~~ 68 bytes

```
s=>s.replace(/'[aeiou]'/gi,c=>"ï   ÖÄöä ËÜëüÏ "[c.charCodeAt(1)%15])

```

---

## Try It

```
f=
s=>s.replace(/'[aeiou]'/gi,c=>"ï   ÖÄöä ËÜëüÏ "[c.charCodeAt(1)%15])
i.addEventListener("input",_=>o.innerText=f(i.value))
console.log(f("'A'sthetik")) // Ästhetik
console.log(f("Meinung ist wichtig!")) // Meinung ist wichtig!
console.log(f(`Ich sagte: "Er sagte: 'Ich habe Hunger'"`)) // Ich sagte: "Er sagte: 'Ich habe Hunger'"
console.log(f(`Ich sagte: "Er sagte: ''A'sthetik'"`)) // Ich sagte: "Er sagte: 'Ästhetik'"
console.log(f("Hämisch rieb er sich die H'a'nde")) // Hämisch rieb er sich die Hände
console.log(f("H'a''a'slich isn't a German word")) // Hääslich isn't a German word
console.log(f("since it's really called h'a'sslich")) // since it's really called hässlich
```

```
<input id=i><pre id=o>
```

---

## Explanation

* `s=>` Anonymous function taking the input string as an argument via parameter "s".
* `s.replace(x,y)` Returns the string with "x" replaced by "y".
* `/'[aeiou]'/gi` Case insensitive regular expression that matches all occurrences of a vowel enclosed by single quotes.
* `c=>` Passes each match of the regular expression to an anonymous function via parameter "c".
* `"ï ÖÄöä ËÜëüÏ "[n]` Returns the nth character (0 indexed) in the string "ï ÖÄöä ËÜëüÏ ", similar to `"ï ÖÄöä ËÜëüÏ ".charAt(n)`.
* `c.charCodeAt(1)%15` Gets the remainder of the character code of the second character in "c" (i.e. the vowel character) when divided by 15.

---

## Alternative, ~~40/52~~ 36/48 bytes (35/47 characters)

The following was my answer before combining diacritics were disallowed (Boo-urns!) - better viewed in this Fiddle

```
s=>s.replace(/'([aeiou])'/gi,"$1̈")

```

However, ETHproductions suggests that with the addition of `.normalize()` for an additional 12 bytes that this would be valid.

```
s=>s.replace(/'([aeiou])'/gi,"$1̈").normalize()

```

# Answer
> 8 votes
# Perl 5, 25 bytes

```
s/'(\w)'/chr 1+ord$1/age

```

24 bytes, plus 1 for `-pe` instead of `-e`

This makes use of the rule that "you can choose any I/O codepage as long as it supports the characters `AEIOUaeiouÄËÏÖÜäëïöü'`". It also makes use of the `/a` flag on regexes, which causes `\w` to refer to precisely the characters in `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789` no matter how they're encoded.

The chosen I/O codepage for my script is this:

```
 1  a
 2  ä
 3  e
 4  ë
 5  i
 6  ï
 7  o
 8  ö
 9  u
10  ü
11  A
12  Ä
13  E
14  Ë
15  I
16  Ï
17  O
18  Ö
19  U
20  Ü
21  '

```

(I can't test this script on the test cases in the question, as they include some really weird characters, like `t`.)

---

Thanks to Grimy for saving me three bytes. Earlier, I had `s/'([a-z])'/chr 1+ord$1/gie`, which made use of (the encoding and) the interesting fact that `[a-z]` is special-cased in Perl to match precisely `abcdefghijklmnopqrstuvwxyz` no matter the encoding. My earlier answer is, IMO, more interesting, but this one is shorter, so, what the heck, I'll take it.

# Answer
> 6 votes
# Vim, 33 bytes

```
:s/\c'\([aeiou]\)'/<C-v><C-k>\1:/g
ii<esc>D@"

```

Try it online! in the backwards compatible V interpreter.

# Answer
> 4 votes
# Japt, 29 bytes

```
r"'%v'"@"ï   ÖÄöä ËÜëüÏ "gXc1

```

Try it online!

### Explanation

```
r"'%v'"@"ï   ÖÄöä ËÜëüÏ "gXc1

r"'%v'"@                       // Replace each match X of /'<vowel>'/ in the input with
        "ï   ÖÄöä ËÜëüÏ "g     //   the character in this string at index
                          Xc1  //     X.charCodeAt(1).
                               //   Values larger than the length of the string wrap around,
                               //   so this is effectively equal to " ... "[n%15].
                               // Implicit: output result of last expression

```

# Answer
> 4 votes
# Javascript, 67 bytes

```
s=>s.replace(/'.'/g,c=>"äëïöüÄËÏÖÜ"['aeiouAEIOU'.indexOf(c[1])]||c)

```

Try it online!

Replace all characters between quotes with either the corresponding umlauted character, or the match itself if it's not in the group of characters that need changing.

# Answer
> 3 votes
# Jelly, 36 bytes

```
œṣ⁹Ṫ¤j
“.ạẏụ’D196;+\Ọż⁾''jÐ€Øc¤;@Wç/

```

**Try it online!**

This seems pretty complicated for Jelly!

### How?

Note: Since the characters are not on the code-page, but are within the range of a byte in Unicode I think they must be created from ordinals, so I have.

```
œṣ⁹Ṫ¤j - Link 1, Replace: char list S [...], list R [char T, char list F]
œṣ     - split S at sublists equal to:
    ¤  -   nilad followed by link(s) as a nilad:
  ⁹    -     link's right argument, R
   Ṫ   -     tail - yield char list F and modify R to become [T]
     j - join with R (now [T])
       - all in all split S at Rs and join back up with [T]s.

“.ạẏụ’D196;+\Ọż⁾''jÐ€Øc¤;@Wç/ - Main link: char list S
       196;                   - 196 concatenate with:
“.ạẏụ’                        -   base 250 literal 747687476
      D                       -   to decimal list [7,4,7,6,8,7,4,7,6]
           +\                 - cumulative reduce with addition: [196,203,207,214,220,228,235,239,246,252]
             Ọ                - cast to characters: ÄËÏÖÜäëïöü
                       ¤      - nilad followed by link(s) as a nilad:
               ⁾''            -   literal ["'", "'"]
                     Øc       -   vowel yield: AEIOUaeiou
                  jÐ€         -   join mapped:  ["'A'", "'E'", ...]
              ż               - zip together
                          W   - wrap S in a list
                        ;@    - concatenate (swap @rguments)
                           ç/ - reduce with last link (1) as a dyad
                              - implicit print

```

# Answer
> 3 votes
# , 24 bytes

```
Óã'¨[aeiou]©'/±:
éiD@"

```

Try it online!

Hexdump:

```
00000000: d3e3 27a8 5b61 6569 6f75 5da9 272f 160b  ..'.[aeiou].'/..
00000010: b13a 0ae9 6944 4022                      .:..iD@"

```

This is just a direct translation of my vim answer so that I can beat all of the golfing languages. :P

# Answer
> 2 votes
# Ruby, 62+1 = 63 bytes

Uses the `-p` flag for +1 byte.

```
gsub(/'([aeiou])'/i){$1.tr"AEIOUaeiou","ÄËÏÖÜäëïöü"}

```

Try it online!

# Answer
> 1 votes
# APL (Dyalog), 53 bytes

```
(v←'''[AEIOUaeiou]''')⎕R{'  ÄËÏÖÜäëïöü'[v⍳2⊃⍵.Match]}

```

Try it online!

Uses PCRE *R*eplace (saving the RegEx as *v*) to apply the following function to quoted vowels:

`{` anonymous function

`' ÄËÏÖÜäëïöü'[``]` index the string (note two spaces corresponding to `'[`) with:

`⍵.Match` the matched string

`2⊃` pick second letter (the vowel)

`v⍳` find index in *v*

`}`

# Answer
> 1 votes
# ///, 67 bytes

```
/~/'\///`/\/\/~/'A~Ä`E~Ë`I~Ï`O~Ö`U~Ü`a~ä`e~ë`i~ï`o~ö`u~ü/

```

Try it online!

This works by replacing non-dotted letters surrounded by single-quotes(`'A'`) with the same letter as a dotted, without the single quotes (`Ä`). A single replacement of this looks like this (before the golf): `/'A'/Ä/`.

The golf takes two common occurrences, `//` and `'/`, and uses them as replacements.

# Answer
> 1 votes
# SOGL, ~~43~~ 35 (UTF-8) bytes

```
L∫:ÆW ':h++;"äëïöü”:U+Wŗ

```

Explanation:

```
L∫                        repeat 10 times, pushing current iteration (0-based)
  :                       duplicate the iteration
   ÆW                     get the index (1-based) in "aeiouAEIOU"
      ':h++               quote it
           ;              put the copy (current iteration) ontop
            "äëïöü”       push "äëïöü"
                   :      duplicate it
                    U     uppercase it
                     +    join together, resulting in "äëïöüÄËÏÖÜ"
                      W   get the index (1-based) in it
                       ŗ  replace [in the input, current char from "aeiouAEIOU" with
                          the corresponding char in "äëïöüÄËÏÖÜ"

```

# Answer
> 1 votes
# Swift - 201 bytes

```
import Foundation;func g(s:String){var e=s;var r="aeiouAEIOUäëïöüÄËÏÖÜ".characters.map{String($0)};for i in r[0...9]{e=e.replacingOccurrences(of:"'\(i)'",with:r[r.index(of:i)!+10])};print(e)}

```

Usage: `g("'A'sthetik") // => Ästhetik`

# Answer
> 1 votes
# AWK, 99 bytes

```
{split("AEIOUaeiou",p,"")
for(i=1;i<=split("ÄËÏÖÜäëïöü",r,"");i++)gsub("'"p[i]"'",r[i])}1

```

Try it online!

I tried to come up with some clever regex within a `gensub` but failed :(

# Answer
> 1 votes
# Python 3.6, ~~98~~ 92 characters

```
import re;a=lambda i,p="'([AEIOUaeiou])'":re.sub(p,lambda x:'ÄËÏÖÜäëïöü'[p.index(x[1])-3],i)

```

It's a function, not a complete program.

Formatted for readability:

```
import re

a = lambda i, p="'([AEIOUaeiou])'":\
    re.sub(p, lambda x: 'ÄËÏÖÜäëïöü'[p.index(x[1]) - 3], i)

```

Thanks to @ValueInk for clever tips for further golfing.

# Answer
> 1 votes
# 05AB1E, ~~30~~ ~~29~~ 24 bytes

-6 bytes thanks to Emigna

```
žMDu«S''«''ì"äëïöü"Du«S:

```

05AB1E conveniently has the characters `äëïöü` in its code page.

Try it online!

(old code)

```
žMDu«Svy''.ø})"äëïöü"Du«¹ŠS:

```

Explanation (outdated):

```
žM                             Push aeiou                    ['aeiou']
  D                            Duplicate                     ['aeiou', 'aeiou']
   u                           Uppercase                     ['aeiou', 'AEIOU']
    «                          Concatenate                   ['aeiouAEIOU']
     vy                        For each...
       ''                        Push '
         .ø                      Surround a with b (a -> bab)
           }                   End loop
            )                  Wrap stack to array           [["'a'", "'e'", "'i'", "'o'", "'u'", "'A'", "'E'", "'I'", "'O'", "'U'"]]
             "äëïöü"           String literal.               [["'a'", "'e'", "'i'", "'o'", "'u'", "'A'", "'E'", "'I'", "'O'", "'U'"], 'äëïöü']
                    Du«        Duplicate, uppercase, concat  [["'a'", "'e'", "'i'", "'o'", "'u'", "'A'", "'E'", "'I'", "'O'", "'U'"], 'äëïöüÄËÏÖÜ']
                       ¹       Push first input
                        Š      Push c, a, b                  ["'A'sthetik", ["'a'", "'e'", "'i'", "'o'", "'u'", "'A'", "'E'", "'I'", "'O'", "'U'"], 'äëïöüÄËÏÖÜ']
                          S    Convert to char list          ["'A'sthetik", ["'a'", "'e'", "'i'", "'o'", "'u'", "'A'", "'E'", "'I'", "'O'", "'U'"], ['ä', 'ë', 'ï', 'ö', 'ü', 'Ä', 'Ë', 'Ï', 'Ö', 'Ü']]
                           :   Replace all                   ['Ästhetik']
                               Implicit print

```

Try it online!

# Answer
> 0 votes
# Retina, 39 bytes

```
iT`A\EI\OUaei\ou'`ÄËÏÖÜäëïöü_`'[aeiou]'

```

Try it online!

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


title: Golf A Free Lunch

text:
# Question
Title: Golf A Free Lunch
Find a maximally profitable sequence of exchanges given an exchange rate table.

---

As an example consider the currencies **A**riary (your home currency), **B**aht, **C**edi, and **D**enar where the rate from one to another (after any transaction rate has been levied) is given by the (row, column) entry in the exchange rate table below:

```
                       TO
       A          B          C          D

   A   0.9999     1.719828   4.509549   0.709929

F  B   0.579942   0.9999     2.619738   0.409959
R
O  C   0.219978   0.379962   0.9999     0.149985
M
   D   1.39986    2.429757   6.409359   0.9999

```

Obviously exchanging **A** for **A** is not a great idea as this desk will happily charge you for doing nothing.

Less obviously, but true with this table, exchanging **A** for any other currency and then exchanging back again is a loss maker:

```
via B: 1.719828 × 0.579942 = 0.997400489976
via C: 4.509549 × 0.219978 = 0.992001569922
via D: 0.709929 × 1.39986  = 0.99380120994

```

However, exchanging **A** to **D** then **D** to **B** then **B** back to **A** *does* profit (given enough capital not to succumb to rounding):

```
0.709929 × 2.429757 × 0.579942 = 1.0003738278192194

```

One could repeatedly take this "free lunch" while the opportunity exists.

But an even more enticing chain exists here, namely **A** to **D** then **D** to **C** then **C** to **B** and finally **B** back to **A**:

```
0.709929 × 6.409359 × 0.379962 × 0.579942 = 1.0026612752037345

```

---

### Challenge Details

Given an exchange rate table in any reasonable format which fixes the meaning of the home-currency (e.g. 1st row and 1st column are always the home-currency)
(or given such a table and a home-currency index)
find a\* maximal arbitrage sequence of exchanges **starting and ending with the home currency** as indexes into the currency list **without repeating the use of any exchange** (i.e. a Y-\>X exchange may follow an X-\>Y one, but an X-\>Y may not follow an X-\>Y).

If no such profitable opportunity exists yield an empty list, or some other result not confusable with an identified opportunity.
\- e.g. for the above example (**A-\>D,D-\>C,C-\>B,B-\>A**):

* using 0-indexing one might return `[[0,3],[3,2],[2,1],[1,0]]` or `[0,3,2,1,0]`
* using 1-indexing one might return `[[1,4],[4,3],[3,2],[2,1]]` or `[1,4,3,2,1]`

Other formats are fine so long as there is no ambiguity.
\- One thing to watch out for is that it is possible for the best opportunity to be a single transaction from home-\>home (a foolish desk). If you decide to go with excluding the home currency index from both ends of the flat option above (i.e. `[3,2,1]` or `[4,3,2]`) and an empty list for "no opportunity" then make sure the home-\>home is not also an empty list.

* If multiple equally profitable valid opportunities happen to exist, return any of them, some of them, or all of them.

The Bellman-Ford algorithm is one way to approach this, but probably not the best suited for golf.

### Test Cases

Inputs shown are in the arrangement used in the example, and the results shown use 0-indexing to list the to-currency-indices (when an opportunity exists the home currency is at the trailing end only; no opportunity is an empty list).

```
[[0.999900, 1.719828, 4.509549, 0.709929],
 [0.579942, 0.999900, 2.619738, 0.409959],
 [0.219978, 0.379962, 0.999900, 0.149985],
 [1.399860, 2.429757, 6.409359, 0.999900]]  ->  [3, 2, 1, 0]

[[0.9999, 1.5645, 0.9048, 1.0929],
 [0.6382, 0.9999, 0.5790, 0.6998],
 [1.1051, 1.7269, 0.9999, 1.2087],
 [0.9131, 1.4288, 0.8262, 0.9999]]  ->  [1, 2, 0]

[[0.9999, 1.4288, 0.8262, 0.9131],
 [0.6998, 0.9999, 0.5790, 0.6382],
 [1.2087, 1.7269, 0.9999, 1.1051],
 [1.0929, 1.5645, 0.9048, 0.9999]]  ->  [1, 2, 3, 1, 0]

[[1.002662, 1.719828, 4.509549, 0.709929],
 [0.579942, 0.999900, 2.619738, 0.409959],
 [0.219978, 0.379962, 0.999900, 0.149985],
 [1.399860, 2.429757, 6.409359, 0.999900]]  ->  [3, 2, 1, 0, 0]

[[1.002662, 1.719828, 4.509549, 0.709929],
 [0.579942, 1.002604, 2.619738, 0.409959],
 [0.219978, 0.379962, 1.003000, 0.149985],
 [1.399860, 2.429757, 6.409359, 1.002244]]  ->  [3, 3, 2, 2, 1, 1, 0, 0]

[[0.9999, 1.4288, 0.8262, 0.9131],
 [0.6998, 0.9999, 0.5790, 0.6382],
 [1.2087, 1.7269, 1.0001, 1.1051],
 [1.0929, 1.4974, 0.9048, 0.9999]]  ->  [1, 2, 2, 0]

[[0.9999, 1.3262, 0.7262, 0.9131],
 [0.6998, 0.9999, 0.5490, 0.6382],
 [1.2087, 1.7269, 0.9999, 1.2051],
 [1.0929, 1.5645, 0.9048, 0.9999]]  ->  [3, 2, 3, 1, 0]

[[0.9999, 1.5645, 0.9048, 0.5790],
 [0.6382, 0.9999, 0.5790, 0.3585],
 [1.1051, 1.7269, 0.9999, 0.6391],
 [1.7271, 2.6992, 1.5645, 0.9999]]  ->  [1, 2, 0]  and/or  [3, 2, 0]

[[0.9999, 1.2645, 0.7048, 0.3790],
 [0.4382, 0.9999, 0.3790, 0.1585],
 [1.0001, 1.5269, 1.0001, 0.4391],
 [1.5271, 2.4992, 1.3645, 0.9999]]  ->  []

[[0.9999, 1.2645, 0.7048, 0.3790],
 [0.4382, 0.9999, 0.3790, 0.1585],
 [0.9999, 1.5269, 1.4190, 0.4391],
 [1.5271, 2.4992, 1.3645, 0.9999]]  ->  [2, 2, 0]

```

---

This is so the shortest solution in bytes wins, but competition should be made intra-language too, so don't let code-golfing languages put you off submitting in your favourite one!

# Answer
# JavaScript (ES6), ~~122~~ ~~113~~ 103 bytes

Takes input as a transposed matrix with respect to the format described in the challenge. Returns a string describing the exchanges in `(from,to)` format.

```
a=>(g=(s,x=b=0,h='')=>a.map((r,y)=>~h.search(k=`(${x},${y})`)||g(s*r[x],y,h+k),x|s<b||(b=s,p=h)))(1)&&p

```

First test case: Try it online!

More test cases: Try it online!

### Commented

```
a => (                  // given the exchange rate matrix a[][]
  g = (                 // g = recursive function taking:
    s,                  //   s = current amount of money
    x = b = 0,          //   x = ID of current currency, b = best result so far
    h = ''              //   h = exchange history, as a string
  ) =>                  //
  a.map((r, y) =>       // for each row at position y in a[]:
    ~h.search(          //   if we can't find in h ...
      k = `(${x},${y})` //     ... the exchange key k from currency x to currency y
    ) ||                //   then:
    g(                  //   do a recursive call to g() with:
      s * r[x],         //     s = new amount obtained by applying the exchange rate
      y,                //     x = y
      h + k             //     h = h + k
    ),                  //   end of recursive call
    x | s < b ||        //   if x is our home currency and s is greater than or equal to b
    (b = s, p = h)      //   then set b to s and set p to h
  )                     // end of map()
)(1)                    // initial call to g() with s = 1
&& p                    // return p

```
> 8 votes

# Answer
# Python 2, ~~143~~ ~~125~~ 124 bytes

```
lambda M:g(M)[1]
g=lambda M,s=[],p=1,x=0:max([(p,s)]*-~-x+[g(M,s+[(x,y)],p*M[x][y],y)for y in range(len(M))if(x,y)not in s])

```

Try it online!

Uses 0-based indexing (0 is the home currency); returns a list of tuples of the exchanges yielding the max payout.

The approach is brute force: via the recursion, we end up visiting every non-edge-repeating path starting at `0` (for `n` being the number of currencies, this gives a maximum *depth* of `n^2`). For the subset of these paths also ending with '0', we maximize the payoff.
> 5 votes

# Answer
# Haskell, 175 bytes

```
e?l|e`elem`l=0|2>1=1
w[]=[]
w l=[maximum l];0!q=[q]
n!c@(v,i,(h,l))=do{j<-[0..3];c:((n-1)!(v*l!!i!!j*(i,j)?h,j,((i,j):h,l)))}
z l=w$filter(\(v,e,_)->v>1&&e==0)$12!(1,0,([],l))

```

Try it here
> 2 votes

---
Tags: code-golf, number, arithmetic, matrix
---


title: Three-Dimensional Chess

text:
# Question
Title: Three-Dimensional Chess
In order to defend someone’s baffling decision, people often say that that person is going over everyone’s heads and playing “3-dimensional chess”. Now it’s your chance to play 3-dimensional chess!

## Rules

There are many variants of 3D Chess, but for this challenge I’ve made up my own. My version is just like regular chess except that the pieces are inside cubes instead of squares, and now have an additional dimension of movement. To make this challenge simple there are **no pawns** and **no castling**.

## Piece Movement

*(Compass directions refer to movement that would occur on a standard chessboard, Up and Down refer to moving vertically on the 3D chess board).*

* **King** \- has 26 squares it can go to on a given turn: N,NE,E,SE,S,SW,W,NW; as well as up, down, and up/down + one of the compass directions.
* **Queen** \- can move in the same directions as the King, but as far as she wants in those directions.
* **Rook** \- can move in 6 directions: N,E,S,W, Up, and Down,
* **Bishop** \- has 8 triagonal directions of travel: NE + Up/Down, SE + Up/Down, SW + Up/Down, NW + Up/Down
* **Knight** \- moves 2 spaces one axis, then 1 space on another. Just like regular chess, the knight is the only piece that can hop over other pieces.

## Piece Tester

Use this snippet to see how the different pieces move on the 3D board (***tip***: check out the `*Test` functions in the JS for quick ways to determine if a square is a valid move, simply based on its absolute distance from the piece.):

```
const color = "Black";
const pieces = ["N","B","R","Q","K"];
const urls = ["https://image.ibb.co/gyS9Cx/Black_N.png","https://image.ibb.co/dknnzc/Black_B.png","https://image.ibb.co/kb3hXx/Black_R.png","https://image.ibb.co/hGO5kH/Black_Q.png","https://image.ibb.co/jApd5H/Black_K.png"];
var dragPiece;
var size = 3;
var index = 0;
function start() {
Array.prototype.add = function(a) {return [this[0]+a[0],this[1]+a[1],this[2]+a[2]]};

document.getElementById("n").onchange=function() {
 size = parseInt(this.value);
 var s = document.getElementsByClassName("selected");
 var pos;
 if(s.length > 0) {
  pos = s[0].pos;
 }
 document.body.removeChild(document.body.firstChild);
 createBoards();
 if(pos != null && valid(...pos)) {
 cellAt(...pos).click();
 }
};
createBoards();
}

function createBoards() {
var boards = document.createElement("div");
boards.style.counterReset = "board-count "+(size+1);
boards.name=size;
for(var x = 0;x<size;x++) {
var t = document.createElement("table");
for(var i = 0;i<size;i++) {
  var row = document.createElement("tr");
  row.className="row";
  for(var j = 0;j<size;j++) {
   var cell = document.createElement("td");
    cell.className = (size+i+j)%2 == 1 ? "black" : "white";
    var im = document.createElement("img");
    im.draggable = true;
    im.ondragstart = function(e) {dragPiece = this;e.dataTransfer.setData("piece",this.parentElement.name);
    this.parentElement.classList.add("start");
    this.classList.add("dragged");
    };
    im.ondragend = function(e) {this.parentElement.classList.remove("start");this.classList.remove("dragged");};
    im.hidden = true;
    cell.appendChild(im);
    cell.pos = [j,i,x];
    cell.ondragover = function(e) {e.preventDefault();};
    cell.ondragenter = function(e) {this.classList.add("drag");};
    cell.ondragleave = function(e) {this.classList.remove("drag");};
    cell.ondrop = function(e) { e.preventDefault();this.classList.remove("drag");
    if(this != dragPiece.parentElement && this.firstChild.hidden ){
    dragPiece.hidden=true;
    setPiece(this,e.dataTransfer.getData("piece"));
    }

    };
    cell.onclick = function() {
    if(this.firstChild.hidden == false && this.classList.contains("selected")) {
  index++;
     if(index == pieces.length) index = 0;
    }
      setPiece(this,pieces[index]);
    };

    row.appendChild(cell);
  }
  t.appendChild(row);
  }
  boards.appendChild(t);
  }
  document.body.insertBefore(boards,document.body.firstChild);
}

function clearHighlighted() {
 var sel =  document.getElementsByClassName("highlighted");
     while(sel.length > 0) {
      sel[0].classList.remove("highlighted");
     }
}

function setPiece(cell,piece) {
var s=document.getElementsByClassName("selected");
if(s.length > 0){ s[0].firstChild.hidden=true;s[0].classList.remove("selected");}
cell.classList.add("selected");
cell.firstChild.hidden = false;
cell.name = piece;
      cell.firstChild.src = urls[index];
     clearHighlighted();
      showMoves(cell,piece);
}

function showMoves(cell,piece) {
 if(piece=="K") selector(cell,kingTest)
 else if(piece=="N") selector(cell,knightTest);
 else if(piece=="Q") selector(cell,queenTest);
 else if(piece=="R") selector(cell,rookTest);
 else if(piece=="B") selector(cell,bishopTest);
}

function cellAt(col,row,board) {
 return document.body.firstChild.children[board].children[row].children[col];
}

function valid(col,row,board) {
 return 0<=col && col<size && 0<=row && row<size && 0<=board && board<size;
}

function select(cell) {
if(cell != null && cell.firstChild.hidden) cell.classList.add("highlighted");
}

function rookTest(dist) {
 var d = [].concat(dist).sort();
 return d[0] == 0 && d[1] == 0;
}

function knightTest(dist) {
 var d = [].concat(dist).sort();
 return d[0] == 0 && d[1] == 1 && d[2] == 2;
}

function kingTest(dist) {
 return dist[0] <= 1 && dist[1] <= 1 && dist[2] <= 1;
}

function bishopTest(dist) {
 return dist[0]==dist[1] && dist[1]==dist[2];
}

function queenTest(dist) {
 var d = [].concat(dist).sort();
 return rookTest(dist) || bishopTest(dist) || (d[0]==0 && d[1]==d[2]) ;
}

function dist(cell,x,y,z) {
 return [Math.abs(cell.pos[0]-x),Math.abs(cell.pos[1]-y),Math.abs(cell.pos[2]-z)];
}

function selector(cell,test) {
 for(var i = 0;i<size;i++) {
  for(var j = 0;j<size;j++) {
   for(var k = 0;k<size;k++) {
   if(test(dist(cell,k,j,i))) {
    var c = cellAt(k,j,i);
    if(c != cell) select(c);
   }
   }
   }
   }

}
```

```
table
{
 padding: 10px;
  display:inline-block;
}

table:after
{
  counter-increment: board-count -1;
  content: "("counter(board-count,upper-roman)")";
  float:right;
}

td
{
  width:28px;
  height:28px;
  border: 1px solid;
  cursor: pointer;
}

.black
{
  background-color: rgba(127,127,127,0.6);
}

.white
{
  background-color: white;
}

.start {
background-color: rgba(0,204,0,0.6);
}

.highlighted {
background-color: rgba(0,255,0,0.6);
}

.drag
{
background-color: rgba(0,204,255,0.6);
}

.selected {
background-color: green;
cursor: grab;
}

.selected img
{
  display:block;
}

.dragged {
  cursor: grabbing;
}
```

```
<body data-size=3 onload="start()"
<label for="n">Size: </label><select id="n">
<option>2</option>
<option selected>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
<div>Click or drag to place the piece. Click on the piece to change its type.</div>
</body>
```

## Challenge

Given an *n*x*n*x*n* board, determine if the white king is in checkmate.

## Input

* (Optional) *n* ≥ 2 - the size of the board
* The game board
    + Can be in the form of 1d- 2d- or 3d- array, or other similar format. Notation can be in any simple format. For example, KQRBN (White) and kqrbn (Black) with # for empty cubes. Or, use numbers for the different values.
    + Think of the 3D chess board as multiple boards stacked on top of each other and listed from top to bottom. Then, each individual board is notated from left to right, back to front (Black side to White side).
    + Imagine this 2x2x2 case given as a 3D array:

```
 [
[[bq][##]]
[[bn][KQ]]
]

```

"top" board:  "bottom" board:

## Output

* boolean (truthy/falsy value) - true if white king is in checkmate, false otherwise.

## Checkmate

The white king is in **check** if a black piece threatens to capture it on Black's next turn. To get out of check, White needs to move his king to safety, defend it with another piece, or capture the threatening piece. If White has no way to get out of check, then the white king is in **checkmate** . Remember, if White is *not* in check, but can not move without getting into check, then it is a *stalemate*, which is not a checkmate.

## Specification

* You won't be given a board where the black king is trying to "check" the white king, or a board where both kings are in check (impossible scenarios).

## Test Cases

1. n=3, `[###,n##,#rr],[#b#,###,###],[###,###,bRK]`

(III) (II) (I)

Output: **true**

Explanation: The king is receiving a check from the rook on the top floor. The white rook is unable to block the attack or capture the threatening rook, so the king must try to move out of the way. Let's consider the king's move options:

1. c2(I) - guarded by bishop at b3(II)
    2. b2(I) - guarded by knight at a2(III)
    3. c1(II) - guarded by rook at c1(III)
    4. b1(II) - guarded by rook at b1(III)
    5. c2(II) - guarded by knight at a2(III)
    6. b2(II) - guarded by bishop at a1(I)

Since the king cannot escape check, it's a checkmate!

2. n=3, `[b#b,###,###],[###,###,RNR],[#q#,###,#K#]`

(III) (II) (I)

Output: **false** Explanation: The king is receiving a check from the queen, and has no moves to escape or block with. However, the knight can capture the queen.
3. n=3, `[#q#,#b#,###],[n##,###,###],[#k#,###,#KB]`

(III) (II) (I)

Output: **false** Explanation: White has no way of capturing the threatening queen or moving his king to safety. However, by moving his bishop to b2(II), White can block the queen's threat.

4. n=4, `[####,####,r###,####],[####,#q##,####,####],[##r#,###b,####,BRnn],[####,####,#N##,#KQ#]`

(IV) (III) (II) (I)

Output: **true** Explanation: In this case the king is receiving a check from one of the knights and a queen. Even though White can capture/block one of the checking pieces, he can't capture/block both. Therefore, White must try to move his king out of check, but he has no options.
5. n=3, `[###,##b,r#r],[###,###,###],[#k#,###,#K#]`

(III) (II) (I)

Output: **false** Explanation: White is not in check, but has no way of moving without getting into check. Therefore, it is a stalemate, but not a checkmate.

6. n=3, `[##k,###,r#K],[###,n##,#N#],[###,###,#Q#]`

(III) (II) (I)

Output: **true** Explanation: White would like to swoop in with his queen to defend his king, but his knight is blocking the path.

7. n=3, `[###,###,##q],[###,###,###],[#k#,###,rNK]`

(III) (II) (I)

Output: **true** Explanation: White can not take the queen with his knight, because then the rook will be checking White's king.

8. n=2, `[#q,##],[##,K#]`

(II) (I)

Output: **false** Explanation: White can capture the queen with his king.

9. n=2, `[rq,##],[##,K#]`

(II) (I)

Output: **true** Explanation: This time the rook is guarding, so the king can't capture the queen.

10. n=3, `[###,###,#q#],[###,###,###],[#k#,###,BKn]`

(III) (II) (I)

Output: **false** Explanation: The white king can escape by capturing the knight.

# Answer
# Ruby, ~~412~~ 413 bytes

```
->b,w=2{n=b=~/\n/
g=->h{h[0]-~n*(h[1]-~n*h[2])}
r=1
(n**6).times{|i|a=b*1
m=[]
9.times{|j|m<<(j<6?i/n**j%n:m[j-6]-m[j-3])}
x,y,z=v=m[6,3].map{|j|j*j}
d=v.max
e=x+y+z
q=95&o=(t=a[p=g[m[3,3]]]).ord
k=a[s=g[m]].ord
o/32==w&&(o^k>31||k==75)&&((q%8==2&&q%9*d==e||q==81&&x%d+y%d+z%d<1)&&((1...c=d**0.5).map{|j|a[p+g[m[6,3]]/c*j]}+[?#]).max<?A||q==78&&e==5||q==75&&e<4)&&(a[p]=?0;a[s]=t;r&&=w>2?a=~/K/:!f[a,3])}
r}

```

Try it online! Now checked on all test cases. Code increased by 1 byte to fix a bug on case 5 (stalemate case.)

Llambda function requiring input as a string in the format shown below. An optional second parameter can be given, indicating which group of 32 ASCII codes are to be considered on the next move (by default this 2 corresponding to uppercase/white characters, but the function calls itself recursively using 3 corresponding to lowercase/black characters.)

Recursion level 1: Tries all possible moves for white (any cube to any cube) and steps through all the legal ones. Recursion level 2: In each case it then calls itself to step through all possible moves for black. This returns true if the white king has survived all possible black moves. Recursion level 1: If all possible white moves lead to a situation where the white king does NOT survive all possible black moves, then return true (otherwise false.)

In general, a piece cannot move to a square occupied by a friendly piece. In order to consider the case where white does not move at all (hence checkmate not stalemate), the case where the king "moves" to the square he is already on is also allowed. For reasons of short code, the other white pieces are also allowed to move to the square occupied by the white king. This is a nonsense move, but allowing it does not affect the result so it is not a problem.

**The following tests are used to check if a move is valid for each piece.** `x,y,z` are the squares of the distances travelled in each axis. `e` is the sum of these (hence the square of the euclidean distance) and `d` is the maximum. The piece type is ANDed with 95 to convert lowercase ASCII values to uppercase ones.

```
Bishop and Rook (ASCII 66 and 82) For the rook e=1*d. For the bishop e=3*d.
The same code is used for both with q%9 giving 1 and 3 respectively.

Queen (ASCII 81) x%d+y%d+z%d<1 Each axis must be 0 or d, so this sum must be 0.

For the above pieces, any cubes crossed must be checked to ensure they are empty.

Knight (ASCII 78) e=5

King (ASCII 75) e<4

```

**Commented code**

```
->b,w=2{                                                        #board, colour to move (default upcase/white)
  n=b=~/\n/                                                     #n=board size (index of first newline.)
  g=->h{h[0]-~n*(h[1]-~n*h[2])}                                 #Function to calculate position in string based on array of 3d coordinates.
  r=1                                                           #Return value = truthy.
  (n**6).times{|i|                                              #Iterate through n**6 moves (n**3 start cubes and n**3 end cubes.)
    a=b*1
    m=[]                                                        #Make an empty array for coordinates.
    9.times{|j|m<<(j<6?i/n**j%n:m[j-6]-m[j-3])}                 #Split i into six base n digits for the start and end coordinates. also derive 3 relative move distances.
    x,y,z=v=m[6,3].map{|j|j*j}                                  #v=array of relative distances squared. x,y,z are the 3 individual relative distances squared.
    d=v.max                                                     #Max of x,y,z
    e=x+y+z                                                     #Square of euclidean distance
    q=95&o=(t=a[p=g[m[3,3]]]).ord                               #t=contents of cube to move from. o=ascii value, q=uppercase of o.
    k=a[s=g[m]].ord                                             #k=ascii value of contents of cube to move to.
    o/32==w&&(o^k>31||k==75)&&                                  #If o is in the right 32 byte range (uppercase or lowercase) AND the destination contains the white king or a character not in the same 32 byte range AND...
      ((q%8==2&&q%9*d==e||q==81&&x%d+y%d+z%d<1)&&               #the piece is a rook, bishop or queen with a valid move (as described in the text) AND..
      ((1...c=d**0.5).map{|j|a[p+g[m[6,3]]/c*j]}+[?#]).max<?A|| #the intervening squares are all empty, OR..
      q==78&&e==5||                                             #the piece is a knight and the move has euclidean distance sqrt(5) OR..
      q==75&&e<4)&&                                             #the piece is a king and the move has euclidean distance <4 THEN
      (a[p]=?0;a[s]=t;r&&=w>2?a=~/K/:!f[a,3])                   #put a 0 in the start cube and put the piece in the end cube. If moved piece is black, is the white king still there? AND with return value.
  }                                                             #If moved piece is white, recursively call the f to carry out the black moves. Does the white king NOT survive some black moves? AND with return value.
r}

```
> 5 votes

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


title: Room Number Locator

text:
# Question
Title: Room Number Locator
# Room Number Locator

I have come across an interesting problem solving technique at my job when given the wrong room number from a colleague for a meeting. Every now and then, while on the way to a meeting, a member on my team will send me the wrong room number, typically because they are in a rush at their desk and fat finger the wrong key.

Interestingly, upon arrival at the wrong room, I typically can guess which room they really meant by imagining a Numeric Keypad:

and by guessing an adjacent number they meant to press.

## Challenge

Your challenge is to write a function that takes a building office number (000-999) and outputs the possible typo solutions, **assuming your colleague only mistypes one digit.**

The following table shows which numbers are adjacent to each other on a Numeric Keypad:

```
0 -> 1,2
1 -> 0,2,4
2 -> 0,1,3,5
3 -> 2,6
4 -> 1,5,7
5 -> 2,4,6,8
6 -> 3,5,9
7 -> 4,8
8 -> 5,7,9
9 -> 6,8

```

## Input

A 3 digit number: `000-999`. Assume input of exactly 3 digits. If the number is less than 100 or less than 10, you will be given the leading zeros. (i.e. 004 & 028).

## Output

A list of possible rooms. This can be in any form you want, as long as there is a delimiter between room numbers. (i.e. space, comma, new line, etc..) If the number is less than 100 or less than 10, you can or cannot have the leading zeros as output, that is up to you. (i.e. 004 can be `004 04 4`, and 028 can be `028 28`)

Test Cases(leading zeros are optional):

```
008 -> 108, 208, 018, 028, 005, 007, 009
123 -> 023, 223, 423, 103, 113, 133, 153, 122, 126
585 -> 285, 485, 685, 885, 555, 575, 595, 582, 584, 586, 588
777 -> 477, 877, 747, 787, 774, 778
963 -> 663, 863, 933, 953, 993, 962, 966
555 -> 255, 455, 655, 855, 525, 545, 565, 585, 552, 554, 556, 558

```

This is , so the shortest code in bytes for each language wins.

# Answer
# Wolfram Language (Mathematica), ~~112~~ 106 bytes

Recognizing that a numeric keypad is basically a 3x3 `GridGraph` with edges added for 0, we get the adjacent digits for each input digit with `AdjacencyList`.

This can be seen below:

`EdgeAdd[GridGraph[{3,3},VertexLabels->"Name",GraphLayout->"SpringEmbedding"],{0<->1,0<->2}]` yields:

Then I use `Tuples` to figure out all the possible mistakes and pick out those with exactly one error with `Select` and `EditDistance`. By the way, this will work for longer room numbers and you can also increase the `EditDistance` parameter to allow for more than one error. Might be able to golf this down a little further but wanted to show my approach.

```
h@u_:=Select[Tuples[AdjacencyList[EdgeAdd[GridGraph[{3,3}],{0<->1,0<->2}],#]~Join~{#}&/@u],#~EditDistance~u==1&]

```

Slightly more golfed version hardcoded to length 3 room numbers (106 Bytes). This will output as a rank 3 list corresponding to each digit:

```
Thread/@ReplacePart[#~Table~3,{i_,i_}:>(AdjacencyList[GridGraph@{3,3}~EdgeAdd~{0<->1,0<->2},#]&/@#)[[i]]]&

```

Try it online!
> 13 votes

# Answer
# Python 2, 89 bytes

```
lambda r:[r[:i]+[c]+r[i+1:]for i,n in enumerate(r)for c in`ord(u'ÌЋ>তŧ0ɃD'[n])`]

```

Try it online!

The 1st and 5th characters may not being displayed here (browser dependent), but the full string is equivalent to `[21, 204, 1035, 62, 157, 2468, 359, 48, 579, 68]`
> 9 votes

# Answer
# 05AB1E, 29 bytes

```
v•4TË\ªye-³—Ïʒ••Ćδn¼•S£yèʒNǝ,

```

Try it online!
> 4 votes

# Answer
# , 190 bytes

```
function(x){l=list(c(1,2),c(0,2,4),c(0,1,3,5),c(2,6),c(1,5,7),c(2,4,6,8),c(3,5,9),c(4,8),c(5,7,9),c(6,8))
a=do.call(expand.grid, mapply(c,l[x+1],x))
a[apply(a,1,function(y){sum(x==y)==2}),]}

```

Try it online!

---

My second attempt at CodeGolf! Pretty long, 190 bytes, but the best I could manage with R. Curious to see if others have feedback or can do better!
> 3 votes

# Answer
# Ruby 97 bytes

```
->i{c=0;i.map{|j|[12,204,1035,26,157,2468,359,48,579,68][j].digits.map{|k|f=*i;f[c]=k;p f};c+=1}}

```

Try it online!

### Alternatively, 94 chars but 100 bytes

```
->i{c=0;i.map{|j|"\fÌЋ\u001A\u009Dতŧ0ɃD".unpack("U*")[j].digits.map{|k|f=*i;f[c]=k;p f};c+=1}}

```

Try it online!
> 2 votes

# Answer
## JavaScript (Firefox 30-57), ~~115~~ 109 bytes

```
f=([c,...a],p=``)=>c?[...(for(n of``+[12,240,1350,26,157,2468,359,48,579,68][c])p+n+a.join``),...f(a,p+c)]:[]

```

Edit: Saved 6 bytes thanks to @edc65 (although suggested `0`s now appear after other suggestions). ES6 version, ~~118~~ 112 bytes:

```
f=([c,...a],p=``)=>c?[...[...``+[12,240,1350,26,157,2468,359,48,579,68][c]].map(n=>p+n+a.join``),...f(a,p+c)]:[]
```

```
<input oninput=o.textContent=f(this.value).join`\n`><pre id=o>
```
> 2 votes

# Answer
# C (gcc), 136 or 114 bytes

## ASCII version 136 bytes

```
m[]={12,240,1350,26,157,2468,359,48,579,68},p,i,X=10;f(n){for(i=100;i;i/=X)for(p=m[n/i%X];p;p/=X)printf("%d ",n/(i*X)*(i*X)+p%X*i+n%i);}

```

Try it online!

## Unicode ~~114~~ 108 bytes (TiO seems to count weirdly for this)

Thanks to @ceilingcat for this version.

```
p,i,X=10;f(n){for(i=1e3;i/=X;)for(p=L"\fðՆ\32\x9dতŧ0ɃD"[n/i%X];p;p/=X)printf("%d ",n/i/X*i*X+p%X*i+n%i);}

```

Try it online!
> 2 votes

# Answer
# Java, 205 177 bytes

```
b->{for(int c=0;c<3;c++){char[]d=b.toCharArray();for(char e:"12,024,0135,26,157,2468,359,48,579,68".split(",")[new Byte(""+d[c])].toCharArray()){d[c]=e;System.out.println(d);}}}

```

I know it's long compared to the other answers. My excuse: it's in Java.
Oracle should rename `toCharArray` to something like `getCrs`.

## Credits

-28 characters by **Kevin Cruijssen**
> 2 votes

# Answer
# Python 2, 103 bytes

thanks to @Lynn for -4 bytes.

```
lambda n:{n[:i]+r+n[i+1:]for i,v in enumerate(n)for r in`0x134cd9a07d1e58feab643f7db24102`[int(v)::10]}

```

Try it online!
> 1 votes

# Answer
# Jelly, 35 bytes

```
ḷþị“-ⱮⱮVḟ|żṣ~ẋ³ɱgẆ’ḃ⁽¦ḳ¤$ṛ¦DŒp$¥"JẎ

```

Try it online!

-1 thanks to Jonathan Allan.

*Explanation being updated...*
> 1 votes

# Answer
# Perl 5, ~~120~~ 85 + 2 (`-F`) = 87 bytes

```
map{@,=@F;$,[$i]=$_,say@,for(12,240,1350,26,157,2468,359,48,579,68)[$_]=~/./g;$i++}@F

```

Try it online!

Saved 35 bytes by borrowing an idea from @AsoneTuhid's ruby answer.
> 1 votes

# Answer
# Julia 0.6, 93 bytes

```
~r=[(R=copy(r);R[j]=i;R)for i=0:9,j=1:3 if(big(1)<<(i+10r[j]))&0x502A044228550A21102B05406>0]

```

Try it online!

* Takes a vector of digits and returns a list in the same format.
* `0x502A044228550A21102B05406` is a `UInt128` in which the `1+10j`th bit is set iff `i` is next to `j` on the numpad.
* `big(1)` is a `BigInt`. It is used to prevent overflow and uses less characters than `Int128(1)` or `UInt128(1)`.
> 1 votes

# Answer
## SQL (SQLite), 533 bytes

```
with m as (select 0 as i, 1 as o union values (0,2),(1,0),(1,2),(1,4),(2,0),(2,1),(2,3),(2,5),(3,2),(3,6),(4,1),(4,5),(4,7),(5,2),(5,4),(5,6),(5,8),(6,3),(6,5),(6,9),(7,4),(7,8),(8,5),(8,7),(8,9),(9,6),(9,8))select o || substr('008', 2, 1) || substr('008', 3, 1)from m where substr('008', 1, 1) = cast(i as text)union select substr('008', 1, 1) || o || substr('008', 3, 1)from m where substr('008', 2, 1) = cast(i as text)union select substr('008', 1, 1) || substr('008', 2, 1) || o from m where substr('008', 3, 1) = cast(i as text)

```

### Ungolfed

```
with m as (
    select 0 as i, 1 as o
    union
    values
    /*(0,1),*/(0,2),
    (1,0),(1,2),(1,4),
    (2,0),(2,1),(2,3),(2,5),
    (3,2),(3,6),
    (4,1),(4,5),(4,7),
    (5,2),(5,4),(5,6),(5,8),
    (6,3),(6,5),(6,9),
    (7,4),(7,8),
    (8,5),(8,7),(8,9),
    (9,6),(9,8)
)
select o || substr(s, 2, 1) || substr(s, 3, 1)
from m, t
where substr(s, 1, 1) = cast(i as text)
union
select substr(s, 1, 1) || o || substr(s, 3, 1)
from m, t
where substr(s, 2, 1) = cast(i as text)
union
select substr(s, 1, 1) || substr(s, 2, 1) || o
from m, t
where substr(s, 3, 1) = cast(i as text)

```

### Explanation

The input is a single text row on table `t` with column `s`. My understanding is that according to this meta answer this is an acceptable form of input. The input can be created as below.

```
drop table if exists t;
create table t (s text);
insert into t values('555'); -- Your input here

```

### Annotated solution

```
with m as ( -- Using this in the "with" allows us to only type is once
    select 0 as i, 1 as o -- The first pair is here and it names the columns
    union
    values
    /*(0,1),*/(0,2),
    (1,0),(1,2),(1,4),
    (2,0),(2,1),(2,3),(2,5),
    (3,2),(3,6),
    (4,1),(4,5),(4,7),
    (5,2),(5,4),(5,6),(5,8),
    (6,3),(6,5),(6,9),
    (7,4),(7,8),
    (8,5),(8,7),(8,9),
    (9,6),(9,8)
)
select o || substr(s, 2, 1) || substr(s, 3, 1) -- concat the first wrong char with two correct chars
from m, t
where substr(s, 1, 1) = cast(i as text) -- when the first char is in the i (input) column from above
union
select substr(s, 1, 1) || o || substr(s, 3, 1)
from m, t
where substr(s, 2, 1) = cast(i as text)
union
select substr(s, 1, 1) || substr(s, 2, 1) || o
from m, t
where substr(s, 3, 1) = cast(i as text)

```
> 1 votes

# Answer
# Kotlin, 117 bytes

```
mapIndexed{i,c->"12,024,0135,26,157,2468,359,48,579,68".split(",")[c-'0'].map{replaceRange(i,i+1,it+"")}}.flatMap{it}

```

## Beautified

```
mapIndexed { i, c ->
    "12,024,0135,26,157,2468,359,48,579,68"
        .split(",")[c - '0']
        .map { replaceRange(i, i + 1, it + "") }
}.flatMap { it }

```

## Test

```
fun String.f(): List<String> =
mapIndexed{i,c->"12,024,0135,26,157,2468,359,48,579,68".split(",")[c-'0'].map{replaceRange(i,i+1,it+"")}}.flatMap{it}

data class Test(val input:Int, val answers: List<Int>)

val tests = listOf(
    Test(8, listOf(108, 208, 18, 28, 5, 7, 9)),
    Test(123, listOf(23, 223, 423, 103, 113, 133, 153, 122, 126)),
    Test(585, listOf(285, 485, 685, 885, 555, 575, 595, 582, 584, 586, 588)),
    Test(777, listOf(477, 877, 747, 787, 774, 778)),
    Test(963, listOf(663, 863, 933, 953, 993, 962, 966)),
    Test(555, listOf(255, 455, 655, 855, 525, 545, 565, 585, 552, 554, 556, 558))
)

fun main(args: Array<String>) {
    for (r in tests) {
        val input = r.input.toString().padStart(3, '0')
        val expected = r.answers.map { it.toString().padStart(3, '0') }.sorted()
        val actual = input.f().sorted()
        if (expected != actual) {
            throw AssertionError("$input -> $actual | $expected")
        }
    }
}

```

## TIO

TryItOnline
> 1 votes

# Answer
# T-SQL, 322 bytes

```
WITH m AS(SELECT LEFT(value,1)i,RIGHT(value,1)o FROM STRING_SPLIT('01,02,10,12,14,20,21,23,25,32,36,41,45,47,52,54,56,58,63,65,69,74,78,85,87,89,96,98',','))SELECT o+RIGHT(s,2)FROM t,m WHERE i=LEFT(s,1)UNION SELECT LEFT(s,1)+o+RIGHT(s,1)FROM t,m WHERE i=SUBSTRING(s,2,1)UNION SELECT LEFT(s,2)+o FROM t,m WHERE i=RIGHT(s,1)

```

The input is taken from the column `s` of a single-row table named `t`:

```
DROP TABLE IF EXISTS t
CREATE TABLE t (s CHAR(3))
INSERT INTO t VALUES('008')

```

Ungolfed:

```
WITH m AS (
    SELECT LEFT(value,1) i, RIGHT(value,1) o
    FROM STRING_SPLIT('01,02,10,12,14,20,21,23,25,32,36,41,45,47,52,54,56,58,63,65,69,74,78,85,87,89,96,98',',')
)
SELECT o+RIGHT(s,2) FROM t,m WHERE i=LEFT(s,1)
UNION
SELECT LEFT(s,1)+o+RIGHT(s,1) FROM t,m WHERE i=SUBSTRING(s,2,1)
UNION
SELECT LEFT(s,2)+o FROM t,m WHERE i=RIGHT(s,1)

```

SQLFiddle
> 1 votes

---
Tags: code-golf
---


title: unRSA: solve the private key

text:
# Question
Title: unRSA: solve the private key
Given positive integer `n` and `e`, knowing that `e<n` and that `n` is the product of two different odd primes(but the primes are not directly given to you), find such a positive integer `d` smaller than `n` that, for each integer `m`, (me)d ≡ m (mod n).

Your program should handle `n` up to 24096 in 1TB space, but not necessary reasonable time. You can assume such a `d` exist.

Sample Input: `n=53*61=3233, e=17`

Sample output: `d=413`

Note that your program will not be given the prime factor of `n`.

Shortest code in bytes win.

# Answer
> 3 votes
# Python 3, 77 bytes

```
def f(n,e):r=range(n);all(any(m-pow(m,e*d,n)for m in r)or print(d)for d in r)

```

Try it online!

Direct translation of the requirement. `any(...)` becomes false when the smallest correct `d` is found, and `print(d)` returns `None`, making `all(...)` stop running.

# 76 bytes, if unlimited memory is allowed

```
def f(n,e):r=range(n);all(any(m**(e*d)%n-m for m in r)or print(d)for d in r)

```

Try it online!

# Answer
> 2 votes
# Python 2, 65 bytes

```
n,e=input()
p=s=1
while n%~p:p+=1
while s%e:s-=p*n/~p+p
print s/e

```

Try it online!

Finds a prime factor `p` of `n` to obtain the order `φ(n)=(p-1)(n/p-1)`. Then, solves the modular equation `d * e % φ(n) == 1` by counting up values `s` of the form `s = 1 + c * φ(n)` until a multiple of `e`is obtained. Since all expressions are arithmetical without exponents, only log-space is used.

The code actually uses `p` to stand for one below the prime to save bytes on initialization.

---

# Python 2, 78 bytes

```
lambda n,e:pow(e,F(F(n))-1,F(n))
F=lambda n:sum(k/n*k%n==1for k in range(n*n))

```

Try it online!

A direct expression using Dennis's totient function implementation.

# Answer
> 1 votes
# Jelly, 5 bytes

Thanks to *xnor* for -2 bytes! (pointing out `ÆṪ`, totient function)

```
ÆṪæi@

```

Try it online!

Previously I used `Æf’Pæi@` at 7 bytes.

---
Tags: code-golf, number-theory, restricted-memory
---


# Question
Title: Eiffel Towers: Create a large "A" from "A"s
Create a function which given a number of lines `n`, makes a `bigA`.

* The horizontal bar of `bigA` must be at the middle row, or the lower of the two if `n` is even
* Assume a monospace font for output

Output should be a string (or similar, eg character array) with clear linebreaks to break up the lines, and with correct whitespace for left-padding (you can assume \t to be 4 spaces). There can be any whitespace on the right.

## Examples

### n = 1

`A`

### n = 2

```
 A
AAA

```

### n = 3

```
  A
 AAA
A   A

```

### n = 4

```
   A
  A A
 AAAAA
A     A

```

### n = 5

```
    A
   A A
  AAAAA
 A     A
A       A

```

This is inspired by Create an "H" from smaller "H"s

# Answer
> 12 votes
# 05AB1E, 13 bytes

### Code:

```
Ð;î¹)'A1376SΛ

```

Uses the **05AB1E** encoding. Try it online!

### Explanation:

```
Ð                  # Triplicate the input.
 ;î                # Compute ceiling(n / 2).
   ¹               # Push the first input again.
    )              # Wrap into an array. For input 7, this would result in:
                     [7, 7, 4, 7].
     'A            # Push the character 'A'
       1376S       # Push the array [1, 3, 7, 6]. These are the directions of the canvas.
                     This essentially translates to [↗, ↘, ↖, ←].
            Λ      # Write to canvas using the previous three parameters.

```

### Canvas

I should probably document the canvas a little bit more (and a lot of other functions), but this basically sums it up. The canvas has different 'modes' based on the parameter types given. The canvas command has three parameters: **\<length\> \<string\> \<direction\>**.

Since the length and direction parameters are lists, it 'zips' these lists to create a set of instructions to be executed. The string parameter is just the letter **A**, so this is the fill character used by all instructions. The canvas interprets this as the following set of instructions (for input 7):

* Draw a line of length **7** with the string **A** in direction
* Draw a line of length **7** with the string **A** in direction
* Draw a line of length **4** with the string **A** in direction
* Draw a line of length **7** with the string **A** in direction

The directions are translated in the following manner:

```
7   0   1
  ↖ ↑ ↗
6 ← X → 2
  ↙ ↓ ↘
5   4   3

```

If nothing has been outputted, 05AB1E automatically outputs the canvas result.

# Answer
> 6 votes
# Charcoal, ~~17~~ 15 bytes

```
ＮθＰ×θAＭ⊘θ↗Ｐ^×θA

```

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

```
Ｎθ

```

Input `n`.

```
Ｐ×θA

```

Print the horizontal bar of the big `A`. (For even numbers, the `n+1`th overlaps the right side anyway.)

```
Ｍ⊘θ↗

```

Move to the top of the big `A`.

```
Ｐ^×θA

```

Print both sides of the big `A`.

# Answer
> 4 votes
# Python 2, 80 bytes

```
lambda n:'\n'.join(' '*(n+~i)+('A'+' A'[i==n/2]*n*2)[:i*2]+'A'for i in range(n))

```

Try it online!

Divide the desired output into the left whitespace, left `A` plus middle whitespace or `A`s, and the right `A`. Compute the middle part using slicing on a fixed string. This allows to use the same way to generate the first line.

# Answer
> 4 votes
# Stax, 15 bytes

```
┴3╬*ôP^x'┌_╓J²♫

```

Run and debug it

Unpacked, ungolfed, and commented, the program looks like this.

```
m       map over [1 .. input] using rest of the program, output each result
'A      "A" literal
xhi=    is the iteration index equal to (integer) half the input?
65*     multiply by 65 (character code of "A")
]i*     repeat that character (" " or  "A") i times
+       concat to initial "A"
x)      left pad to the original input
|p      palindromize (concatenate the reverse minus the last character)

```

Run this one

# Answer
> 4 votes
# JavaScript (ES6), 77 bytes

This source code has a rectangle shape! Oh wait ... wrong challenge :-/

```
f=(n,k=n>>1,p='A')=>--n?f(n,k,' '+p)+`
${p}${(k-n?' ':'A').repeat(n*2-1)}A`:p

```

Try it online!

# Answer
> 4 votes
# Python 3.6, 79 bytes or 73 bytes

Using **f-strings** to align horizontal parts of the letter:

```
lambda n:'\n'.join(f"{'A'+' A'[i==n//2]*2*i:>{n+i}}"[:-1]+'A'for i in range(n))

```

With `\b` used to delete one `A` (possibly cheating):

```
lambda n:'\n'.join(f"{'A'+' A'[i==n//2]*2*i:>{n+i}}\bA"for i in range(n))

```

# Answer
> 3 votes
# Java (JDK), 121 bytes

```
n->{var a=new char[n][n+n-1];for(int c=n*n,r,q;c-->0;a[r=c%n][q=c/n]=a[r][n+n-q-2]+=r==n/2&q>=r|r==n+~q?65:32);return a;}

```

Try it online!

## Credits

# Answer
> 3 votes
# , 65 bytes

```
f=:3 :''' A''{~1(([:(<@;]+i.@+:)<.@-:)y)}([:(}:@|."1,.])=/~@i.)y'

```

Try it online!

It can be reduced by approx. 12 bytes by simply making the verb tacit, but I have problems doing it.

## Explanation:

`3 : '...'` denotes an explicit one-liner verb

`y` is the argument

`=/~@i.` creates an identity matrix with size the argument

```
    =/~@i. 4
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

```

`([:(}:@|."1,.])` prepends the identity matrix with its mirror copy with last elements of each row dropped.

```
    ]a =. ([:(}:@|."1,.])=/~@i.) 4
0 0 0 1 0 0 0
0 0 1 0 1 0 0
0 1 0 0 0 1 0
1 0 0 0 0 0 1

```

`1(...)}(...)` changes to 1 the positions in its right argument, selected by the left one

`([:(<@;]+i.@+:)<.@-:)` \- prepares the selection by doing the following:

```
               <.@-: - halves the argument and finds the floor (finds the row number)
    <@;              - box the row, followed by a list of columns:
        ]+i.@+:      - a list form the argumnt to the doubled row number

    ([:(<@;]+i.@+:)<.@-:) 4
┌───────────┐
│┌─┬───────┐│
││2│2 3 4 5││
│└─┴───────┘│
└───────────┘

    1(([:(<@;]+i.@+:)<.@-:) 4)}a
0 0 0 1 0 0 0
0 0 1 0 1 0 0
0 1 1 1 1 1 0
1 0 0 0 0 0 1

```

`' A'{~` renders a space in the places of 0 and 'A' where there is 1

```
    ' A'{~1(([:(<@;]+i.@+:)<.@-:) 4)}a
   A
  A A
 AAAAA
A     A

```

# Answer
> 3 votes
# Canvas, ~~17~~ 13 bytes

```
A×／╶½A×╶»╵：╋│

```

Try it here!

*-4 bytes thanks to dzaima!*

# Answer
> 2 votes
# Japt `-R`, ~~20~~ 19 bytes

```
Çç" A"gZ¶Uz¹i'A êÃû

```

Try it

---

## Explanation

```
                        :Implicit input of integer U
Ç                       :Create the range [0,U) and pass each Z through a function
         Uz             :  Floor divide U by 2
       Z¶               :  Test for equality with Z (true=1, false=0)
  " A"g                 :  Get the character in the string " A" at that index
 ç                      :  Repeat Z times
           ¹            :  (Closes a few nested methods)
            i'A         :  Prepend an "A"
                ê       :  Palindromise
                 Ã      :End function
                  û     :Centre pad each element to the length of the longest element
                        :Implicitly join with newlines and output

```

---

## Alternative

(In the hope that it might help me spot some savings!)

```
Æ'AúXÄ" A"gX¶Uz¹êÃû

```

# Answer
> 2 votes
# SOGL V0.12, 12 bytes

```
 A*:╚╥≤.»I:ž

```

Try it Here!

Explanation:

```
 A*           repeat "A" input times
   :          duplicate it
    ╚         create a "/" diagonal of one of the copies of As
     ╥        palindromize it horizontally
      ≤       get the other copy of the "A"s on top
       .»I:   push floor(input/2)+1 twice
           ž  and at those coordinates in the palindromized diagonals place in the row of As

```

# Answer
> 2 votes
# Ruby, 66 bytes

```
->n{(0...n).map{|i|(s=(i==n/2??A:?\s)*2*i+?A)[0]=?A;?\s*(n+~i)+s}}

```

Try it online!

Returns as array of lines

# Answer
> 1 votes
# Jelly, ~~23~~ ~~20~~ ~~19~~ 18 bytes

```
=þ`o\L‘HĊƲ¦UŒBị⁾A

```

Try it online!

`=þ`` creates an identity matrix of size `n`.

`L‘HĊƲ` finds the row index of the horizontal bar with `¦` picking that row out and applying `o\` to it which creates the bar.

`U` reverses each row so we don't have an upside down "A" and `ŒB` (palindromize; vectorizes) makes the second half of the "A".

`ị⁾A` (with a space that is getting trimmed in the formatting) replaces `0`s with spaces and `1`s with `A`s.

# Answer
> 1 votes
# Javascript, 124 bytes

A fairly naive solution, gave it a shot to practice js skills.

`for(i=-1,p=" ".repeat(n-1)+"A ";++i<n;console.log(i-~~(n/2)?p:p.slice(0,i)+"A".repeat(n)),p=p.slice(1,n)+" "+p.slice(n-1)){}`

Unpacked

```
for(
 //create the first line
 i=-1, p=" ".repeat(n-1)+"A ";
 ++i<n;
 console.log(
 //if we are not at the bar
      i-~~(n/2)?
 //otherwise, use the modified previous line
      p
 //slice the start of the previous line and add As
      :p.slice(0,i)+"A".repeat(n)),
 //add a space in between the previous line and remove padding on each side
 p=p.slice(1,n)+" "+p.slice(n-1)){}

```

# Answer
> 1 votes
# Ruby, 73 bytes

```
->n{(0...n).map{|i|(?A.ljust(i*2,i==n/2??A:' ')+(i>0??A:'')).center n*2}}

```

Try it online!

# Answer
> 1 votes
# T-SQL, ~~182~~ 177 bytes

```
DECLARE @n INT=5DECLARE @ INT=0a:DECLARE @s VARCHAR(9)=STR(POWER(10,@),@n)PRINT REPLACE(REPLACE(@s+REVERSE(LEFT(@s,@n-1)),'1','A'),'0',IIF(@=@n/2,'A',' '))SET @+=1IF @<@n GOTO a

```

First version (with 182 bytes):

```
DECLARE @n INT=5DECLARE @ INT=0WHILE @<@n BEGIN DECLARE @s VARCHAR(9)=STR(POWER(10,@),@n)PRINT REPLACE(REPLACE(@s+REVERSE(LEFT(@s,@n-1)),'1','A'),'0',IIF(@=@n/2,'A',' '))SET @+=1 END

```

The version above works up to @n=9.

Here is another version, which works up to @n=23, but has 2 extra bytes:

```
DECLARE @n INT=5DECLARE @ INT=0WHILE @<@n BEGIN DECLARE @s VARCHAR(23)=STR(POWER(10.,@),@n)PRINT REPLACE(REPLACE(@s+REVERSE(LEFT(@s,@n-1)),'1','A'),'0',IIF(@=@n/2,'A',' '))SET @+=1 END

```

Ungolfed:

```
DECLARE @n INT=5

DECLARE @i INT=0
WHILE @i<@n BEGIN
    DECLARE @s VARCHAR(9)=STR(POWER(10,@i),@n)
    PRINT REPLACE(REPLACE(@s+REVERSE(LEFT(@s,@n-1)),'1','A'),'0',IIF(@i=@n/2,'A',' '))
    SET @i+=1
END

```

# Answer
> 1 votes
# Haskell, ~~98~~ ~~97~~ 95 bytes and 109 bytes

Two very different approaches. First (95 bytes):

```
c!n=([1..n]>>c)++"A"
f n=unlines[" "!(n-x)++drop 3([" "!(abs$n`div`2-x+1)!!0]!(2*x))|x<-[1..n]]

```

and second (109 bytes):

```
m True='A'
m _=' '
g n=unlines[[m(abs(n-j)==l||l==q&&elem j[q+1..q+n])|j<-[1..2*n]]|l<-[0..n-1],q<-[n`div`2]]

```

~~Try them here!~~; ~~Try modified version here!~~

Try third version here!

# Answer
> 1 votes
# Python 2, 70 bytes or 65 bytes

List of strings is acceptable result, as @Budd stated in comments.

```
lambda n:['%*sA\n'%(n+i,('A'+i*2*' A'[i==n/2])[:-1])for i in range(n)]

```

Try it online!

---

Seemingly cheaty solution, using `\b`. It looks funky in TIO, in console it does the job.

```
lambda n:['%*s\bA\n'%(n+i,'A'+i*2*' A'[i==n/2])for i in range(n)]

```

Try it online!

# Answer
> 0 votes
# Python 3, 93, 88 bytes

```
lambda n:'\n'.join(f"{'A'+(x>0)*('A '[x!=n//2]*(x*2-1)+'A'):^{n*2-1}}"for x in range(n))

```

Try it online!

-3 by @ovs using f-string

# Answer
> 0 votes
# Perl 5 `-n`, 57 bytes

```
#!/usr/bin/perl -n
say$"x-$_.uc(A x($n+$_&-2?1:$n*2)|$"x2x$n++.A)for 1-$_..0

```

Try it online!

---
Tags: code-golf, ascii-art
---


title: Work out root(x, n)

text:
# Question
Title: Work out root(x, n)
Given integers 0\<x\<10106 and 0\<n\<106, work out x(1/n) under 15 seconds(TIO or your computer), 1GB memory. You can assume the result is integer smaller than 50000.

Shortest code in bytes in each language win.

Sample:

```
x     n     result
121   2     11
123   1     123
1024  10    2

```

A larger sample can be seen here

# Answer
> 3 votes
# Pari/GP, 12 bytes

```
x->n->x^n^-1

```

Try it online!

All test cases, including the sample test case (1234^123456) and case x=10^10^6-1 & n=10^6-1, finish in under 50ms.

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

```
n=>x=>10**((x.length+Math.log10('.'+x.slice(0,99)))/n)+.5|0

```

Try it online!

---
Tags: code-golf, math
---


title: Drunkard's Journey Home

text:
# Question
Title: Drunkard's Journey Home
# Drunkard's Journey Home

In this challenge you are to write a program which simulates a drunkard stumbling his way home from the bar.

### Input:

The input will be an adjacency matrix (representing a directed graph) which represents paths the drunkard can take. At each location, the drunkard will choose one path at random (Each option has an approximately equal chance and is independent of prior choices) to follow.

Assume that the drunkard always starts at the bar (first row in the adjacency matrix).

If the drunkard enters a dead-end it can be assumed that he has either made his way home or has been arrested for public intoxication and the program should return his path.

It can be assumed that the graph will always contain at least one dead-end.

It can also be assumed that the drunkard will always be able to exit the bar (the first row will not be all zeroes) and that if the drunkard would be stuck in a location, that the row would be represented by all zeroes.

### Output:

The output will be the path the drunkard took in his attempt to make his way home. The values for the locations can be either zero or one indexed.

### Examples:

```
Input
[1,0,1,1]
[0,0,0,0]
[1,0,0,0]
[1,1,1,1]

Possible Outputs
[0,2,0,3,2,0,0,3,1]
[0,3,0,3,1]

Input
[0,1,1,1,0,1]
[1,0,1,0,1,1]
[0,0,0,0,0,0]
[0,0,0,0,0,1]
[1,0,0,0,0,0]
[0,0,0,0,0,0]

Possible outputs
[0,1,5]
[0,5]
[0,1,4,0,2]
[0,3,5]
[0,3,0,1,4,0,5]

Deterministic path:

Input
[0,0,1,0]
[0,0,0,1]
[0,1,0,0]
[0,0,0,0]

Output
[0,2,1,3]

```

# Answer
## Mathematica, 72 bytes

```
{1}//.{r___,x_}:>{r,x,n=1;Check[RandomChoice[#[[x]]->(n++&/@#)],##&[]]}&

```

This is a function takes the matrix as an argument and returns a list, and it uses 1-indexing.

The basic idea is to start with

```
{1}//.

```

which repeatedly applies the rule that follows to the list `{1}` until it stops changing. The rule matches the pattern

```
{r___,x_}:>

```

which means "a list with zero or more elements called `r` followed by an element called `x`." This gives `x` as the last element in the current list, and we replace the list with

```
{r,x,<stuff>}

```

which is the original list with `<stuff>` appended. The stuff in question is

```
RandomChoice[#[[x]]->(n++&/@#)]

```

which takes `#[[x]]` (the `x`th element of the input matrix) as a list of weights and maps them to `n++&/@#`, which is short for `Range@Length@#` (i.e. `{1,2,3,...}` with the appropriate length). This will throw an error if the weights are all zero, which is why it's wrapped in a

```
Check[...,##&[]]

```

which will return `##&[]` if an error message is generated. This is just a fancy way of writing `Sequence[]`, which acts as a "nothing" element (`{1,2,Sequence[],3}` evaluates to `{1,2,3}`) and therefore leaves the list unchanged, causing the `//.` to stop replacing.
> 7 votes

# Answer
# , ~~72~~ ~~69~~ 66 bytes

```
function(m,o=1)while({print(o);any(x<-m[o,])})o=sample(which(x),1)

```

Try it online!

Takes input as a `logical` matrix, and prints the 1-based indices to the console.
> 4 votes

# Answer
# MATL,15 bytes

```
1`GyY)ft?th1ZrT

```

Output is 1-based.

Try it online! First input. Second input. Third input.

### Explanation

```
1          % Push 1: initial value of current row index
`          % Do...while
  G        %   Push input matrix
  y        %   Duplicate from below: pushes copy of current row index
  Y)       %   Get that row
  f        %   Find: push (possibly empty) array of indices of non-zero entries
  t        %   Duplicate
  ?        %   If non-empty
    th     %     Attach a copy of itself. This is needed in case the array
           %     contains a single number n, because then the randsample
           %     function would incorrectly treat that as the array [1 2 ... n]
    1Zr    %     Randsample: pick 1 entry at random with uniform probability
    T      %     Push true
           %   End (implicit)
           % End (implicit). Proceed with a new iteration if the top of the
           % stack is truthy. This happens if the current row had some
           % non-zero entry, in which case true was pushed (and is now
           % consumed). If the current row was all zeros, the top of the stack
           % is an empty array that was produced by the find function, which is
           % falsy (and is also consumed now). In that case the loop is exited,
           % and then the stack contains a collection of numbers which
           % collectively describe the path
           % Implicit display

```
> 3 votes

# Answer
# Perl 5 `-a0`, ~~53~~ 51 bytes

Give input matrix as separate tight strings on STDIN

```
$!/usr/bin/perl -a0
$n=!say$%;$F[$%]=~s:1:($%)=@-if 1>rand++$n:eg&&redo

```

Try it online!

Damages `@F` during the loop body but it gets repaired by `redo`
> 3 votes

# Answer
# JavaScript (ES6), 87 bytes

```
f=(a,y=0)=>[y,.../1/.test(r=a[y])?f(a,(g=_=>r[k=Math.random()*r.length|0]?k:g())()):[]]

```

Try it online!

---

# Alternate version, 81 bytes

Takes input as an array of binary strings. The maximum supported size is 16x16.

```
f=(a,y=0)=>[y,...+(r=a[y])?f(a,(g=_=>+r[k=Math.random()*r.length|0]?k:g())()):[]]

```

Try it online!
> 2 votes

# Answer
# Python, 136 bytes

Using zero indexing, assuming randrange has been imported. Takes an input m as the adjacency matrix

**113 no imports**

`s=lambda m,c=0,p=[0],x=0:1 in m[c]and(m[c][x]and s(m,x,p+[x],randrange(len(m)))or s(m,c,p,randrange(len(m))))or p`

**136 with imports**

`import random as r;s=lambda m,c=0,p=[0],x=0:1 in m[c]and(m[c][x]and s(m,x,p+[x],r.randrange(len(m)))or s(m,c,p,r.randrange(len(m))))or p`
> 2 votes

# Answer
# Ruby, ~~70 67~~ 65 bytes

```
f=->m,i=0{m[i].sum<1?[]:m[i][x=rand(m.size)]<1?f[m,i]:[x]+f[m,x]}

```

Thanks to benj2240 for saving 2 bytes!

Try it online!
> 2 votes

# Answer
# Perl 6, 38 bytes

```
{0,{.[$^l].grep(?*,:k).roll}...^!*.kv}

```

Try it online!
> 2 votes

# Answer
# Java 10, 135 bytes

```
m->{var R="0 ";for(int r=0,c,t;;R+=(r=c)+" "){t=0;for(int x:m[r])t+=x;if(t<1)return R;for(t=c=m.length;m[r][c*=Math.random()]<1;)c=t;}}

```

0-indexed

**Explanation:**

Try it online.

```
m->{                   // Method with integer-matrix parameter and String return-type
  var R="0 ";          //  Result-String, starting at "0 "
  for(int r=0,         //  Row-integer, starting at 0
          c,           //  Column-integer
          t;           //  Temp-integer
      ;                //  Loop indefinitely
       R+=             //    After every iteration: Append the result with:
          (r=c)+" "){  //     The current column and a delimiter-space,
                       //     And set the current row to this column at the same time
    t=0;               //   (Re-)set `t` to 0
    for(int x:m[r])    //   Loop over the values of the current row
      t+=x;            //    And add them to `t`
    if(t<1)            //   If the entire row only contained zeroes:
      return R;        //    Return the result
    for(t=c=m.length;  //   Set `t` (and `c`) to the size of the matrix
        m[r][c*=Math.random()]<1;)
                       //   Loop until we've found a 1,
                       //   picking a random column in the range [0,`c`)
      c=t;}}           //    Reset the range of `c` to `t` (the size of the matrix)

```
> 1 votes

# Answer
# Haskell, ~~123~~ 118 bytes

```
import System.Random
i#m|sum(m!!i)<1=pure[]|1<2=do{x<-randomRIO(0,length m-1);[i#m,x#m>>=pure.(x:)]!!(m!!i!!x)}
f=(0#)

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Unicode), 32 ~~34~~ bytes

```
t←⎕
{}{s[?≢s←⍸⍵⊃t]}⍣{~0∊t⊃⍨⎕←⍵}1

```

Try it online!

Takes a nested binary array as input. Outputs each iteration on separate lines.
> 1 votes

# Answer
# Python, ~~97~~ 94 bytes

```
f=lambda a,i=0,j=0:sum(a[i])and[i]*a[i][j]+f(a[:],(i,j)[a[i][j]],id(a)**7%~-2**67%len(a))or[i]

```

Try it online!

---

See this answer for more explanation about the random number generator:

```
id(a)**7%~-2**67

```
> 1 votes

---
Tags: code-golf, random, graph-theory
---