title: Cambridge Transposition

text:
# Question
Title: Cambridge Transposition
I'm sure most, if not all, of you have come across this at some point or another:

> Aoccdrnig to a rscheeachr at Cmabrigde Uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is taht the frist and lsat ltteer be at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit porbelm. Tihs is bcuseae the huamn mnid deos not raed ervey lteter by istlef, but the wrod as a wlohe.

* Create a program that inputs any amount of text. For testing purposes, use the unscrambled version of the above text, found below.
* The program must then randomly transpose the letters of each word with a length of 4 or more letters, except the first and last letter of each word.
* All other formatting must remain the same (capitalization and punctuation, etc.).

Testing text:

> According to a researcher at Cambridge University, it doesn't matter in what order the letters in a word are, the only important thing is that the first and last letter be at the right place. The rest can be a total mess and you can still read it without problem. This is because the human mind does not read every letter by itself but the word as a whole.

As usual, this is a code-golf. Shortest code wins.

# Answer
> 10 votes
## Ruby - 50 48 chars, plus `-p` command line parameter.

```
gsub(/(?<=\w)\w+(?=\w)/){[*$&.chars].shuffle*''}

```

Thanks @primo for -2 char.

## Test

```
➜  codegolf git:(master) ruby -p 9261-cambridge-transposition.rb < 9261.in
Acdrcinog to a racreseher at Cagribmde Ursvetniiy, it dsoen't mttaer in waht odrer the leertts in a word are, the olny ionarpmtt tnhig is that the fsirt and last letetr be at the rghit pcale. The rset can be a taotl mses and you can slitl raed it wthiuot perlbom. Tihs is buaecse the hmuan mind does not raed ervey lteetr by ietlsf but the word as a wlhoe.

```

# Answer
> 5 votes
## PHP 84 bytes

```
<?for(;$s=fgets(STDIN);)echo preg_filter('/\w\K\w+(?=\w)/e','str_shuffle("\0")',$s);

```

Using a regex to capture words that are at least ~~4~~ 3 letters long, and shuffling the inner characters. This code can handle input with multiple lines as well.

If only one line of input is required (as in the example), this can be reduced to **68 bytes**

```
<?=preg_filter('/\w\K\w+(?=\w)/e','str_shuffle("\0")',fgets(STDIN));

```

---

There's only one letter in the middle, so it doesn't matter if you shuffle it.

# Answer
> 5 votes
# Python, 118

Python is terribly awkward for things like this!

```
from random import*
for w in raw_input().split():l=len(w)-2;print l>0and w[0]+''.join((sample(w[1:-1],l)))+w[-1]or w,

```

### Bonus

I tried some other things that I thought would be clever, but you have to import all sorts of things, and a lot of methods don't have return values, but need to be called separately as its own statement. The worst is when you need to convert the string to a list and then `join`ing it back to a string again.

Anyways, here are some of the things that I tried:

Regex!
```
import re,random
def f(x):a,b,c=x.group(1,2,3);return a+''.join(random.sample(b,len(b)))+c
print re.sub('(\w)(\w+)(\w)',f,raw_input())

```
Permutations!
```
import itertools as i,random as r
for w in raw_input().split():print''.join(r.choice([x for x in i.permutations(w)if w[0]+w[-1]==x[0]+x[-1]])),

```
You can't shuffle a partition of a list directly and `shuffle` returns `None`, yay!
```
from random import*
for w in raw_input().split():
 w=list(w)
 if len(w)>3:v=w[1:-1];shuffle(v);w[1:-1]=v
 print ''.join(w),

```

# Answer
> 5 votes
# Retina, 10 bytes

```
?V`\B\w+\B

```

Try it online!

Hey, this old challenge was made for the new Retina!

### Explanation

`\B\w+\B` matches groups of letters between non-boundaries, that is groups of letters that don't begin or end a word. Since regexes are greedy, this will match all the letters of a word except the first and the last one.

`V` is the "reverse" stage, that reverses the order of characters in each match of the regex. With the `?` option it scrambles them instead.

# Answer
> 3 votes
## J (48)

```
''[1!:2&4('\w(\w+)\w';,1)({~?~@#)rxapply 1!:1[3

```

Explanation:

* `1!:1[3`: read all input from stdin
* `rxapply`: apply the given function to the portions of the input that match the regex
* `({~?~@#)`: a verb train that shuffles its input: `#` counts the length, this gets applied to both sides of `?` giving N distinct numbers from 0 to N, `{` then selects the elements at those indices from the input array.
* `('\w(\w+)\w';,1)`: use that regex but only use the value from the first group
* `[1!:2&4`: send unformatted output to stdout
* `''[`: suppress formatted output. This is necessary because otherwise it only outputs that part of the output that fits on a terminal line and then ends with `...`.

# Answer
> 2 votes
## Nibbles, 15 bytes

This was a little awkward since nibbles doesn't have shuffle or even randomness (nor does it have regex).

```
+.%~@ \$a
  :@
    ::`($
      ++=~
        `)\`'$
        `# $ 0
      $

```

(Nibbles isn't on TIO yet). But use it like:

```
> nibbles cambridge.nbl < input.txt
Aoinrccdg to a raeeercshr at Caibrmgde Uvteiinrsy, it doesn't mttaer in waht oerdr the ltteers in a word are, the olny itoanrmpt tinhg is taht the first and last ltteer be at the rihgt palce. The rest can be a ttoal mess and you can stlil raed it wutoiht poelbrm. Tihs is buaecse the huamn mind does not raed every ltteer by itelsf but the word as a wolhe.

```

That's the literate form which is 30 nibbles.

That last $ could be left out but there is no point since this program is 30 nibbles (it would be 29 half bytes then rounded up)

### How?

```
+.%~@ \$a          concat the map of the split by alpha numeric chars
  :@               append the value that preceded the split match
    ::`($          append the first value of the match to
      ++=~         concat the concat of the group by of
        `)\`'$     the tail of the reverse of the transpose of the tail of the match
        `# $ 0     hash of the char (0 says range is infinite)
      $            the head of the reversed thing from earlier

```

Essentially it selects groups of alphanums, then selects the inner part of that using uncons twice. Then for randomness does a group by (which also sorts by) the hash of a character.

The transpose part is so that doing uncons on an empty string returns an empty string instead of null character (which becomes a space). You could leave it out but you'd get an extra space on 1 letter words like "a".

# Answer
> 1 votes
## APL 107

Unfortunately my APL interpreter does not support regexs so here's a home rolled version where the text to be scrambled is stored in the variable t:

```
⎕av[((~z)\(∊y)[∊(+\0,¯1↓n)+¨n?¨n←⍴¨y←(~z←×(~x)+(x>¯1↓0,x)+x>1↓(x←~53≤(∊(⊂⍳26)+¨65 97)⍳v←⎕av⍳,t),0)⊂v])+z×v]

```

Essentially the code partitions the text into words based on the letters of the alphabet only and then into the letters between the first and last letters of those words. These letters are then scrambled and the whole character string reassembled.

# Answer
> 1 votes
## APL, ~~58~~ 49

I believe this works in IBM APL2 (I don't have IBM APL)

```
({⍵[⌽∪t,⌽∪1,?⍨t←⍴⍵]}¨x⊂⍨~b),.,x⊂⍨b←' ,.'∊⍨x←⍞,' '

```

---

If not, then in Dyalog APL, add to the front:

```
 ⎕ML←3⋄

```

which adds 6 chars

---

This assumes the only non-word characters are space, comma, and period.

# Answer
> 1 votes
## VBA, 351 373/409

```
Sub v(g)
m=1:Z=Split(g," "):j=UBound(Z)
For u=0 To j
t=Z(u):w=Len(t):l=Right(t,1):If Not l Like"[A-Za-z]" Then w=w-1:t=Left(t,w):e=l Else e=""
If w>3 Then
n=Left(t,1):p=w-1:s=Right(t,p):f=Right(t,1)
For p=1 To p-1
q=w-p:r=Int((q-1)*Rnd())+1:n=n & Mid(s,r,1):s=Left(s,r-1) & Right(s,q-r)
Next
Else
n=t:f=""
End If
d=d & n & f & e & " "
Next
g=d
End Sub

```

Alternate (larger) Method:

```
Sub v(g)
m=1:Z=Split(g," "):j=UBound(Z)
For u=0 To j
t=Split(StrConv(Z(u),64),Chr(0)):w=UBound(t)-1:l=Asc(t(w)):If l<64 Or (l>90 And l<97) Or l>122 Then e=t(w):w=w-1 Else e=""
If w>3 Then
n=t(0):p=w-1:s=""
For i=-p To -1
s=t(-i) & s
Next
f=t(w)
For p=1 To p-1
r=Int((w-p)*Rnd())+1:n=n & Mid(s,r,1):s=Left(s,r-1) & Right(s,w-p-r)
Next
n=n & s
Else
n=Z(u):f="":e=""
End If
d=d & n & f & e & " "
Next
g=d
End Sub

```

Both of these methods change the value of the variable passed to the `Sub`. i.e.

```
Sub Test()
strTestString = "This is a test."
v strTestString
Debug.Print strTestString
End Sub

```

will output something like this:

```
"Tihs is a tset."

```

Also, this does randomize mid-word punctuation, so this may not fit the spec 100%.

# Answer
> 1 votes
# APL NARS 172 chars

```
r←g x;i;s;d;k
s←⎕AV[98..123]∪⎕A
i←1⋄v←''⋄r←''⋄k←⍴x
A:d←''⋄→C×⍳i>k⋄d←x[i]⋄→C×⍳∼d∊s⋄v←v,d⋄i+←1⋄→A
C:v←{t←¯2+⍴r←⍵⋄t≤1:r⋄r[1+t?t]←⍵[1+⍳t]⋄r}v
r←∊r,v,d
v←''⋄i+←1⋄→A×⍳i≤k
g x←⍞

```

13+17+18+44+41+8+17+5+9=172; This function g() has input as a string; has output as a string. I add the input command because i don't know how insert \\' in a quoted string. Commented

```
∇r←g x;i;s;d;k
   ⍝ words are element of  a-zA-Z separed from all other
   s←⎕AV[98..123]∪⎕A ⍝a-zA-Z ascii ⎕IO = 1
   i←1⋄v←''⋄r←''⋄k←⍴x
A:   d←''⋄→C×⍳i>k⋄d←x[i]⋄→C×⍳∼d∊s⋄v←v,d⋄i+←1⋄→A
C:      v←{t←¯2+⍴r←⍵⋄t≤1:r⋄r[1+t?t]←⍵[1+⍳t]⋄r}v
        r←∊r,v,d
        v←''⋄i+←1⋄→A×⍳i≤k
∇

```

result

```
g x←⍞
According to a researcher at Cambridge University, it doesn't matter in what order the letters in a word are, the only important thing is that the first and last letter be at the right place. The rest can be a total mess and you can still read it without problem. This is because the human mind does not read every letter by itself but the word as a whole.
  Androiccg to a rhraeecser at Cgirbdmae Uirevtsiny, it deson't mtetar in waht oderr the ltrtees in a wrod are, the olny intro
  apmt tinhg is taht the frsit and lsat lteter be at the rghit pacle. The rset can be a ttaol mses and you can siltl rae
  d it wtuhoit poeblrm. Tihs is bcsauee the hmaun mnid deos not raed eervy lteter by isletf but the wrod as a wolhe.

```

# Answer
> 1 votes
# PHP 7.1, not competing, 80 bytes

```
for(;$w=$argv[++$i];)echo$w[3]?$w[0].str_shuffle(substr($w,1,-1)).$w[-1]:$w," ";

```

takes input from command line arguments. Run with `-nr`. (will obviously fail at punctuation)

# Answer
> 1 votes
# PHP, 94+1 bytes

+1 for `-R` flag

```
<?=preg_replace_callback("/(?<=\w)\w+(?=\w)/",function($m){return str_shuffle($m[0]);},$argn);

```

Pipe input through `php -nR '<code>'`.

Note: `preg_replace_callback` came to PHP in 4.0.5; closures were introduced in php 5.3;
so this requires PHP 5.3 or later.

Unfortunately, the match is always sent as an array, even if there are no sub patterns,
thus I cannot just use `str_shuffle` as the callback, which would save 29 bytes.

# Answer
> 1 votes
# JavaScript, ~~76~~ 67 bytes

thanks to Arnauld for -9 bytes.

```
t=>t.replace(/\B\w+\B/g,m=>[...m].sort(_=>Math.random()-.5).join``)

```

Try it online!

---

## Ungolfed

```
t =>                  // function with a single argument
     t.replace(       // Replace ...
         /\B\w+\B/g,  // every match of the regex
         m => ...     // with the return value of the replacement function
     )

/       /g            // Match all occurences of
   \w+                // 1 or more word chars ...
 \B   \B              // ... that aren't on the beginning or end of the word

m =>                  // Replacement function
     [...m]           // convert matched string to a list of chars
       .sort(_ => Math.random()-.5) // sort with a random comparision function
       .join``        // join the list into a single string

```

# Answer
> 1 votes
# Jelly, ~~22~~ 20 bytes

```
e€ØẠ+ƝỊŻœṗµḢ,ṪjW)ẎẊ€

```

Try it online!

This was fun to make.

Each non-alphabet character is grouped into a single character string, and the first and last characters of each word are grouped the same way as well. That way, taking a random permutation of those characters will not change their order.

Made with a lot of help from caird coinheringaahing.

-2 bytes from caird coinheringaahing.

## Explanation

```
e€ØẠ+2\ỊŻœṗ⁸µḢ,ṪjW)ẎẊ€
 €                     for each character:
e ØẠ                   check if it's in the alphabet
    +2\                add overlapping pairs
       Ị               check if they are ≤ 1
        œṗ⁸            and partition the input using that bitmask
           µ      )    execute the following on each part:
            Ḣ,ṪjW      get head, tail, and join with the modified list
                   Ẏ   join the list of triplets together
                    Ẋ€ get a random permutation of each of the elements

```

# Answer
> 1 votes
# Stax, ~~15 14~~ 13 bytes

```
â#]ø\┘‼↕ip2╚_

```

Run and debug it

Regex is busted.

-2 bytes from recursive.

# Answer
> 1 votes
# Python 3, 113 bytes

*based on the original python answer by daniero*

```
import re,random
print(re.sub('(\w)(\w+)(\w)',lambda m:m[1]+''.join(random.sample(m[2],len(m[2])))+m[3],input()))

```

Try it online!

# Answer
> 1 votes
# , 159 bytes

```
function(x){l=attr(w<-el(gregexpr("[a-zA-Z]+",x)),"m")
Map(function(i,j)substr(x,i,j)<<-Reduce(paste0,sample(substring(x,r<-i:j,r))),s<-w[l>3]+1,s+l[l>3]-3)
x}

```

Try it online!

Posted before realizing that there was already another  answer, but pleasingly the two approaches are quite different...

**Ungolfed code:**

```
cambridge_transpose=
function(x){                        # x is the input string,
  w=el(gregexpr("[a-zA-Z]+",x))     # w gets the words in x using a regex,
  l=attr(w,"match.length")          # l gets the lengths of each word,
  s=w[l>3]+1                        # s is the start letter to jumble in each word,
  e=s+l[l>3]-3                      # e is the end letter to jumble in each word.
  Map(function(i,j) ... ,s,e)       # Now, use this function on all elements i,j from s,e:
    substr(x,i,j)<<-                #   replace letters in x from i to j
      Reduce(paste0,                #   with these letters joined-together:
        sample(                     #     a random sample of
          substring(x,r<-i:j,r)))   #     the letters in x from i to j.
x}                                  # Finally, return (modified) x.

```

# Answer
> 1 votes
# Python3, 110 bytes:

```
lambda x:re.sub('(?<=\w)\w{3,}(?=\w)',lambda x:''.join(r.sample(g:=x.group(),len(g))),x)
import re,random as r

```

Try it online!

# Answer
> 0 votes
## R, 179

Using the function I wrote for the randomize letters in a word problem:

Input:

```
s <- "According to a researcher at Cambridge University, it doesn't matter in what order the letters in a word are, the only important thing is that the first and last letter be at the right place. The rest can be a total mess and you can still read it without problem. This is because the human mind does not read every letter by itself but the word as a whole."

```

Solution:

```
f=function(w){l=length;s=strsplit(w,"")[[1]];ifelse(l(s)<3,w,paste(c(s[1],sample(s[2:(l(s)-1)]),s[l(s)]),collapse=""))}
g=Vectorize(f)
paste(g(strsplit(s," ")[[1]]), collapse=" ")

```

Result:

```
[1] "Arioccdng to a reehaecrsr at Cabrgimde Uveirisnyt, it des'not mttear in waht odrer the lttrees in a wrod are, the olny inpotmart thnig is that the fsrit and lsat letetr be at the right palce. The rset can be a toatl mses and you can stlil raed it wutioht pmrlebo. This is bsuceae the hmuan mnid deos not read ervey lteetr by iesltf but the word as a wleho."

```

# Answer
> 0 votes
# Pyth, 23 bytes

```
jdm?gld4++hd.<Ptd1eddcz

```

Non-competing because Pyth was made after this challenge was posted.

Try it online

# Answer
> 0 votes
# Japt, 32 bytes

```
m@Xl ¨4?Xg0 +Xs1J ö(x) +XgJ:X}"

```

Try it online!

# Answer
> 0 votes
**Java, ~~1557~~ 834 bytes** Thanks to @JoKing for tips.

A bit late to the competition. Forgot that I had started on this problem.

**Golfed**

```
import java.util.*;public class s{ public static void main(String[] args){ Scanner s=new Scanner(System.in);String a=s.next();String[] q=a.split("\\s+");for (int i=0;i<q.length;i++) { q[i]=q[i].replaceAll("[^\\w]", ""); }String f="";for (String z:q) { f+=scramble(z);f+=" "; }System.out.print(f); }private static String scramble(String w){if(w.length()==1||w.length()==2){return w;}char[]l=w.toCharArray();char q=l[w.length()-1];String e=Character.toString(l[0]);char[]n=new char[l.length-2];for(int i=0;i<l.length-2;i++){n[i]=l[i+1];}HashMap<Integer,Character>s=new HashMap<>();int c=1;for(char p:n){s.put(c,p);c++;}HashMap<Integer,Integer>o=new HashMap<>();Random z=new Random();for(int i=0;i<w.length()-2;i++){int m=z.nextInt(n.length);while(o.getOrDefault(m,0) == 1){m=z.nextInt(n.length);}e+=s.get(m+1);o.put(m,1);}return e+=q;}}

```

**Non-golfed**

```
import java.util.HashMap;
import java.util.Random;

public class SentenceTransposition {
    public static void main(String[] args) {
        String input = "According to a researcher at Cambridge University, it doesn't matter in what order the letters in a word are, the only important thing is that the first and last letter be at the right place. The rest can be a total mess and you can still read it without problem. This is because the human mind does not read every letter by itself but the word as a whole.";
        String[] words = input.split("\\s+");
        for (int i = 0; i < words.length; i++) {
            words[i] = words[i].replaceAll("[^\\w]", "");
        }
        String finalsentence = "";
        for (String word : words) {
            finalsentence += scramble(word);
            finalsentence += " ";
        }
        System.out.println(finalsentence);
    }

    private static String scramble(String word) {
        if (word.length() == 1 || word.length() == 2) {
            return word;
        }
        char[] letters = word.toCharArray();
        char lletter = letters[word.length()-1];
        String endword = Character.toString(letters[0]);
        char[] nletters = new char[letters.length-2];
        for (int i = 0; i < letters.length-2; i++) {
            nletters[i] = letters[i+1];
        }
        HashMap<Integer, Character> set = new HashMap<>();
        int count = 1;
        for (char nletter : nletters) {
            set.put(count, nletter);
            count++;
        }
        HashMap<Integer, Integer> chosen = new HashMap<>();
        Random random = new Random();
        for (int i = 0; i < word.length()-2; i++) {
            int cur = random.nextInt(nletters.length);
            while (chosen.getOrDefault(cur,0) == 1) {
                cur = random.nextInt(nletters.length);
            }
            endword += set.get(cur+1);
            chosen.put(cur, 1);
        }
        return endword += lletter;
    }
}

```

# Answer
> 0 votes
# Sidef, ~~89~~ 85 bytes

Block (anonymous callable):

```
{.words.map{[_[0],(_.len-1?([_[1..^(_.len-1)]].shuffle...,_[1]):'')].join}.join(' ')}

```

Output, when used like `{ ... }('..')`:

```
 I hvae nveer not ocne in my life slleepd nhedatarnel crtreolcy
 I have never not once in my lfie sepelld naetadenrhl ccrtloery

```

Somewhat ungolfed

```
.words.map{
  [
    .first,
    (_.len-1
      ? (  [ _[1..^(_.len-1)] ].shuffle..., .last )
      : '')
  ].join
}.join(' ')

```

# Answer
> 0 votes
# Perl 5 `-p`, 74 bytes

```
s|\pL\K\pL{2,}(?=\pL)|$,=$q=$&;$q=join'',shuffle$,=~/./g while$,eq$q;$q|ge

```

Try it online!

# Answer
> 0 votes
# Raku, 49 bytes

Moved from the duplicate thread.

```
{S:g/(\w)(\w*)(\w)/{$0~$1.comb.pick(*).join~$2}/}

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 19 bytes

```
.γa}εDaićsD¨.rsθJ]J

```

Try it online.

**Explanation:**

```
.γ              # Consecutive group by:
  a             #  Is alphabetic (so all upper- and lowercase letters)
 }ε             # After the group-by, map each string to:
   D            #  Duplicate the current string
    ai          #  If it's alphabetic:
      ć         #   Extract head; pop and push the remainder-string and first character
                #   separated to the stack
                #    i.e. "According" → STACK: "ccording","A"
       s        #   Swap so remainder-string is at the top again
                #    STACK: "A","ccording"
        D       #   Duplicate it
                #    STACK: "A","ccording","ccording"
         ¨      #   Remove the last character from the copy
                #    STACK: "A","ccording","ccordin"
          .r    #   Shuffle the remaining characters
                #    STACK: "A","ccording","occdrni"
            s   #   Swap so the remainder-string is at the top again
                #    STACK: "A","occdrni","ccording"
             θ  #   Only leave its last character
                #    STACK: "A","occdrni","g"
              J #   Join the three back together to a string again
                #    STACK: "Aoccdrnig"
  ]             # Close both the if-statement and map
   J            # And join all strings in the list back together
                # (after which the result is output implicitly)

```

# Answer
> 0 votes
# Go, ~~248~~ 226 bytes

```
import(."math/rand";."regexp")
func f(s string)string{return MustCompile(`(\w)(\w+)(\w)`).ReplaceAllStringFunc(s,func(S string)(e string){k:=S[1:len(S)-1]
for _,i:=range Perm(len(k)){e+=k[i:i+1]}
return S[:1]+e+S[len(S)-1:]})}

```

Attempt This Online!

Embeds my answer for "How to randomize letters in a word" within this answer.

* -22 from `rand.Perm`, string slices, and named return.

# Answer
> 0 votes
# Japt, 13 bytes

```
r"%B%w+%B"Èö¬

```

Try it

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


# Question
Title: Maximum of outer product of integer vectors (in linear time)
## Introduction

Our goal is to efficiently find the maximum of a large amount of (redundant) data.

We define the outer product of vectors \\$A\\$ and \\$B\\$ as a matrix containing the products of all entries of \\$A\\$ with each entry of \\$B\\$. (see outer Product)

$$ A\otimes B := A\cdot B^T = \left(\begin{array}{rrr} A(1)\cdot B(1) & A(1)\cdot B(2) & \ldots & A(1)\cdot B(M)\\ A(2)\cdot B(1) & A(2)\cdot B(2) & \ldots & A(2)\cdot B(M)\\ \ldots & & & \ldots \\ A(N)\cdot B(1) & A(N)\cdot B(2) & \ldots & A(N)\cdot B(M)\\ \end{array}\right) $$

Here \\$A\\$ has \\$N\\$ entries (size \\$N\\$) and \\$B\\$ has \\$M\\$ entries.

In this way, the outer product of \\$K\\$ vectors yields a \\$K\\$-dimensional array (tensor of order \\$K\\$). If \\$N\_1,N\_2,\ldots,N\_K\\$ are the sizes of the vectors, we get a total of \\$N\_1\cdot N\_2\cdot\ldots\cdot N\_K\\$ products.

Example: $$ \left(\begin{array}{r}1\\ 2\\ 0\end{array}\right)\otimes \left(\begin{array}{r}1\\ 3\end{array}\right)\otimes \left(\begin{array}{r}-5\\ 7\end{array}\right)= \left(\begin{array}{rr|rr|rr}-5 & 7 & -10 & 14 & 0 & 0\\ -15 & 21 & -30 & 42 & 0 & 0\end{array}\right) $$

The result is a \\$3\\$-dimensional array consisting of three \\$2\times2\\$ slices. We want to determine the maximum of the array, which is \\$42\\$ here.
An alternative formulation is: Find the maximum of all products that contain exactly one number from each vector.

Of course, we can do all the multiplications and keep track of the maximum. However, it is possible to use only a number of operations that depends linearly on the length of the input sequence (total number of vector entries). This means that we can, for example, process an input of \\$13\\$ vectors each of size \\$37\\$ in less than one second on a common computer.
Thus, the problem reads:

## Challenge

* "Determine the maximum of the outer product of given integer-valued vectors. Ensure that the algorithm runs in linear time with respect to the length of the input sequence."
* The input contains at least one vector.
* This is , so shortest answer in bytes wins!

## Test cases

We leave the input format to the free decision. In the test cases we use \\$,\\$ to separate vector entries and \\$;\\$ to separate vectors. So the example above is coded as: \\$\quad 1,2,0;1,3;-5,7\\$

* \\$0,1,2\qquad -\>\qquad 2\\$
* \\$-2,-1,-2;1,2,3;-1,-2\qquad -\>\qquad 12\\$
* \\$-2,-1;-3,-4;-3,2,1;1,4,-4\qquad -\>\qquad 96\\$
* \\$-1,-2;3,4\qquad -\>\qquad -3\\$
* \\$-1,-2;1,-3,2;1,-1,-2\qquad -\>\qquad 8\\$
* \\$1,0,-2;0,-2,1;-2,1,0;-2,0,1;0,1,-2;1,-2,0;1,0,-2;0,-2,1;-2,1,0;-2,0,1;0,1,-2;1,-2,0;1,0,-2;0,-2,1;-2,1,0;-2,0,1;0,1,-2;1,-2,0;1,0,-2;0,-2,1;-2,1,0;-2,0,1;0,1,-2;1,-2,0;1,0,-2;0,-2,1;-2,1,0;-2,0,1;0,1,-2;1,-2,0;1,-2,0;1,0,1\qquad -\>\qquad 1073741824\\$

# Answer
> 9 votes
# JavaScript (Node.js), 84 bytes

```
f=([a,...x],m=1,n=1)=>a?f(x,Math.min(...q=a.flatMap(c=>[c*m,c*n])),Math.max(...q)):n

```

Try it online!

Keep trace of min and max

# Answer
> 6 votes
# Jelly, ~~12~~ 10 bytes

```
Ṃ,ṀƊ×þFɗ/Ṁ

```

Try it online!

*-2 from using Ɗ and ɗ for grouping instead of separate lines*

This submission is a monadic link. For input, use a list of the vectors (i.e. `[[1,2,0],[1,3],[-5,7]]`) as the first argument. This assumes `[]` is not valid input.

This is similar to @l4m2's algorithm, but it starts with the first vector instead of `(1, 1)`.

Explanation:

This works by taking the (min, max) of the first vector and finding all products of either with elements of the second vector. The same thing happens with the result and the third vector, then that result and the fourth, etc. Then, the answer is the max of the last result.

```
Ṃ,ṀƊ×þFɗ/Ṁ
Ṃ          # List Minimum
 ,         # Pair
  Ṁ        # List Maximum
   Ɗ       # Group the last 3 links ("Ṃ", ",", and "Ṁ") as a monad
    ×þ     # Outer product
      F    # Flatten
       ɗ   # Group the last 3 links ("Ṃ,ṀƊ", "×þ", and "F") as a dyad
        /  # Reduce
         Ṁ # List Maximum

```

This is my first time using Jelly, so there is probably still room for further golfing.

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

```
Max@*Fold[{#2Min@#,#2Max@#}&]

```

Try it online!

# Answer
> 3 votes
# Python 3.8 (pre-release), 85 bytes

Port of @l4m2's JavaScript answer

```
f=lambda x,y=1,z=1:x and f(x[1:],min(q:=sum(([c*y,c*z]for c in x[0]),[])),max(q))or z

```

Try it online!

# Answer
> 3 votes
# 05AB1E, ~~11~~ 10 bytes

```
1$vsß‚yδ*Z

```

Port of *@EvanBailey*'s Jelly answer, which in turn uses the same approach as *@l4m2*'s Javascript answer, so make sure to upvote both of them as well!

Input as a list of lists.

Try it online or verify all test cases (with brute-force verify `.»â€˜Pà` in the footer for the smaller test cases).

**Explanation:**

```
1           # Push 1
 $          # Push another 1, and the input-list
  v         # Pop the input-list, and loop over each inner list `y`:
   s        #  Swap so the current list is at the top
            #  (or simply swap the two 1s on the stack in the very first iteration)
    ß       #  Pop and push the minimum (1 remains 1)
     ‚      #  Pair the top two values together
            #  ([1,1] in the first iteration; [max,min] in every other iteration)
       δ    #  Apply double-vectorized
      y     #  on this pair and list `y`:
        *   #   Multiply
         Z  #  Push the flattened maximum (without popping the list of lists)
            # (after the loop, the final flattened maximum that's on top of the stack is
            # output implicitly as result)

```

It runs in \\$O(\sum L)\\$, where \\$L\\$ is the length of each individual list.

In term of iterations, it'll do \\$\sum(6L)-2L\_n\\$, where \\$6\\$ comes from \\$2\\$ (for \\$\[min,max\]\\$) times \\$3\\$ (once for the double-vectorized to create the list; and then once each to retrieve the flattened maximum and minimum of this list of lists); minus \\$2\\$ times the length of the last list \\$L\_n\\$, since we won't retrieve its minimum. E.g. input `[[1,2,0],[1,3],[-5,7]]` has \\$6\times3+6\times2+6\times2-2\times2=38\\$ iterations and an input of \\$13\\$ lists of size \\$37\\$ each has \\$13\times6\times37-2\times37=2812\\$ iterations.

# Answer
> 2 votes
# Charcoal, 19 bytes

```
⊞υ¹ＦＡ≔⁺×ι⌊υ×ι⌈υυＩ⌈υ

```

Try it online! Link is to verbose version of code. Explanation: Another port of @l4m2's algorithm.

```
⊞υ¹

```

Start with a minimum and maximum of `1`.

```
ＦＡ

```

Loop over the input vectors.

```
≔⁺×ι⌊υ×ι⌈υυ

```

Multiply the current vector by both the minimum and maximum so far.

```
Ｉ⌈υ

```

Output the final maximum.

# Answer
> 2 votes
# Haskell, 80 bytes

```
r a=[minimum a,maximum a]
f=last.foldl1(\a b->r$map product$sequence[a,b]).map r

```

Try it online!

# Answer
> 2 votes
# Haskell, 50 bytes

```
m.foldl1(\x->((*)<$>[minimum x,m x]<*>))
m=maximum

```

Attempt This Online!

-2 bytes thanks to @ Unrelated String.

A port of my Mathematica answer.

# Answer
> 2 votes
# Vyxal ~~14~~ 11 bytes

```
?ƒλ₍gGẊvΠ;G

```

Try it online!

Any improves welcome! For input needs always list of vectors,
so first test case should be \[\[0,1,2\]\]

## Explanation

```
?      # Get input
ƒ      # Begin reduce list of vectors by lambda
λ      # Open lambda
₍gG    # [min, max] of current vector
Ẋ      # Cartesian product with previous vector
vΠ     # Vectorised product
;G     # Close lambda and print total max

```

# Answer
> 1 votes
# , 42 bytes

```
function(L)max(Reduce(`%o%`,Map(range,L)))

```

Try it online!

Using `outer` instead of `'%o%'` is equivalent. Fortunately, `range` returns a vector of `c(min,max)` instead of `max - min` as you might otherwise expect. Based, as many others, on l4m2's answer

Also, random note, `range` automatically flattens `list`s.

---
Tags: code-golf, math, restricted-complexity, algorithm
---


title: Where's my value?

text:
# Question
Title: Where's my value?
My boss now wants me to implement a mechanism that lets him search for an item in an array, and gives him the index/indices where that value occurs.

## Your Task:

Write a program or function that receives an array and a value (String, Integer, Float, or Boolean), and returns the indices of the array at which the value occurs (either 0 or 1 indexed, whichever you prefer). If the value is not in the array return an empty array.

## Input:

An array A and a value V, that may or may not be present in A.

## Output:

An array containing the indice(s) at which the V occurs in A, or, if V does not occur in A, an empty array.

## Test Cases:

Please note that the test cases are 0 based.

```
12, [12,14,14,2,"Hello World!",3,12,12]         -> [0,6,7]
"Hello World", ["Hi", "Hi World!", 12,2,3,True] -> []
"a", ["A",True,False,"aa","a"]                  -> [4]
12, [12,"12",12]                                -> [0,2]

```

## Scoring:

This is , so the lowest score in bytes wins.

# Answer
# Pyth, 2 bytes

0-indexed.

```
xE

```

**Try it online!** or **Check all the Test Cases**

---

# Explanation

```
xEQ  - Full Program. Takes Input from standard input. Q means evaluated input and is implicit at the end of the program.

x   - Get all the indexes of x in y
 E  - Evaluated Input #2 - The value
  Q - The list - Evaluated Input #1

```
> 10 votes

# Answer
# Python 3, 45 bytes

*-3 bytes thanks to @EriktheOutgolfer and @Chris\_Rands*

```
lambda y,x:[i for i,j in enumerate(x)if j==y]

```

**Test Suite.**

Today I learned `enumerate(x) == zip(range(len(x)),x)`.

---

# Python 3, 47 bytes

```
lambda n,l:[x for x in range(len(l))if l[x]==n]

```

**Try it online!** or **Check all the Test Cases**
> 7 votes

# Answer
# JavaScript, 39 bytes

```
e=>a=>[...a.keys()].filter(i=>a[i]===e)

```

```
f=
e=>a=>[...a.keys()].filter(i=>a[i]===e)

console.log(f(12)([12,14,14,2,"Hello World!",3,12,12]));
console.log(f("Hello World")(["Hi", "Hi World!", 12,2,3,true]));
console.log(f("a")(["A",true,false,"aa","a"]));
console.log(f(12)([12,14,14,2,"Hello World!",3,12,'12']));
```

The above snippet might not work on all browsers, so here's a TIO link.
> 7 votes

# Answer
# MATL, 2 bytes

```
mf

```

The `m` consumes two arguments, and checks each element in the array whether is equal to the other argument, `f` returns the indices of the truthy entries of an array.

Try it online!
> 7 votes

# Answer
# JavaScript (ES6), ~~44~~ 43 bytes

*Crossed out 44 is still regular 44 ;(*

```
v=>a=>a.map((x,i)=>x===v&&++i).filter(x=>x)

```

*Saved 1 bytes thanks to* @Arnauld

```
let f=
v=>a=>a.map((x,i)=>x===v&&++i).filter(x=>x)
;

console.log(f(12)([12,14,14,2,"Hello World!",3,12,12]));         // => [1,7,8]
console.log(f("Hello World")(["Hi", "Hi World!", 12,2,3,true])); // => []
console.log(f("a")(["A",true,false,"aa","a"]));                  // => [5]
```
> 6 votes

# Answer
# R (+pryr), 20 bytes

```
pryr::f(which(a==b))

```

Which evaluates to the function

```
function (a, b)
which(a == b)

```

Where either `a` can be the value to look for and `b` the vector, or the other way around. When presented with two vectors of unequal lengths (a single value counts as a length-1 vector in R), R will wrap the shorter one to match the length of the longer one. Then the equality is checked. This generates a logical vector. `which` provides the indices where this vector is true.

Try it online!
> 6 votes

# Answer
# Jelly, 3 bytes

```
⁼€T

```

Try it online!

-1 thanks to Mr. Xcoder. (dyadic chains)
> 5 votes

# Answer
# C#, ~~88~~ 72 bytes

```
using System.Linq;a=>o=>a.Select((i,n)=>o.Equals(i)?n:-1).Where(n=>n>=0)

```

*Saved 16 bytes thanks to @LiefdeWen.*

Try it online!
> 5 votes

# Answer
# 05AB1E, 4 bytes

```
QāsÏ

```

Try it online!

1-indexed.
> 5 votes

# Answer
# Ruby, ~~46 40~~ 39 bytes

```
->e,a{i=-1;a.map{|x|i+=1;x==e&&i}-[!1]}

```

Saved 7 bytes!!! thanks to Eric Duminil.

Try it online.
> 3 votes

# Answer
# Haskell, ~~41~~ 39 bytes

```
v!l=fst<$>(filter((==v).snd)$zip[1..]l)

```

Try it online!

*Saved two bytes thanks to @flawr*

Haskell is statically typed, so I had to use a little workaround to run the test cases.
> 3 votes

# Answer
# Husk, 5 bytes

```
`fNm=

```

Try it online! 1-indexed.

### Explanation

```
       -- implicitly input a value v and a list L
   m=  -- map "equals v" over the list L, resulting in a list of truthy and falsy values
`fN    -- filter the natural numbers N by discarding the numbers at falsy positions
          and keeping the ones at truthy positions

```
> 3 votes

# Answer
# APL (Dyalog Unicode), 2 bytesSBCS

Takes item to look for as left argument (must be scalar to find an *item* of the lookup array rather than a subarray) and the lookup array (which may have up to 15 dimensions) as right argument. Returns list of indices, each of which may has as many elements as the number of dimensions in the lookup array.

```
⍸⍷

```

Try it online!

**ɩ**ndices where

found
> 3 votes

# Answer
# Ruby, 38 bytes

```
->e,a{a.each_index.select{|x|a[x]==e}}

```

Try it online!
> 3 votes

# Answer
# Google Sheets, 101 bytes

```
=IfError(Join(",",Filter(Column(Offset(A1,0,0,1,Counta(Split(B1,",")))),Exact(Split(B1,","),A1))),"")

```

Value `V` in `A1` and array `A` in `B1` with each entry separated by a comma. Null entires are not allowed (row 5 below shows what happens).

Explanation:

`Offset(A1,0,0,1,Counta(Split(B1,",")))` returns a range that is one row tall and as many columns wide as there are entries in `A1`.

`=IfError(Join(",",Filter(Column(~),Exact(Split(B1,","),A1))),"")` filters the column numbers of that range based on whether or not the value in `A1` is exactly each of the values in `B1` and concatenates them all in a comma-delineated list.
> 3 votes

# Answer
# Clojure, 40 bytes

First attempt at code golf.

`keep-indexed` maps a function over a collection here, passing the current index into the callback and yielding any non-nil return values.

```
(fn[a b](keep-indexed #(if(= %2 a)%1)b))

```

Try it online!
> 3 votes

# Answer
## Batch, 86 bytes

```
@set i=0
:g
@if "%~2"=="" exit/b
@if %1==%2 echo %i%
@set/ai+=1
@shift/2
@goto g

```

Takes input as command line parameters (value then the array elements as separate parameters). Note: String quoting is considered part of the match e.g. `"1"` won't equal `1` (would cost 6 bytes).
> 2 votes

# Answer
# Python 2, 49 bytes

```
lambda l,v:filter(lambda i:l[i]==v,range(len(l)))

```

Try it online!

Not short enough, but I thought it was cool. ¯\\\_(ツ)\_/¯
> 2 votes

# Answer
# Perl 5, 28 bytes

```
sub{grep$_[$_]eq$_[0],1..@_}

```

Try it online!

The output is 1-indexed.
An anonymous function is quite unusual for Perl, but it happens to be the shortest I could think of. `grep ..., 1 .. @_` iterates over the indexes of the input array (actually it goes one cell beyond the last, but it doesn't matter), keeping only the index that satisfy `$_[$_]eq$_[0]`, ie. the ones where the value of the element (`$_[$_]`) is the same as the value we need to keep (`$_[0]`).

---

Slightly longer (31 bytes (30 + `-l` flag)), but as a full program:

```
$@=<>;$@eq$_&&print$.-1while<>

```

Try it online!
> 2 votes

# Answer
# Haskell, ~~37~~ 33 bytes

```
import Data.List
findIndices.(==)

```

Thanks @Laikoni for -4 bytes!

Try it online!
> 2 votes

# Answer
# Java 8, ~~146~~ ~~113~~ ~~112~~ ~~111~~ ~~110~~ 108 bytes

```
import java.util.*;l->o->{List r=new Stack();for(int i;(i=l.indexOf(o))>-1;l.set(i,null))r.add(i);return r;}

```

-2 bytes thanks to *@TAsk* by using `Vector` instead of `ArrayList`.
-1 byte by using `Stack` instead of `Vector`.
-2 bytes thanks to *@Jakob* by inputting a `ArrayList` instead of an array.

0-indexed

**Explanation:**

Try it here.

```
import java.util.*;    // Required import for Vector and Vector
l->o->{                // Method with List and Object parameters
  List r=new Stack();  //  Result-list
  for(int i;(i=l.indexOf(o))>=-1;
                       //  Loop as long as we can find the object in the list
    l.set(i,null))     //   After every iteration, remove the found item from the list
      r.add(i);        //    Add the index to the result-list
                       //  End of loop (implicit / single-line body)
  return r;            //  Return the result-List
}                      // End of method

```
> 2 votes

# Answer
# 05AB1E, 4 bytes

```
Qƶ0K

```

Try it online!

**It is 1-indexed, as shown below:**

```
IN A-#------------------------> [2,3,3,3,4]
IN B-#------------------------> 3
-----#------------------------+-----------------
Q    # Vectorized equivalence | [0,1,1,1,0]
 ƶ   # Lift by index          | [0,2,3,4,0]
  0K # Remove zeros           | [2,3,4]

```
> 1 votes

# Answer
# Mathematica, 12 bytes

```
Position@##&

```

1-Indexed

**input** \[Array,Value\]

> \[{12, 14, 14, 2, "Hello World!", 3, 12, 12}, 12\]

**output**

> {{1}, {7}, {8}}
> 1 votes

# Answer
## Haskell, 29 bytes

```
e#l=[i|(i,h)<-zip[0..]l,h==e]

```

Try it online!
> 1 votes

# Answer
# Japt, 9 bytes

```
mÈ¶V©YÄÃf

```

1-indexed.

Japt input doesn't support booleans, so they have been replaced with `0` and `1` in the test cases.

Try it online! with the `-Q` flag to format the array output.

## 0-indexed Solution, 11 bytes

```
l o f@gX ¶V

```

Try it online!
> 1 votes

# Answer
# Perl 6, 21 bytes

```
{grep :k,*===$^v,@^z}

```

Try it online!

The `:k` adverb to `grep` tells it to return the matching keys (indices) of the input sequence that match the predicate `* === $^v`.

If strings and numbers were considered equivalent, one could use a grep predicate of just `$^v` instead of `* === $^v`.
> 1 votes

# Answer
## C ~~340~~ ~~362~~ ~~166~~ 115 Bytes

Hello all. My first time here. I figured since I enjoy (attempting) to write optimized code I may as well give this a try.

@Rodney - ~39 bytes from the includes

@Zacharý - 7 bytes with implicit typing

**0-indexed**.

**How to Run:**

As per @Arnolds suggestion, the program takes arguments in a much more C friendly manner. This let me reduce the size of the file by a little more than half.

The arguments should be passed in the following order `value [element1 ...]` where braces indicate optional arguments

You may or may not have to add escaped quotes to any strings that are provided in order to satisfy the condition of `12 != "12"`. On my system the this can be done in the following manner

```
prog-name.exe 12 3 "Hello" 12 4 "12"
Returns [2,4]     < This is incorrect

prog-name.exe 12 3 "\"Hello\"" 12 4 "\"12\""
Returns [2]       < Correct

```

---

golfed

```
#define P printf(
b=0;main(int c,char**v){P"[");for(--c;c-1;c--)b|=strcmp(v[1],v[c])?0:P b?",%i":"%i",c-2);P"]");}

```

ungolfed

```
#define P printf(

//Implicit only works in global(I totally knew this after almost 4 years of C :P)
b = 0;
main(int c,char**v)
{

    P"[");

    //match loop
    //b is used to determine if this is the first iteration. it can be assumed that printf will always return >0
    //subract two from c to get correct index number of match
    for(--c; c-1; c--)
        b |= strcmp(v[1], v[c]) ? 0 : P b ? ",%i" : "%i", c-2);

    P"]");

    return 0;
}

```
> 1 votes

# Answer
# Common Lisp, 66 bytes

```
(lambda(x s)(loop as i in s as j from 0 when(equal i x)collect j))

```

Try it online!
> 1 votes

# Answer
## TXR Lisp, 26 bytes

```
(op where(op equal @@1)@2)

```

In other words, "Where is argument 2 equal to argument 1?"

Run:

```
1> (op where(op equal @@1) @2)
#<interpreted fun: lambda (#:arg-01-0166 #:arg-02-0167 . #:rest-0165)>
2> [*1 12 #(12 14 14 2 "Hello world!" 3 12 12)]
(0 6 7)
3> [*1 "Hello World" #("Hi" "Hi world!" 12 2 3 t)]
nil

```
> 1 votes

# Answer
## Clojure, ~~39~~ 38 bytes

```
#(filter(comp #{%2}%)(range(count %)))

```

A bit obscure :) The first input argument is a `vec` of values and the second one is the searched value. `%` maps indexes to values, and the set `#{%2}` returns truthy (the input argument `%2`) or falsy `nil` for that value. comp composes these together.
> 1 votes

# Answer
# MY, 5 bytes

```
⎕⎕=⍸↵

```

Try it online!

## How?

* evaluated line of input
* evaluated line of input
* `=` element-wise equality
* indexes of truthy elements
* output with new line

MY is capable of something again! Order of the inputs does not matter. Indexing is 1-based by default.
> 1 votes

# Answer
# , 6 bytes

```
I.@:=

```

Assumes inputs are of the same type.

I do not know J very well. This took *way* too long.

`=` is (vectorized) equality. `I.` returns the indices of 1s in an array. `@:` is verb composition.

Try it online!
> 1 votes

# Answer
# Japt, ~~9~~ 3 bytes

```
ð¶V

```

Try it

```
ð¶V     :Implicit input of array U and element V
ð       :Indices of elements in U
 ¶V     :That are equal to V

```
> 1 votes

# Answer
# Rust, 51 bytes

```
|a,v|(0..).zip(a).filter(move|a|a.1==v).map(|a|a.0)

```

Try it online!
> 1 votes

# Answer
# Pyt, 6 bytes

```
=ĐŁř*ž

```

Try it online!

```
=           implicit inputs; is each element in the array equal to the value?
 Đ          duplicate resultant array
  Łř        get length and create array [1,2,3,...,<length>]
    *       multiply (does normal integer multiplication for integers, booleans,
            and floats, and does string multiplication for strings)
     ž      remove zeros; implicit print

```
> 1 votes

# Answer
# Javascript,48 bytes

```
b=>a=>a.reduce((a,e,i)=>(e===b&&a.push(i),a),[])

```

```
let f=b=>a=>a.reduce((a,e,i)=>(e===b&&a.push(i),a),[]);

console.log(f(12)([12,14,14,2,"Hello World!",3,12,12]));         //[0,6,7]
console.log(f("Hello World")(["Hi", "Hi World!", 12,2,3,true])); //[]
console.log(f("a")(["A",true,false,"aa","a"]));                  //[4]
console.log(f(12)([12,"12",12]))                                 //[0,2]
```
> 0 votes

# Answer
# D, 78 bytes

```
int[]f(T)(T[]a,T e){int[]r;for(int i;i<a.length;i++)if(e==a[i])r~=i;return r;}

```

The calling mechanism is ... really odd: Try it online!.

D has a variant type!
> 0 votes

# Answer
# Swift 4, 46 bytes

```
{a,e in a.enumerated().flatMap{$1==e ?$0:nil}}

```

`a.enumerated()` produces an array of `(index, element)` pairs.

`flatMap` compares the element (the second member of the tuple, accessed by the implicit closure parameter `$1`), and either returns the index (the first member of the tuple, accessed by the implicit closure parameter `$0`), or `nil`.

`flatMap` has the effect of removing `nils` from the output sequence, so only the indices remain.

This is a byte shorter than the more obvious

```
{a,e in a.enumerated().filter{$1==e}.map{$0.0}}

```
> 0 votes

# Answer
# SmileBASIC, ~~77~~ 53 bytes

```
DEF S A,V
FOR I=0TO LEN(A)-1IF V==A[I]THEN?I
NEXT
END

```

Also works with strings/characters in addition to normal arrays/values.
> 0 votes

# Answer
# PHP, 99 bytes

Not the best, but at least I try.

PD: Hate PHP's functions name

```
function f($c,$a){return array_filter(array_keys($a), function($b)use($a,$c){return $a[$b]==$c;});}

```

Try it online!
> 0 votes

# Answer
# Kotlin, 66 bytes

```
{v:Any,l:List<Any>->l.mapIndexedNotNull{i,j->if(j==v)i else null}}

```

Try it online!

`mapIndexedNotNull` really is the powerhouse of this lambda. It's the same thing as `mapIndexed` (`map` with an additional index argument) with the added bonus that it excludes `null` results from the output. Find something we don't like? Return `null`!

```
{ v: Any, l: List<Any> ->          // lambda
    l.mapIndexedNotNull { i, j ->  // map with index, removing nulls
        if(j == v) i else null     // return index if equal else null
    }
}

```
> 0 votes

# Answer
# , 2 bytes

```
ss

```

**S**tring **s**earch is in the `strings` library which is implicitly imported if your interpreter isn’t too old. It’s defined as `I.@E.` (compare with the APL solution) so it can also look for sequences of values. Try it online!
> 0 votes

# Answer
# Factor, 7 bytes

```
indices

```

Try it online!
> 0 votes

# Answer
# jq, 25 bytes

```
.[0]as$r|.[1]|indices($r)

```

All input to `jq` has to be valid JSON, so the examples need to be enclosed in brackets. And boolean constants like `True` need to be translated to `true`, etc... Other than that, it essentially sets things up to use a builtin function `indices()` which does exactly what the challenges wants.

```
.[0]as$r                  - Set var "$r" to what we want to find
        |.[1]             - Select the list of options...
             |indices($r) - Find positions of "$r" in the list

```

The output is a list of integers, with the offsets to matching entries. The output is an empty list of the target isn't in the list.

Try it online!
> 0 votes

# Answer
# Thunno, \\$ 2 \log\_{256}(96) \approx \\$ 1.65 bytes

```
zI

```

Attempt This Online!

Built-in solution.
> 0 votes

# Answer
# Go, 75 bytes, `int` only

```
func(e int,A[]int)(I[]int){for i,E:=range A{if e==E{I=append(I,i)}};return}

```

Attempt This Online!

### Go, 98 bytes, generic

```
func f[T any](e T,A[]T,C func(T,T)bool)(I[]int){for i,E:=range A{if C(e,E){I=append(I,i)}};return}

```

Attempt This Online!

Golang is statically typed, so both solutions take in a homogenous slice.

The challenge as-written is possible with `interface{}` shenanigans.

### Go, 133 bytes, as written

```
func f[T any](e T,A[]any,C func(T,T)bool)(I[]int){for i,E:=range A{switch E:=any(E).(type){case T: if C(e,E){I=append(I,i)}}};return}

```

Attempt This Online!

Uses this trick to cast the generic type to `interface{}` so that it can be type-switched over.
> 0 votes

# Answer
# Nibbles, 2 bytes

```
`?$_

```

Attempt This Online!

Built-in.

```
`? Find indices
$   in the first argument
_   of the second argument

```
> 0 votes

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


title: Rotational Average

text:
# Question
Title: Rotational Average
Given an input integer `n >= 10`, output the average of all deduplicated rotations of the integer.

For example, for input `123`, the rotations are `123` (no rotation), `231` (one rotation) and `312` (two rotations). The average of those is `(123 + 231 + 312) / 3` or `222`.

As another example, take `4928`. The rotations are `4928`, `9284`, `2849`, and `8492`. Taking the average of those four numbers equals `6388.25`.

For another example, for input `445445`, the deduplicated rotations are `445445`, `454454`, and `544544`, so the output is `481481`.

For input `777`, there is only one deduplicated rotation, so the output is `777`.

## Rules

* If applicable, you can assume that the input/output will fit in your language's native Integer type.
* The input and output can be given by any convenient method.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 11 votes
# Python 3, ~~38~~ 36 bytes

```
lambda*n:10**len(n)//9*sum(n)/len(n)

```

Takes the digits as separate arguments. *Thanks to @Rod for suggesting Python 3, saving 2 bytes.*

Try it online!

# Answer
> 9 votes
# APL (Dyalog), 9 bytes

```
10⊥≢⍴+/÷≢

```

A monadic function taking a vector of digits as an argument.

Try it online!

I take the average of the digits `+/÷≢`, then repeat it by the length of the input `≢⍴`, and finally convert from base 10.

Conceptially, I am taking the sum of the rotations (without carrying):

```
 4  2  9  8
 2  9  8  4
 9  8  4  2
+8  4  2  9
 -----------
 23 23 23 23

```

This is just `4+2+9+8` repeated 4 times. Then converting from base `10` (which does the carrying for me) and dividing by the length. Although I divide by the length earlier on because it is equivilent and saves bytes.

# Answer
> 3 votes
# , ~~84~~ ~~73~~ 64 bytes

```
function(D,K=sum(D|1))mean(array(D,K+1:0)[1:K,1:K]%*%10^(K:1-1))

```

Try it online!

Input as list of digits.

Thanks to MickyT for shaving off 11 bytes! 8 bytes shaved by Dennis' proof that deduplication is unnecessary.

# Answer
> 3 votes
# Java 10, ~~163~~ ~~137~~ ~~76~~ ~~72~~ 71 bytes

```
n->(Math.pow(10,n.size())-1)/9*n.stream().mapToInt(i->i).sum()/n.size()

```

-36 bytes thanks to *@Nevay*.
-61 bytes thanks to *@OlivierGrégoire* by creating a port of *@Dennis*' Python 3 answer.
-1 bytes by taking the input as a List of digits instead of String.

**Explanation:**

Try it online.

```
n->                                 // Method with String parameter and double return-type
  (Math.pow(10,n.size())-1)/9       //  Repunits the same length as the input-size
  *n.stream().mapToInt(i->i).sum()  //  multiplied by the sum of digits
  /n.size()                         //  divided by the input-size

```

# Answer
> 3 votes
# Husk, 5 bytes

```
d´MKA

```

Try it online!

### Explanation

```
d´MKA
    A  Take the average of the digits
 ´MK   Replace each element of the original list with the average
d      Join the list to get a number

```

---

# Husk, 7 bytes

```
A§modṙŀ

```

Try it online!

### Explanation

```
A§modṙŀ
      ŀ  Take the range [1..length(input)]
 §m  ṙ   Rotate the input by each element of the range
   od    Convert each list of digits to a number
A        Take the average of the list

```

# Answer
> 3 votes
# Vyxal, 3 bytes

```
Ṗ⌊ṁ

```

*-2 bytes thanks to @lyxal*

Try it online!

Explanation

```
Ṗ   # Permutations
 ⌊  # Convert each to an integer
  ṁ # Mean

```

# Answer
> 2 votes
# Jelly, ~~6~~ 5 bytes

```
ṙJḌÆm

```

Try it online!

### How it works

```
ṙJḌÆm  Main link. Argument: A (digit array)

 J     Yield the indices of A, i.e., [1, ..., len(A)].
ṙ      Rotate A 1, ..., and len(A) units to the left, yielding a 2D array.
  Ḍ    Convert each rotation from decimal to integer.
   Æm  Take the arithmetic mean.

```

# Answer
> 2 votes
# 05AB1E, 9 bytes

```
vÀD}\OIg/

```

Try it online!

# Answer
> 2 votes
# Stax, 6 bytes

```
ñJä⌠╤►

```

Run and debug it

This program takes a quote-delimited string as input, and expresses the average as a reduced fraction. e.g. `777/1` It's not necessary to de-duplicate the rotations. It never changes the result.

Unpacked, ungolfed, and commented, it looks like this.

```
:)  get all character rotations
{em convert strings back to integers
:V  mean - integer inputs means result will be rational

```

Run this one

# Answer
> 2 votes
# Perl 5 `-lpF`, ~~24~~ 22 bytes

```
#!/usr/bin/perl -lpF
$_=1x@F/s/./+$&/g*eval

```

Try it online!

Doing it as a list of digits is only 1 byte shorter and feels like cheating:

```
#!/usr/bin/perl -p
$;+=$_}{$_=1x$./$.*$

```

Try it online!

# Answer
> 2 votes
# Perl 6, 15 bytes

```
{.sum/$_*1 x$_}

```

Try it online!

The average is the digit average applied to each decimal position, so digit average times 111.... `1 x $_` produces a string of 1s which get coerced to strings by the multiply.

Takes a list of digits as input. A sequence would require a .cache before the sum, and a number or string input would need a .comb.

# Answer
> 2 votes
# Ruby, 60 bytes

```
->n{a=b=c=0.0;a,b,c,n=a+n%10,b*10+1,c+1,n/10while n>0;a*b/c}

```

Try it online!

# Answer
> 2 votes
# Wolfram Language (Mathematica), 22 bytes

```
FromDigits[0#+Mean@#]&

```

Try it online!

# Answer
> 2 votes
# Ruby, 33 bytes

```
->n{10**(k=n.size)/9*n.sum*1.0/k}

```

Try it online!

A port of Dennis's Python 3 answer

### Here's my lame attempt (74 bytes)

```
->s{a=(1..s.size).map{|i|s.chars.rotate(i).join.to_i}|[];a.sum*1.0/a.size}

```

Try it online!

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

```
x=>eval(x.join`+`)*'1'.repeat(n=x.length)/n

```

Try it online!

> Can we take input as a list of digits? – Dennis♦ 7 mins ago
>
> @Dennis Sure, that's fine. Go save some bytes. :p – AdmBorkBork 3 mins ago

# Answer
> 1 votes
# Japt, 8 bytes

Takes input as an array of single digit strings.

```
xpUÊ)÷UÊ

```

Try it

---

## Explanation

```
             :Implicit input of array U
 pUÊ         :Repeat each string length of U times
x   )        :Reduce by addition
     ÷UÊ     :Divide by the length of U

```

# Answer
> 1 votes
# Python 2, ~~83~~ 77 bytes

```
def f(a):b={int(`a`[i:]+`a`[:i])for i in range(len(`a`))};print sum(b)/len(b)

```

EDIT: -6 bytes thanks to @ovs

# Answer
> 1 votes
# APL (Dyalog Unicode), ~~21~~ 14 bytesSBCS

```
+/≢÷⍨⍳∘≢(⍎⌽)¨⊂

```

Try it online!

Tacit prefix function. Takes input as a string.

Thanks to Adám for an enlightening 7 byte save.

### How?

```
+/≢÷⍨⍳∘≢(⍎⌽)¨⊂ ⍝ Main fn, example argument '123'
              ⊂ ⍝ Enclose the argument (turns it into a scalar)
             ¨  ⍝ Use each of the left arguments to
         ( ⌽)   ⍝ Rotate, then
          ⍎     ⍝ Convert strings into numbers
      ⍳∘≢       ⍝ Tally (≢) the argument, then index (⍳) from 1.
                ⍝ Returns 1 2 3 for a 3 digit argument, and rotates the argument 1, 2, then 3 times.
     ⍨          ⍝ Use the result as left argument for
    ÷           ⍝ Divide
   ≢            ⍝ By the number of rotations
+/              ⍝ And sum the results

```

# Answer
> 1 votes
# Charcoal, 11 bytes

```
Ｉ∕×ΣθＩ⭆θ1Ｌθ

```

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

```
    θ  θ  θ Input as a string
   Σ        Sum of digits
      ⭆ 1   Replace each character with the literal `1`
     Ｉ      Cast to integer
  ×         Multiply
         Ｌ  Length
 ∕          Divide
Ｉ           Cast to string
            Implicitly print

```

# Answer
> 1 votes
# , 10 bytes

```
10#.#$+/%#

```

This is a port of H.PWiz's great APL solution to J.

Takes a list of digits as an argument.

## Explanation:

`+/%#` the average of the digits (divide `%` the sum of the digits `+/` by their number `#`)

`#$`creates a list of copies of the average according to the number of digits

`10#.` convert form base 10

Try it online!

# Answer
> 1 votes
# Pari/GP, 34 bytes

Takes input as a list of digits.

```
n->fromdigits([vecsum(n)|x<-n])/#n

```

Try it online!

# Answer
> 1 votes
## C++, ~~218~~ 208 bytes

-10 bytes thanks to Zacharý

```
#include<set>
#include<cmath>
float a(int m){std::set<int>a;int n=m,t,c=0;for(;n>0;n/=10)++c;for(;n<c;++n){a.insert(m);t=m%10;m=m/10+std::pow(10.f,c-1)*t;}int s=0;for(int v:a){s+=v;}return float(s)/a.size();}

```

And, to test :

```
int main() {
    printf("%f\n%f\n%f\n%f\n",a(123),a(4928),a(445445),a(777));
}

```

# Answer
> 1 votes
# 05AB1E, 3 bytes

```
œÅA

```

Port of *@tybocopperkettle*'s Vyxal answer, so make sure to upvote him/her as well!

Try it online or verify all test cases.

**Explanation:**

```
œ    # Get all permutations of the (implicit) input
     #  e.g. 123 → ["123","132","213","231","312","321"]
 ÅA  # Take the average of this list
     #  → 222.0
     # (which is output implicitly as result)

```

# Answer
> 1 votes
# Thunno `E`, \\$ 9 \log\_{256}(96) \approx \\$ 7.41 bytes

```
DLzP.ZDAA

```

Attempt This Online!

Port of Vyxal.

#### Explanation

```
DLzP.ZDAA  # Implicit input. The E flag keeps it as a string.
DL         # Duplicate and get the length of the input string.
  zP       # Permutations of the input with the same length.
    .ZD    # Converted to integers from lists of characters.
       AA  # Get the average of this list of integers.
           # Implicit output.

```

# Answer
> 1 votes
# TI-Basic, 10 bytes

```
mean(Ans)int(1/9₁₀^(dim(Ans

```

Takes input in `Ans` as a list. Port of Dennis's Python 3 answer.

# Answer
> 0 votes
# Pyth, 12 bytes

```
csms.<zdlzlz

```

Probably improvable.

```
c         lz     Divide by the length of the input:
 s               Reduce by +
  m     lz       Map over d = [0 ... the length of the input]:
   s.<zd         Shift the input d characters to the left and cast to int

```

Try it here!

# Answer
> 0 votes
# J, 23 Bytes

```
(+/%#)".~.(|."0 1~i.@#)

```

Takes input as a string

### Explanation

```
          (|."0 1~i.@#)  | All rotations
        ~.               | Deduplicate
      ".                 | Convert each to int
(+/%#)                   | Average

```

# Answer
> 0 votes
# Matlab, 65 bytes

```
c=num2str(n);l=nnz(c);mean(str2num(c(mod((1:l)+(0:l-1)'-1,l)+1)))

```

Gonna work on this, pretty sure it can be done better.

# Answer
> 0 votes
## Clojure, 139 bytes

```
#(let[n(count %)G(set(apply map list(for[i(range n)](take n(drop i(cycle %))))))](/(apply +(for[g G](read-string(apply str g))))(count G)))

```

Quite sub-optimal language features for converting sequences of characters to integers.

# Answer
> 0 votes
# dc, 37 bytes

This is a full program, reading input and printing the output:

```
?1sd[O~rzsadO<x+ldO*1+sd]dsxxOkld*la/p

```

It works by separating the number into its digits, and multiplying the mean of the digits by the appropriate length repdigit (which is built up in `d` as we go).

```
?                               # read input
 1sd                            # initialize d=1
    [                   ]dsxx   # define and execute recursive macro x:
     O~r                        #   remainder and quotient of /10
        zsa                     #   a = number of digits
           dO<x                 #   recurse if needed
               +ldO*1+sd        #   increment repdigit d
                             Ok         # after executing x, set precision
                               ld*la/   # multiply by repdigit; divide by a
                                     p  # print the result

```

# Answer
> 0 votes
# PowerShell Core, 45 bytes

```
($args-join'+'|iex)*("1"*($l=$args.Count))/$l

```

Try it online!

# Answer
> 0 votes
# Pyt, 7 bytes

```
ĐŁᴇ₉⇹µ*

```

Try it online!

Takes the number as a list of digits

```
    Đ          implicit input (n); Đuplicate on stack
     Ł         get Łength (l)
      ᴇ₉       get repunit of length l
        ⇹µ     get mean of digits of n
          *    multiply; implicit print

```

---
Tags: code-golf, math, number-theory
---


title: Knook to Mate... With Portals!

text:
# Question
Title: Knook to Mate... With Portals!
*Alternatively: Now you're checking with portals!*

*Inspired this challenge*

I am somewhat of a self-declared Chess Anarchist. That means that when I play chess, en passant is forced (else the brick gets used), double check is mate (and pasta), and all sorts of new pieces and squares are added to the game.

One such piece is the Knook (also called an "Empress" or "Chancellor" in fairy chess). It moves like a horsey and a rook combined. Another common addition are portals, like the kinds you see in the Portal series. They behave as you would expect.

Therefore, in this challenge, I'll be give you the position of a white knook, two black kings and an orange and blue portal. You'll give me the square I should move my knook to in order to check both the kings at once and win the game.

## Detailed Explanation of Knooks and Portals

### The Knook

Here is how a knight moves in chess:

Here is how a rook moves in chess:

Therefore, this is how a knook (knight + rook) moves in chess:

In BCPS notation, it's move is `EM`. In Parlett notation, it's move is `n+, ~ 1/2`. In Betza notation, it's move is `RN`.

### Portals

From the Portal Wiki:

> Portals in a pair act as a direct link between one another. Anything that goes into one portal comes instantly out the other.

Therefore, when a piece moves into a portal, it comes out the other portal. Portals occupy a single square. There are only ever two portals on a board - one orange and one blue. Pieces cannot land on a portal, as they'd just infinitely teleport between the orange and blue portals. Pieces can also attack through portals (so a piece in a position where another piece could exit a portal would be able to be taken.)

Here's are some examples of how a rook would move through a portal. Note that it always exits the other portal in the direction it entered the first portal. Note that the rook also cannot "jump" over the portal - it has to go through if there is a portal in its way.

|  |  |
| --- | --- |

Here's how a knight would move through portals. Note that it can either move two squares into a portal and exit one square in a perpendicular direction, or one square into a portal and exit two squares in a perpendicular direction.

|  |  |
| --- | --- |

Therefore, this is how a knook would move through a portal, obeying laws of both the rook and knight portal movement rules:

|  |  |
| --- | --- |

## An Example

On the following board, the knook is on square `b2`, the black kings are on `d7` and `f6` and the portals are on squares `b5` and `d2`. The winning move is to move the knook through the blue portal to d5, which checks the king on `d7` via rook moves and the king on `f6` via knight moves.

On the following board, the knook is on square `c5`, the black kings are on `g3` and `h4` and the portals are on squares `f7` and `g4`. The winning move is to move the knook to `d7`, as the knook threatens to take the king on `h4` with rook moves after portal travel and threatens to take the king on `g3` with knight moves after portal travel.

On the following board, the knook is on square `f4`. The black kings are on `b8` and `d3`. The portals are on squares `f6` and `a4`. The winning move is to move the knook through the portal on `d6` and exit the portal on `a4` via a knight move (up 2, right 1). This checks both kings.

## Rules

* The positions will be given in algebraic chess notation (letter then number of the square).
* The winning move will be returned in algebraic chess notation.
* Positions can be given and returned in any reasonable and convienient format, including:
    + A list of strings (e.g. `["f4", "b8", "d3", "f6", "a4"]`)
    + A list of list of strings (e.g. `[["f", "4"], ["b", "8"], ["d", "3"], ["f", "6"], ["a", "4"]]`)
    + A list of list of numbers that represent the character codes of each string item (e.g. `[[102, 52], [98, 56], [100, 51], [102, 54], [97, 52]]`)
    + A list of string, number pairs (e.g. `[["f", 4], ["b", 8], ["d", 3], ["f", 6], ["a", 4]]`)
* Input formats and output formats don't have to match, so long as they are consistent.
* Piece positions can be taken in any order (e.g. `[portal 1, portal 2, knook, king 1, king 2]` or `[knook, king 1, king 2, portal 1, portal 2]`)
* This doesn't change much, but you can assume that the black kings will never be on the `c2` square.
* You may assume that there will always be at least one solution to each input.
* The board layout may start with 0 or 1 king(s) already in check. Your goal is to double check.
* Double check is strictly defined as checking both kings for this challenge. A knook checking a king through a portal and starting in check is counted as a single check only for simplicity.
* It doesn't matter if a king can capture the knook if double check is achieved. All that matters is that both kings are in check at the same time.
* If there is more than one solution, you can output one, or all of the solutions.
* Portal travel might not be required for a winning move. Double check via normal knook movement is just as valid as portal usage.
* This is , so the shortest answer in bytes in each language wins.

## Testcases

*Input order is `[knook, king 1, king 2, portal 1, portal 2]`*

```
Positions -> Winning Square
["b2", "d7", "f6", "b5", "d2"] -> "d5"
["c5", "g3", "h4", "f7", "g4"] -> "d7"
["f4", "b8", "d3", "f6", "a4"] -> "a4"
["h1", "a1", "a3", "c1", "f1"] -> "b1"
["c2", "a8", "h8", "d2", "d6"] -> "d8"
["d2", "c6", "g2", "b2", "g7"] -> "g6"
["d3", "f6", "h6", "d4", "e4"] -> "g4"
["c4", "f7", "h5", "a2", "f5"] -> "b2" // Attacks through the portal
["h5", "a7", "e2", "a4", "g6"] -> "g3" // Attacks a7 through the portal and e2 normally.
["h6", "d4", "g3", "a1", "a8"] -> "f5" // No portal travel needed

```

# Answer
> 7 votes
# Python3, 970 bytes:

```
M=[((1,0),1,3),((0,1),0,2),((-1,0),1,3),((0,-1),0,2)]
def A(c):
 q=[(c[0],i,1,[c[0]])for i,*_ in M]+[(c[0],[(i,2),(M[j][0],1)],0,[c[0]])for i,*J in M for j in J]+[(c[0],[(i,1),(M[j][0],2)],0,[c[0]])for i,*J in M for j in J]
 while q:
  (x,y),m,o,P=q.pop(0)
  if o:
   X,Y=m
   if 0<=x+X<8 and 0<=y+Y<8:
    if(T:=(x+X,y+Y))in P:continue
    if T in c[1:3]:yield(1,T)
    elif T in c[-2:]:q+=[([*{*c[-2:]}-{T}][0],m,o,P+[T])]
    else:yield(0,T);q+=[(T,m,o,P+[T])]
  else:
   [(X,Y),C],*I=m
   if 0<=x+X<8 and 0<=y+Y<8:
    if(T:=(x+X,y+Y))in P:continue
    if C-1==0 and[]==I:yield(T in c[1:3],T)
    else:
     if T in c[-2:]and C-1:continue
     q+=[([T,[*{*c[-2:]}-{T}][0]][T in c[-2:]],[[[(X,Y),C-1]]+I,I][C-1==0],0,P+[T])]
def f(d):
 S,*c=[(8-int(b),ord(a)-97)for a,b in d]
 q,s=[S],[S]
 while q:
  S=q.pop(0)
  for x,y in A([S]+c):
   q+=[y]
   if x==0:
    k=[[],[]]
    for X,Y in A([y]+c):k[X]+=[Y]
    if{*k[1]}=={*([1]+c)[1:3]}:return chr(97+y[1])+str(8-y[0])

```

Try it online!

# Answer
> 4 votes
# JavaScript (Node.js), 367 bytes

```
(R,J,K,$,_)=>(
  U=p=>parseInt(p,36),     // internal type
  P=U($),Q=U(_),           // Portal
  g=n=>(                   // p^P^Q switch P and Q
    M=(p,a,b)=>a?M((p+=a)-P&&p-Q?p:p^P^Q,b):p==n,
                           // Two movements for knight
    h=(p,x)=>
      [1,2,-1,-2].some((i,_,o)=>o.some(j=>
        i*i-j*j&&M(U(p),i*36,j)|M(U(p),j,i*36)
      ))|                  // X then Y; Y then X
      (e=(w,i=24,q=U(p))=>q-U(x)?
                           // Maximum 13 moves + w%36 range 8
        (q+=w)-P&&q-Q?
          w%36<i&&q==n|e(w,i-1,q)
        :
          e(w,i,q^P^Q)     // Not counting teleport don't hurt
      )(36)|e(-36)|e(1)|e(-1):0
  )(R)&h(J,K)&h(K,J)&~-n%36<8&
  !~[J,K,$,_].indexOf(N=n.toString(36))?N:g(-~n)
)(360)

```

Try it online!

Modified to list all possible outputs

```
[ 'b2', 'd7', 'f6', 'b5', 'd2' ] [ 'b6', 'd5', 'd6' ]
[ 'c5', 'g3', 'h4', 'f7', 'g4' ] [ 'd7', 'f5', 'h5' ]
[ 'f4', 'b8', 'd3', 'f6', 'a4' ] [ 'b4' ]
[ 'h1', 'a1', 'a3', 'c1', 'f1' ] [ 'b1', 'c2' ]
[ 'c2', 'a8', 'h8', 'd2', 'd6' ] [ 'c8', 'd8' ]
[ 'd2', 'c6', 'g2', 'b2', 'g7' ] [ 'a7', 'c2', 'c7', 'e7', 'g6' ]
[ 'd3', 'f6', 'h6', 'd4', 'e4' ] [ 'g4' ]
[ 'c4', 'f7', 'h5', 'a2', 'f5' ] []
[ 'h5', 'a7', 'e2', 'a4', 'g6' ] [ 'g3' ]
[ 'h6', 'd4', 'g3', 'a1', 'a8' ] [ 'f5', 'g4' ]

```

# Answer
> 3 votes
# Charcoal, ~~194~~ 163 bytes

```
ＵＭθ⍘ι⁴⁰≔Ｅ²⊟θδＦ⁸ＦＥ⁸⁺κ⁺⁴⁰¹×⁴⁰ι¿¬№⁺θδκ«≔⟦⟧ηＦθ«≔⊙⊞ＯΦ⟦δ⮌δ⟧⬤⟦κλ⟧№⟦¹¦²¦⁴⁰¦⁸⁰⟧↔⁻ξ§μπυ№⟦³⁸¦⁴²¦⁷⁹¦⁸¹⟧↔⁻⁻λκ↨μ±¹ζＦ⟦¹¦⁴⁰±¹±⁴⁰⟧«≔κεＦ¹⁵«≧⁺με≧⁺⁼λεζ¿№δε≦⁻Σδε¿‹⁰⌕θε≔⁰μ»»⊞ηζ»¿⌊η⟦⍘κ⁴⁰

```

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

```
ＵＭθ⍘ι⁴⁰

```

Inspired by @l4m2's use of base conversion, convert the inputs from "base 40" (chosen to make it easier for me to calculate the various constants).

```
≔Ｅ²⊟θδ

```

Split off the portal squares.

```
Ｆ⁸ＦＥ⁸⁺κ⁺⁴⁰¹×⁴⁰ι¿¬№⁺θδκ«

```

Loop over each potential square, converted into a "base 40" value, but excluding the input squares.

```
≔⟦⟧η

```

Start counting the number of pieces this square attacks.

```
Ｆθ«

```

Loop over the knook and the two kings.

```
≔⊙⊞ＯΦ⟦δ⮌δ⟧⬤⟦κλ⟧№⟦¹¦²¦⁴⁰¦⁸⁰⟧↔⁻ξ§μπυ№⟦³⁸¦⁴²¦⁷⁹¦⁸¹⟧↔⁻⁻λκ↨μ±¹ζ

```

Check whether the portals are near to the two squares (trying both permutations of squares near to different portals), then also considering the case of a regular knight's move away, see whether the squares are a knight's move away, and if any of the three cases succeeds then mark this square as attackable.

```
Ｆ⟦¹¦⁴⁰±¹±⁴⁰⟧«

```

Loop over all possible rook movements.

```
≔κε

```

Start at one square.

```
Ｆ¹⁵«

```

Repeat 15 times.

```
≧⁺με

```

Move one square in the current direction.

```
≧⁺⁼λεζ

```

If this is the target square then mark it as attackable.

```
¿№δε≦⁻Σδε

```

If it's a portal then jump through it.

```
¿‹⁰⌕θε≔⁰μ

```

If it's a king then stop moving.

```
»»⊞ηζ

```

Keep count of the number of pieces that were attackable.

```
»¿⌊η⟦⍘κ⁴⁰

```

Output the square if all three were attackable, meaning that the knook can move to this square, and from this square can check both kings.

---
Tags: code-golf, chess
---


title: Bingo card generator

text:
# Question
Title: Bingo card generator
A Bingo card is five columns of five squares each, with the middle square designated "FREE". Numbers cannot duplicate.

The five columns are populated with the following range of numbers:

* B:1-15
* I:16-30
* N:31-45
* G:46-60
* O:61-75

In as few characters as possible, output a string that can be interpreted as a randomized Bingo card. For example:

> 1,2,3,4,5,16,17,18,19,20,31,32,33,34,35,46,47,48,49,50,61,62,63,64,65

This example is not randomized so that I can show that column 1 is populated with 1,2,3,4,5. Also note that the free space has not been given any special treatment because the front-end that interprets this string will skip it.

Another example would be:

> 1,16,31,46,61,2,17,32,47,62...

In this example, the output is by row instead of by column.

A third example might be:

> 01020304051617181920313233343546474849506162636465

This is the same output as the 1st example except in fixed length.

# Answer
# , 38 bytes

```
cat(apply(matrix(1:75,,5),2,sample,5))

```

Try it online!

(another 7 years later... )
> 3 votes

# Answer
# PHP, 86

```
for($o=[];25>$i=count($o);){$n=rand(1,15)+($i-$i%5)*3;$o[$n]=$n;}echo implode(",",$o);

```
> 2 votes

# Answer
# R, ~~63~~ ~~51~~ ~~50~~ ~~49~~ 45 bytes

Thanks to Billywob for ongoing suggestions and encouraging my competitive streak.

```
cat(sapply(split(n<-1:75,cut(n,5)),sample,5))

```

> 5 14 15 3 1 20 30 28 18 27 32 45 42 43 41 49 54 50 56 47 68 66 64 73 71
> 2 votes

# Answer
## Windows PowerShell, 51 ~~54~~

I'm not sure whether I understood your task correctly, though.

```
(0..4|%{($x=15*$_+1)..($x+14)|random -c 5})-join','

```

Sample outputs:

```
5,9,1,7,13,26,18,23,17,22,37,33,34,41,44,50,53,59,60,58,73,72,64,69,66
14,10,13,5,1,24,29,26,17,30,34,33,43,41,38,59,50,60,49,56,71,61,72,70,68
3,11,4,5,13,27,16,25,26,22,43,34,42,32,38,51,52,49,58,54,61,70,73,71,62
1,9,13,12,4,23,25,20,26,22,40,33,35,44,37,55,47,52,59,53,74,70,75,64,69
8,6,7,1,9,16,21,23,18,17,35,41,37,38,34,60,50,57,51,59,66,75,73,74,71
11,6,13,4,1,29,27,24,22,18,40,35,41,32,43,51,54,57,58,53,74,71,69,66,64

```
> 1 votes

# Answer
## Ruby 1.9, 48 characters

```
$><<(0..4).map{|i|[*1..75][15*i,15].sample 5}*?,

```
> 1 votes

# Answer
**PHP 106**

```
<?$z=1;for($i=0;$i<5;$i++){for($j=0;$j<rand(1,5);$j++){$o[]=rand($z,$z+15);}$z+=15;}echo implode(",", $o);

```

I'm not sure I understood correctly the problem... Can you provide a more detailed explanation?
> 1 votes

# Answer
# Vyxal, 11 bytes

```
75ɾ15ẇƛÞ℅5Ẏ

```

Try it Online!

```
75ɾ         # range(1, 75)
   15ẇ      # Cut into chunks of 15
      ƛ     # Over each
       Þ℅   # Shuffle
         5Ẏ # Get the first five items

```
> 1 votes

# Answer
## Clojure - 52 chars

```
(map #(take 5(shuffle %))(partition 15(range 1 76)))

```

Example output (note that it provides the separate rows as sub-lists):

```
((4 1 12 10 2) (25 23 21 16 27) (39 33 45 44 43) (48 53 59 54 47) (73 71 61 64 63))

```
> 0 votes

# Answer
# Python 2, 84 bytes

```
from random import*
print sum([sample(range(1+i*15,16+i*15),5)for i in range(5)],[])

```

If the output as list if lists is okay there is a **75 bytes** solution:

```
from random import*
print[sample(range(1+i*15,16+i*15),5)for i in range(5)]

```
> 0 votes

# Answer
# Japt, 12 bytes

```
75õ òF Ëá5 ö

```

Try it (or formatted as a Bingo card)
> 0 votes

---
Tags: code-golf, game
---


title: Modular multiplicative inverse

text:
# Question
Title: Modular multiplicative inverse
Your task is to given two integer numbers, `a` and `b` calculate the modular multiplicative inverse of a modulo b, if it exists.

The modular inverse of `a` modulo `b` is a number `c` such that `ac ≡ 1 (mod b)`. This number is unique modulo `b` for any pair of `a` and `b`. It exists only if the greatest common divisor of `a` and `b` is `1`.

The Wikipedia page for modular multiplicative inverse can be consulted if you require more information about the topic.

## Input and Output

Input is given as either two integers or a list of two integers. Your program should output either a single number, the modular multiplicative inverse that is in the interval `0 < c < b`, or a value indicating there is no inverse. The value can be anything, except a number in the range `(0,b)`, and may also be an exception. The value should however be the same for cases in which there is no inverse.

`0 < a < b` can be assumed

## Rules

* The program should finish at some point, and should solve each test case in less than 60 seconds
* Standard loopholes apply

## Test cases

Test cases below are given in the format, `a, b -> output`

```
1, 2 -> 1
3, 6 -> Does not exist
7, 87 -> 25
25, 87 -> 7
2, 91 -> 46
13, 91 -> Does not exist
19, 1212393831 -> 701912218
31, 73714876143 -> 45180085378
3, 73714876143 -> Does not exist

```

# Scoring

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

This and this are similar questions, but both ask for specific situations.

# Answer
> 11 votes
# Mathematica, 14 bytes

Obligatory Mathematica builtin:

```
ModularInverse

```

It's a function that takes two arguments (`a` and `b`), and returns the inverse of a mod b if it exists. If not, it returns the error `ModularInverse: a is not invertible modulo b.`.

# Answer
> 8 votes
# JavaScript (ES6), ~~79~~ ~~73~~ ~~62~~ 61 bytes

Returns `false` if the inverse does not exist.

It uses the extended Euclidean algorithm and solves all test cases almost instantly.

```
f=(a,b,c=!(n=b),d=1)=>a?f(b%a,a,d,c-(b-b%a)/a*d):b<2&&(c+n)%n

```

### Test cases

```
f=(a,b,c=!(n=b),d=1)=>a?f(b%a,a,d,c-(b-b%a)/a*d):b<2&&(c+n)%n

console.log(f(1, 2)) // -> 1
console.log(f(3, 6)) // -> Does not exist
console.log(f(7, 87)) // -> 25
console.log(f(25, 87)) // -> 7
console.log(f(2, 91)) // -> 46
console.log(f(13, 91)) // -> Does not exist
console.log(f(19, 1212393831)) // -> 701912218
console.log(f(31, 73714876143)) // -> 45180085378
console.log(f(3, 73714876143)) // -> Does not exist
```

# Answer
> 5 votes
# Python 2, 34 bytes

```
f=lambda a,b:a==1or-~b*f(-b%a,a)/a

```

Try it online!

Recursive function that gives `True` for `print f(1,2)`, which I believe to be acceptable, and errors for invalid inputs.

We are trying to find \\$x\\$ in \\$a\cdot x\equiv 1\pmod{b}\\$.

This can be written as \\$a\cdot x-1=k\cdot b\\$ where \\$k\\$ is an integer.

Taking \\$\mod{a}\\$ of this gives \\$-1\equiv k\cdot b\pmod{a}\\$. Moving the minus gives \\$-k\cdot b\equiv1\pmod{a}\\$, where we have to solve for \\$k\\$.

Seeing how it resembles the initial scenario, allow us to recurse to solve for \\$k\\$ by calling the function with \\$f(-b\\%a,a)\\$ (works because Python gives positive values for modulo with a negative argument).

The program recurses for until \\$a\\$ becomes 1, which only happens if the original \\$a\\$ and \\$b\\$ are coprime to each other (ie there exists a multiplicative inverse), or ends in an error caused by division by 0.

This value of \\$k\\$ can be substituted in the equation \\$a\cdot x-1=k\cdot b\\$ to give \\$x\\$ as \\$\frac{k\cdot b+1}{a}\\$.

# Answer
> 4 votes
# Jelly, 2 bytes

```
æi

```

Try it online!

This uses a builtin for modular inverse, and returns 0 for no modular inverse.

# Jelly, 7 bytes

```
R×%⁸’¬T

```

Try it online!

Outputs empty set (represented as empty string) on no modular inverse. Runs out of memory on TIO for the largest test-cases, but should work given enough memory.

**How it Works**

```
R×%⁸’¬T
R        Generate range of b
 ×       Multiply each by a
  %⁸     Mod each by b
    ’    Decrement (Map 1 to 0 and all else to truthy)
     ¬   Logical NOT
      T  Get the index of the truthy element.

```

If you want to work for larger test-cases, try this (relatively ungolfed) version, which requires much time rather than memory:

## Jelly, 9 bytes

```
×⁴%³’¬ø1#

```

Try it online!

**How it Works**

```
×⁴%³’¬ø1#
        #   Get the first
      ø1      one integer
            which meets:
×⁴            When multiplied by a
  %³          And modulo-d by b
    ’         Decrement
     ¬        Is falsy

```

# Answer
> 4 votes
# Mathematica, 18 bytes

```
PowerMod[#,-1,#2]&

```

**input**

> \[31, 73714876143\]

# Answer
> 3 votes
# \+ numbers, 15 bytes

```
numbers::modinv

```

returns `NA` for those `a` without inverses mod `b`.

R-Fiddle to try it!

# , 33 bytes (non-competing)

This will fail on very large `b` since it actually creates a vector of size `32*b` bits.

```
function(a,b)which((1:b*a)%%b==1)

```

Try it online!

Returns `integer(0)` (an empty list) for those `a` without inverses mod `b`.

# Answer
> 3 votes
# Japt, ~~9~~ 8 bytes

Takes the inputs in reverse order. Outputs `-1` for no match. Craps out as the bigger integer gets larger.

```
Ç*V%UÃb1

```

Test it

* Saved 1 byte thanks to ETH pointing out an errant, and very obvious, space.

# Answer
> 2 votes
# Python 2, ~~51~~ ~~49~~ ~~54~~ ~~53~~ ~~51~~ 49 bytes

-1 byte thanks to officialaimm
-1 byte thanks to Shaggy

```
a,b=input()
i=a<2
while(a*i%b-1)*b%a:i+=1
print+i

```

Try it online!

Prints `0` when there is no solution.

# Answer
> 2 votes
# Pyth, 10 bytes

*3 bytes saved thanks to @Jakube*.

```
xm%*szdQQ1

```

**Try it here!**

Returns `-1` for no multiplicative inverse.

### Code Breakdown

```
xm%*szdQQ1      Let Q be the first input.
 m      Q       This maps over [0 ... Q) with a variable d.
   *szd         Now d is multiplied by the evaluated second input.
  %    Q        Now the remained modulo Q is retrieved.
x        1      Then, the first index of 1 is retrieved from that mapping.

```

# Pyth, ~~15~~ 13 bytes

```
KEhfq1%*QTKSK

```

Throws an exception in case no multiplicative inverse exists.

**Try it here!**

# Pyth, 15 bytes

```
Iq1iQKEfq1%*QTK

```

This adds lots of bytes for handling the case where no such number exists. The program can be shortened significantly if that case would not need to be handled:

```
fq1%*QTK

```

**Try it here!**

# Answer
> 2 votes
# Python 3 \+ gmpy, 23 bytes

I don't think it can get any shorter in Python.

```
gmpy.invert
import gmpy

```

Try it online! (won't work if you do not have gmpy installed)

# Answer
> 2 votes
# Python 3, 49 bytes

```
lambda a,b:[c for c in range(b)if-~c*a%b==1][0]+1

```

Try it online!

# Python 3, 50 bytes

```
lambda a,b:[c for c in range(1,b+1)if c*a%b==1][0]

```

Try it online!

This throws `IndexError: list index out of range` in case there is no modular multiplicative inverse, as it is allowed by the rules.

# Answer
> 2 votes
# 8th, 6 bytes

**Code**

```
invmod

```

**Explanation**

`invmod` is a 8th word that calculates the value of the inverse of `a`, modulo `b`. It returns `null` on overflow or other errors.

**Usage and test cases**

```
ok> 1 2 invmod .
1
ok> 3 6 invmod .
null
ok> 7 87 invmod .
25
ok> 25 87 invmod .
7
ok> 2 91 invmod .
46
ok> 13 91 invmod .
null
ok> 19 1212393831 invmod .
701912218
ok> 31 73714876143 invmod .
45180085378
ok> 3 73714876143 invmod .
null

```

# Answer
> 2 votes
# Pari/GP, 11 bytes

```
a->b->1/a%b

```

Throws an error when there is no inverse.

Try it online!

# Answer
> 2 votes
# , 28 bytes

```
4 :'(1=x+.y)*x y&|@^<:5 p:y'

```

Try it online!

Uses Euler's theorem. Returns 0 if the inverse does not exist.

## Explanation

```
4 :'(1=x+.y)*x y&|@^<:5 p:y'  Input: a (LHS), b (RHS)
4 :'                       '  Define an explicit dyad - this is to use the special
                              form `m&|@^` to perform modular exponentiation
                          y   Get b
                      5 p:    Euler totient
                    <:        Decrement
             x                Get a
                   ^          Exponentiate
               y&|@             Modulo b
       x+.y                   GCD of a and b
     1=                       Equals 1
            *                 Multiply

```

# Answer
> 1 votes
# C (gcc), ~~48 110~~ 104 bytes

```
#define f(a,b)g(a,b,!b,1,b)
long g(a,b,c,d,n)long a,b,c,d,n;{a=a?g(b%a,a,d,c-(b-b%a)/a*d):!--b*(c+n)%n;}

```

Try it online!

This should work with all inputs (that fit within a long) within 60 seconds.

Edit. I'm already abusing the `n` variable so I might as well assume that gcc puts the first assignment in `%rax`.

# Answer
> 1 votes
# C (gcc), 115 bytes

```
#define L long long
L g(L a,L b,L c,L d){return a?g(b%a,a,d-b/a*c,c):b-1?0:d;}L f(L a,L b){return(g(a,b,1,0)+b)%b;}

```

Try it online!

Extended Euclidean algorithm, recursive version

# C (gcc), 119 bytes

```
long long f(a,b,c,d,t,n)long long a,b,c,d,t,n;{for(c=1,d=0,n=b;a;a=t)t=d-b/a*c,d=c,c=t,t=b%a,b=a;return b-1?0:(d+n)%n;}

```

Try it online!

Extended Euclidean algorithm, iterative version

# Answer
> 1 votes
# APL (Dyalog Unicode), 36 38 bytes

```
{⌈/i×1=⍵|(i←⍳⍵)×⍵|⍺}

```

Try it online!

Explanation:

```
                   ⍵|⍺} ⍝ Get ⍺ mod ⍵
             (i←⍳⍵)×     ⍝ Multiply the result by all numbers up to ⍵
          ⍵|            ⍝ Take result mod ⍵
     i×1=                ⍝ Find all numbers (1,⍵) where the mod is 1
{⌈/                      ⍝ And take the largest

```

Much thanks to Adam in the APL Orchard chatroom for the help with this one!

Formula obtained from this site

First iteration:

```
{((⍵|⍺),⍵){+/⌈/⍵×1=(¯1↑⍺)|⍵×⊃⍺}⍳⍵}

```

# Answer
> 1 votes
# Python 3.8, 22 bytes

```
lambda a,b:pow(a,-1,b)

```

Obligatory Python 3.8+ builtin. Outputs the result, or gives the error `ValueError: base is not invertible for the given modulus` if there is no result.

Try it online.

**Explanation:**

To quote the Python 3.8 release notes:

> For integers, the three-argument form of the pow() function now permits the exponent to be negative in the case where the base is relatively prime to the modulus. It then computes a modular inverse to the base when the exponent is -1, and a suitable power of that inverse for other negative exponents. For example, to compute the modular multiplicative inverse of 38 modulo 137, write:
>
> ```
> >>> pow(38, -1, 137)
> 119
> >>> 119 * 38 % 137
> 1
>
> ```
>
> Modular inverses arise in the solution of linear Diophantine equations. For example, to find integer solutions for `4258 + 147 = 369`, first rewrite as `4258 ≡ 369 (mod 147)` then solve:
>
> ```
> >>> x = 369 * pow(4258, -1, 147) % 147
> y = (4258 * x - 369) // -147
> 4258 * x + 147 * y
> 369
>
> ```
>
> (Contributed by Mark Dickinson in bpo-36027.)

# Answer
> 1 votes
# \[Pyt\], 1 byte

```
ɯ

```

Try it online!

Takes inputs in the order `b a` (on separate lines). Outputs `None` if there is no such multiplicate inverse. Gotta love built-ins.

# Answer
> 0 votes
# Python 2 \+ sympy, 74 bytes

```
from sympy import*
def f(a,m):i,_,g=numbers.igcdex(a,m);return g==1and i%m

```

Try it online!

Taken from Jelly source code.

# Answer
> 0 votes
# JavaScript (ES6), ~~42~~ ~~41~~ ~~39~~ 38 bytes

Outputs `false` for no match. Will throw a overflow error as the second number gets to be too large.

```
x=>y=>(g=z=>x*z%y==1?z:z<y&&g(++z))(1)

```

# Answer
> 0 votes
# Python 2, 52 bytes

*-3 bytes thanks to Mr. Xcoder.*

```
f=lambda a,b,i=1:i*a%b==1and i or i<b and f(a,b,i+1)

```

Try it online!

Outputs `False` on no solution and errors out as `b` gets larger.

## Embedded TIO

I'm just testing out iframes in Stack Snippets and they work absolutely fantastic.

```
html,body{height:100%;}iframe{height:100%;width:100%;border:none;}
```

```
<iframe src="https://tio.run/##PY3BCsIwEETv/Yq5CEndy6ZotbhfIh4SanBB09Lm4tdHU8HTvIHhzfzOjym5UqI8/SuMHp4CqfCgrd8FEfZphGJaoJeAWqLZJnu2Jd/XvEJwNUxwlmA6wrFmTzj1FdzhT4QzV@DuR7emidULTdhMA@ZFU/4@tGrLBw"></iframe>
```

# Answer
> 0 votes
# Axiom, 45 bytes

```
f(x:PI,y:PI):NNI==(gcd(x,y)=1=>invmod(x,y);0)

```

0 for error else return z with x\*z Mod y =1

# Answer
> 0 votes
# Jelly, 27 bytes

```
²%³
⁴Ç⁹Ð¡x⁸
ÆṪ’BṚçL$P%³×gỊ¥

```

Try it online!

Uses Euler's theorem with modular exponentiation. Since Jelly doesn't have a builtin to perform modular exponentiation, it had to be implemented, and it took most of the bytes.

# Answer
> 0 votes
# Axiom, 99 bytes

```
w(a,b,x,u)==(a=0=>(b*b=1=>b*x;0);w(b rem a,a,u,x-u*(b quo a)));h(a,b)==(b=0=>0;(b+w(a,b,0,1))rem b)

```

it use the function h(); h(a,b) return 0 if error \[not exist inverse\] otherwise it return the z such that a\*z mod b = 1 This would be ok even if arguments are negative...

this would be the general egcd() function that retunr a list of int (so they can be negative too)

```
egcd(aa:INT,bb:INT):List INT==
   x:=u:=-1   -- because the type is INT
   (a,b,x,u):=(aa,bb,0,1)
   repeat
      a=0=>break
      (q,r):=(b quo a, b rem a)
      (b,a,x,u):=(a,r,u,x-u*q)
   [b,x, (b-x*aa)quo bb]

```

this is how use it

```
(7) -> h(31,73714876143)
   (7)  45180085378
                                                    Type: PositiveInteger

```

i find the base algo in internet from https://pastebin.com/A13ybryc

---
Tags: code-golf, math, number, number-theory, abstract-algebra
---