text:
Factoring factorials
Today in my statistics class, I found that some factorials can be simplified when multiplied together! For example: 5! * 3! = 5! *3*2 = 5! *6 = 6!
Your job:
Given a string containing only Arabic numbers and exclamation points, simplify my factorial to its shortest possible string, in the least amount of bytes for your language, code golf style.
Input
A string containing only Arabic numbers and exclamation points. The factorials for the input won't be bigger than 200!. Factorials will not have more than one factorial per number. Input may be taken as a list of integers.
Output
A possibly shortened string, that has the equivalent value on the input. Order is unimportant. Factorial notation is a must,  but you aren't required to use more than one factorial symbol per number.
Test cases
In: 3!2!2!
Out: 4!

In 2!3!2!0!
Out: 4!

In: 7!2!2!7!2!2!2!2!
Out: 8!8!

In: 23!3!2!2!
Out: 24!
Also: 4!!

In: 23!3!2!2!2!
Out: 24!2!

In: 127!2!2!2!2!2!2!2!
Out: 128!

In: 32!56!29!128!
Out: 29!32!56!128!

Best of luck

Since the empty product is 1 is the output for, say 1!1! just an empty string?

@JonathanAllan 1!1! Reduces to 1! Or 0!

Which then reduces to the empty string :/

@JonathanAllan I'm going to say 1 is not equal to as empty string

Jelly,  17  18 bytes
!P
ÇṗLÇ⁼¥ÐfÇḢḟ1ȯ0F

A monadic link taking and returning a list of the numbers (sticks to the one factorial per number option)
Try it online!
How?
A golfed (although independently written) version of Pietu1998's solution.
!P - Link 1, product of factorials: list
!  - factorial (vectorises)
 P - product

ÇṗLÇ⁼¥ÐfÇḢḟ1ȯ0F - Main link: list                       e.g. [3,2,2]
Ç               - call the last link (1) as a monad           24
  L             - length                                      3
 ṗ              - Cartesian power      [[1,1,1],[1,1,2],...,[1,1,24],...,[24,24,24]]
        Ç       - call the last link (1) as a monad           24
      Ðf        - filter keep if:
     ¥          -   last two links as a dyad:
   Ç            -     call the last link (1) as a monad     [1,2,...,24!,...,24!^3]
    ⁼           -     equal?
         Ḣ      - head
          ḟ1    - filter out any ones
            ȯ0  - or with zero (for the empty list case)
              F - flatten (to cater for the fact that zero is not yet a list)

Thanks, I also noticed while writing up the explanation

I think inputs such as 125! (written in string notation) should result in outputs such as 5!!. Would this be theoretically supported (e.g. [[5]] instead of [125] as output)?

It is entirely optional, and I have decided to only ever use a single factorial. ("Factorial notation is a must, but you aren't required to use more than one factorial symbol per number.")

Well, tbf, I'm not really clear on you aren't required to use more than one factorial symbol per number...

Seems clear enough to me - we are not required to use it, but can do so if we want.

If you don't mind, why didn't you count the footer? ("ÇŒṘ")

@tuskiomi The footer is just formatting the list output for clarity... as a full program (rather than as a function) the code will print Jelly's format of a list (nothing for empty & no enclosing [] for lists of length 1).

@tuskiomi TIO has limits ;-) but I think it works theoretically.

@tuskiomi the Cartesian power would result in a list of 23!^4 lists. It will run out of time (60s limit on TIO) if not memory.

so wait... did you make an answer to this that runs in n! time?

N!^M where N is the product and M is the number of terms (and in space too!!)

Jelly, 19 bytes
,!P€E
SṗLçÐfµḢḟ1ȯ1F

Try it online!
Quick and dirty. Very slow, even the 23!2!3!2! test case is a stretch. I/O as lists of integers.
Explanation
,!P€E    Helper link. Arguments: attempt, original
,        Make the array [attempt, original].
         Example: [[1,1,1,4], [2,3,2,0]]
 !       Take the factorial of each item.
         Example: [[1,1,1,24], [2,6,2,1]]
  P€     Take the product of each sublist.
         Example: [24, 24]
    E    Check if the values are equal.

SṗLçÐfµḢḟ1ȯ1F   Main link. Arguments: original
S               Find the sum S of the integers in the input.
  L             Find the number N of integers in the input.
 ṗ              Generate all lists containing N integers from 1 to S.
   çÐf          Take the lists whose factorial-product is the same as the original.
       Ḣ        Take the first match. This is the one with the most ones.
        ḟ1      Remove any ones.
          ȯ1    If there were only ones, return a one instead.
            F   Turn into a list if needed.

We may use lists as I/O

@JonathanAllan Oh, that wasn't apparently edited into the OP

My 17 seems even slower...

Oh, it's way too similar - https://tio.run/##y0rNyan8/18xgOtw@8Od030Otz9q3HNo6eEJaUD@jkUPd8w3PLHe4P///8Y6RjpGAA

@JonathanAllan Go ahead and post it, looks different to me even though the algorithm is essentially the same.

Just noticed we both must add some bytes to wrap the edge case in a list :( EDIT - make that one byte, a trailing F will do it.

Clean, 397 ... 317 bytes
import StdEnv,StdLib
c=length
f c m=sortBy c o flatten o map m
%n=f(>)@[2..n]
@1=[]
@n#f=[i\\i<-[2..n]|n/i*i==n&&and[i/j*j<i\\j<-[2..i-1]]]
=f++ @(n/prod f)
?l=group(f(>)%l)
$l=hd(f(\a b=c a<c b)(~(?l))[0..sum l])
~[]_=[[]]
~i n=[[m:k]\\m<-take n[hd(i!!0++[0])..],k<- ~[drop(c a)b\\a<-group(%m)&b<-i|b>a]n|i== ?[m:k]]

Try it online!
This takes an [Int], determines the prime factors of the result, and reduces over the factors to find the smallest representation, using the largest factor at any stage as a baseline value for the next factorial term. It won't complete some test cases on TIO, but it is fairly* fast, and can run them all in under 3 minutes on a midrange laptop.
* for an O((prod(N)!)^sum(N)) complexity algorithm

Testcase: 6, 2, 2

@tsh Fixed now. It wasn't sorting by smallest length, but by largest first member based on a mistaken assumption.

Ruby, 240 237 233 bytes
This is incredibly inefficient
Accepts an array of ints as input
Returns a string and chooses the shortest option between, say, '720!','6!!' and '3!!!'
->i{f=->n{n>0?n*f[n-1]:1}
s=->a{eval a.map{|i|f[i]}*?*}
r=->e,a=[2]{e==s[a]?a:s[a]<=e&&(r[e,a[0..-2]+[a[-1]+1]]||r[e,a+[2]])}
j=->v{v.join(?!)+?!}
u=r[s[i]]
while j[g=u.map{|i|i&&r[i]?[r[i],p]:i}.flatten].size<j[u].size;u=g;end
j[u]}

Try it online!

><>, 66 bytes
1}:?\~l1=?v{!
-:?!\:{*}1
v?( 4:{/}1<o"!"n-1
{:,} :{/?%}:+1
\:1-?n;

Try it online!
Not efficient, doesn't find the smallest string, and the interpreter doesn't deal very well with extremely large numbers. But at least I tried? Takes input as a list of numbers through the -v flag.
First it calculates the value of the input by factorialising each number and multiplying them together. Then it finds the largest factorial that divides cleanly into the total and outputs it. Repeat until it either gets a prime, (which it outputs) or a 1 and exits the program. Because of this, it sometimes doesn't find the shortest representation of the number, for example, the test case 7!2!2!7!2!2!2!2! returns 10!224 instead of 8!8! because it finds the total is divisible by 10! first.


text:
The Eyes are Following You
This is inspired by the excellent Visualize Visual Eyes challenge. It is posted with permission from and credit to @Jordan
We are going to create an ASCII art approximation of the Xeyes challenge but without worrying about the actual mouse movements. Just the positions.
EDIT
I thought about whether this could be seen as a duplicate but I don't believe it is.

The previous question required detecting mouse movement. This does not and so is open to many more languages.This is simple interactive ASCII art which can be attempted in any language.
While the algorithm for the eye movement may be similar, this is in many ways simpler to achieve.
I'm not convinced that any answer given so far to the previous question could be trivially ported to this.
I don't think I am good enough at languages that could answer the previous question to attempt it. I would have a try at this one.

If consensus is that I am wrong then I am happy to delete the question.
I have removed the comment about "interesting answer" as this is intended to be code golf.
Overview
In all cases the mouse position will be represented by an X.
Here are the eyes with no mouse position (cursor is off screen):
/---\ /---\
|   | |   |
| O | | O |
|   | |   |
\---/ \---/

Now let's say your mouse is to the right of the eyes:
/---\ /---\
|   | |   |
|  O| |  O|X
|   | |   |
\---/ \---/

and now at the bottom left:
 /---\ /---\
 |   | |   |
 |   | |   |
 |O  | |O  |
 \---/ \---/
X

and now at the top:
     X
/---\ /---\
| O | | O |
|   | |   |
|   | |   |
\---/ \---/

From this we can see that (in it's simplest case - we could make it a lot more complicated but let's not do that for now) there are 9 different positions for the eyes and nine different positions for the cursor as shown below:
1     2     3
 /---\ /---\
 |123| |123|
4|456| |456|6
 |789| |789|
 \---/ \---/
7     8     9

Position 5 represents no cursor (off screen). The eyes are both looking forward.
The Challenge
Take an integer (or any representation of an integer) between 1 and 9 inclusive and output the eyes if the cursor was in the position of that integer. You must include the X as the position of the cursor (except when it is off screen i.e. the eyes are looking forward - no X).
Rules

Input format is your own choice.
Program or function.
Any amount of leading or trailing whitespace is allowed.
Output must consist only of the characters /\-| and either upper or
lowercase x and o.
Assume that the input will always be valid, i.e. an integer between
1 and 9 inclusive.
Feel free to change the order of the integers if it helps i.e. 2 does
not have to be top and 5 does not have to be no cursor.
Standard loopholes prohibited as usual.
This is code golf. Shortest answer wins.

Test Cases
Note: All test cases use the numbering sequence detailed in the explanation. As stated in the rules, you do not have to use the same number sequence.
Input = 5

/---\ /---\
|   | |   |
| O | | O |
|   | |   |
\---/ \---/

Input = 6

/---\ /---\
|   | |   |
|  O| |  O|X
|   | |   |
\---/ \---/

Input = 2

     X
/---\ /---\
| O | | O |
|   | |   |
|   | |   |
\---/ \---/

Input = 7

 /---\ /---\
 |   | |   |
 |   | |   |
 |O  | |O  |
 \---/ \---/
X

This challenge has been in the sandbox for the last week.

"Shortest answer wins for each language however I reserve the right to accept what I think is the most interesting answer." so a popularity contest?

I'm tempted to vote to close, as this is really just the other challenge with a section removed, and answers from there are easily portable here.

I don’t think this is a duplicate at all.

Question edited to clarify why I do not think this is a dupe.

Even if a solution from the other one could be trivially ported, it would still have to be competitive for this to qualify as a duplicate which is not the case.

Indeed, in Visualize Visual Eyes, you had to calculate for arbitrary mouse positions, so code for comparing deltas is needed. Simply removing this code often won't make a competitive solution here.

Would anyone who agrees that this is not a dupe please vote to reopen otherwise I will delete.

Voted to reopen, there's no reason for this being closed as a duplicate. @Closevoters: By your reasoning we would have to close every pure kolmogorov challenge as a duplicate in favor of the "Hello, World!" challenge which doesn't make much sense..

Interesting that @Jordan who posted the original challenge has the most upvotes in comments for stating that this is not a duplicate.

BTW, I'm not convinced this is a kolmogorov challenge. The spaces to the left and above depend on the input if you want them to (stated in the rules - Any amount of leading or trailing whitespace is allowed). I didn't add that tag and am going to remove it. If the challenge is reopened and anyone disagrees please feel free to add it with justification of my misunderstanding of kolmogorov.

Clean, 253 bytes
import StdEnv
?n=flatlines[[if([(0,0),(6,0),(12,0),(0,3),(0,9),(12,3),(0,6),(6,6),(12,6)]!!(n-1)==(v,u))'X'b\\b<-[' ':a++a]&v<-[0..]]\\a<-[spaces 6,['/---\\ ']]++[['|':[if(n==i)'0'' '\\i<-[j..j+2]]]++['| ']\\j<-[1,4,7]]++[['\\---/ '],spaces 6]&u<-[0..]]

Try it online!
This is mostly a port from my answer to the other question.

I am a bit disappointed that someone would post an answer, accept the upvotes (including mine simply because it works) and then vote to close as a dupe. No personal attack intended. It just surprises me that members of this community think it is fair to enhance their own rep while denying other members who may want to try the challenge the chance  to do so. No problem if you think it is a bad challenge or a duplicate. Just vote to close but don't answer first and then vote to close. Just vote to close if you feel that strongly or post and don't vote to close. You can't have it both ways.

@ElPedro I admit I hadn't thought about the double standard my actions have created, I only considered each separately. I will not do it again. Additionally, I will delete my answer if you desire.

Please do not delete. I accept your comments and you are still winning ☺

J, 119 112 bytes
d=.y-1
a=.'O'(d{,{;~2+i.3)}7 6$42$'       /---\ |   | |   | |   | \---/'
' '(<3 6)}'X'(d{,{(;+:)3*i.3)}a,.a,.' '

Try it online!

The eyes are good but I don't see the X representing the mouse position. Guess it doesn't really matter as it has been closed as a dupe anyway.

@ElPedro - I'm sorry, apparently I've missed this part of the challenge after looking the other two (then) solutions.
I don't think it's a duplicate.

No prob and thanks. Get the "X" (or "x") in there then +1 (if it gets reopened) :)

Ok, it is reopened

I updated the solution with the required 'X'

Then you get +1 ☺

Perl 5, 150 140 bytes
$x=shift;$_='9     8     7
 /---\ /---\
 09870 09870
606540';$t=reverse;y/98764/12346/;$_.=" $t";s/(\d)$x(.)/\1O\2/g;s/$x/X/;y/0-9/| /;say

Try it online!
Explanation
$x = shift;  # Shift the first value off the input argument array.
# Assign template string to default pattern-search variable.
# Only use first half of output. Use 0 instead of |.
$_ = '9     8     7
 /---\ /---\
 09870 09870
606540';
$t = reverse;  # $t is the reverse of $_.
y/98764/12346/;  # Correct digits in first half of template string $_,
                 # so 9 becomes 1, 8 becomes 2 etc.
$_ .= " $t";  # Append the two halves of the template.
s/(\d)$x(.)/\1O\2/g;  # Regexp replace all occurrences of $x, preceded by
                      # a digit and followed by any non-newline character,
                      # by "O" and the original surrounding characters.
s/$x/X/;  # Replace last remaining occurrence of $x by "X".
y/0-9/| /;  # Replace 0 by |, and all other remaining digits by a space.
say  # Print $_ followed by a newline.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Gerrymandering with Logic Gates
The majority function is a boolean function which takes three boolean inputs and returns the most common. For instance if maj(x,y,z) is the majority function and T denotes true and F denotes false then:
maj(T,T,T) = T
maj(T,T,F) = T
maj(T,F,F) = F
maj(F,F,F) = F

This question concerns writing boolean functions as compositions of majority functions. An example of a 5-ary composition of majority functions is (x1,x2,x3,x4,x5) => maj(x1,x2,maj(x3,x4,x5)). This function returns the following output on these sample input vectors:
(T,T,F,F,F) => maj(T,T,maj(F,F,F)) = maj(T,T,F) = T
(T,F,T,T,F) => maj(T,F,maj(T,T,F)) = maj(T,F,T) = T
(T,F,T,F,F) => maj(T,F,maj(T,F,F)) = maj(T,F,F) = F
(F,F,F,T,T) => maj(F,F,maj(F,T,T)) = maj(F,F,T) = F

Task
Write a program which inputs a positive integer n and a list of length n vectors of booleans and outputs a tree of majority gates that returns true on all of the given vectors if possible.  The function may return either true or false on vectors not in the list of constraints.

The list of vectors may be input in any format you like. If you prefer, instead of inputting the vector, you may input the list of true positions in the vector. So for instance, [TTF,TFT,FTT] or [[T,T,F],[T,F,T],[F,T,T]] or [[1,2],[1,3],[2,3]] (list of true positions) are all fine.
Output can be any valid tree format. For instance, maj(maj(x1,x2,x3),x4,x5) works. You will probably want to use single numbers as stand-ins for variables, as in [[1,2,3],4,5]. Reverse polish 123m45m is also okay, for instance.
If there is no function that works, your program should generate an error or output a falsey value.
If there are multiple functions that work, your program can return any of them. The function does not need to be simplified. For instance, maj(x1,x1,x2) or x1 are equivalent.

Scoring
This is code golf: Shortest solution in bytes wins.
Test cases:
Note that there are many possible outputs for each of these cases, so you should write a checker script that converts your output to a function and check that your function returns true on each of the specified input vectors.
Input: 3, [TFF]
Output: 1 or [1,1,2] or [1,[1,2,2],[1,1,3]] or other equivalent

Input: 3, [TFF,FTF]
Output: Falsey or error (it's not possible)

Input: 3, [TTF,TFT]
Output: [1,2,3] or 1 or other equivalent

Input: 3, [TTF,TFT,FTT]
Output: [1,2,3] or [1,3,2] or other equivalent

Input: 4, [TTFF,TFTF,FFTT]
Output: Falsey or error

Input: 4, [TTTF,TTFT,TFTT,FTTT]
Output: [1, 2, 3] or [2,3,4], or many other options

Input: 5, [TTTFF,FTTFT,TFFFT]
Output: [1,[1,[1,2,5],[2,4,5]],3] or many other options

Input: 6, [TTTFFF,FTFTTF,TFFTFT]
Output: [1, 2, 4] or [1, [1, 2, 4], [2, 3, 4]] or others

Input: 5, [TTTFF,TTFTF,TTFFT,TFTTF,TFTFT,TFFTT,FTTTF,FTTFT,FTFTT,FFTTT]
Output: [[1, [1, 3, 5], 4], [1, 2, [2, 4, 5]], [2, 3, [3, 4, 5]]] or others

Input: 7, [TTTTFFF,TTTFTFF,TTTFFTF,TTTFFFT,TTFTTFF,TTFTFTF,TTFTFFT,TTFFTTF,TTFFTFT,TTFFFTT,TFTTTFF,TFTTFTF,TFTTFFT,TFTFTTF,TFTFTFT,TFTFFTT,TFFTTTF,TFFTTFT,TFFTFTT,TFFFTTT,FTTTTFF,FTTTFTF,FTTTFFT,FTTFTTF,FTTFTFT,FTTFFTT,FTFTTTF,FTFTTFT,FTFTFTT,FTFFTTT,FFTTTTF,FFTTTFT,FFTTFTT,FFTFTTT,FFFTTTT]
Output: [[[1, [1, [1, 4, 7], 6], 5], [1, [1, 3, [3, 6, 7]], [3, 5, [5, 6, 7]]], [3, 4, [4, [4, 5, 7], 6]]], [[1, [1, [1, 4, 7], 6], 5], [1, 2, [2, [2, 5, 7], 6]], [2, [2, 4, [4, 6, 7]], [4, 5, [5, 6, 7]]]], [[2, [2, [2, 4, 7], 6], 5], [2, 3, [3, [3, 5, 7], 6]], [3, [3, 4, [4, 6, 7]], [4, 5, [5, 6, 7]]]]]

"5-ary composition of majority functions is (x1,x2,x3,x4,x5) => maj(x1,x2,maj(x3,x4,x5))" how? What the answer should be if x1=x2=F; x3=x4=x5=T; ?

I will add a truth table.

@tsh Does my edit clarify what the function does?

maybe i misunderstood the question. seems fine

What does an output of 1 mean?

Suggested title: Gerrymandering with logic gates

1 represents x1 so the function is projection onto the first element (x1,x2,x3) => x1.

can Input: 6, [TTTFFF,FTFTTF,TFFTFT] return [1, 2, 4]? I ask because you have listed other outputs for the other inputs

Yes, that's a valid output, sorry that was an oversight.

The longer solution I posted was just the one my solver found.

I'm assuming that in addition to returning true for all the specified vectors, the output should also return false for all other vectors? Worth making it explicit in the spec either way

@trichoplax No, the output on all remaining vectors can be anything. I will update to make that explicit.

JavaScript (ES6), 260 bytes
Takes input as an array of arrays of booleans. Returns a tree of 1-indexed majority gates or throws a recursion error (1) if no solution exists.
The main function f() recursively attempts to find a solution by calling the solver F() and incrementing the maximum nesting level m at each iteration.
(1) after a long time, and assuming infinite memory
f=(a,m)=>(F=(a,d,I=a[i=0].map(_=>++i),g=(a,b)=>b[1]?b.reduce((s,i)=>s+g(a,i),0)>1:a[b-1])=>I.find(i=>a.every(a=>g(a,i)))||d&&(I.reduce((a,x)=>[...a,...a.map(y=>[...y,x])],[[]]).some(b=>r=b.length==3&&F(a.map(a=>[...a,g(a,b)]),d-1,[...I,b]))&&r))(a,m)||f(a,-~m)

Demo

f=(a,m)=>(F=(a,d,I=a[i=0].map(_=>++i),g=(a,b)=>b[1]?b.reduce((s,i)=>s+g(a,i),0)>1:a[b-1])=>I.find(i=>a.every(a=>g(a,i)))||d&&(I.reduce((a,x)=>[...a,...a.map(y=>[...y,x])],[[]]).some(b=>r=b.length==3&&F(a.map(a=>[...a,g(a,b)]),d-1,[...I,b]))&&r))(a,m)||f(a,-~m)

test = a => console.log(JSON.stringify(f(a.split(',').map(s => [...s].map(c => c == 'T')))))

test('TFF')
test('TTF,TFT')
test('TTF,TFT,FTT')
test('TTTF,TTFT,TFTT,FTTT')
test('TTTFF,FTTFT,TFFFT')
test('TTTFFF,FTFTTF,TFFTFT')
test('TTTFF,TTFTF,TTFFT,TFTTF,TFTFT,TFFTT,FTTTF,FTTFT,FTFTT,FFTTT')

Example
Below is a validation table of the solution found for the last test case of the demo.
12345 | [5,[1,2,4],[3,4,[1,2,3]]]
------+-------------------------------------------------------------
TTTFF | [F,[T,T,F],[T,F,[T,T,T]]] --> [F,T,[T,F,T]] -> [F,T,T] --> T
TTFTF | [F,[T,T,T],[F,T,[T,T,F]]] --> [F,T,[F,T,T]] -> [F,T,T] --> T
TTFFT | [T,[T,T,F],[F,F,[T,T,F]]] --> [T,T,[F,F,T]] -> [T,T,F] --> T
TFTTF | [F,[T,F,T],[T,T,[T,F,T]]] --> [F,T,[T,T,T]] -> [F,T,T] --> T
TFTFT | [T,[T,F,F],[T,F,[T,F,T]]] --> [T,F,[T,F,T]] -> [T,F,T] --> T
TFFTT | [T,[T,F,T],[F,T,[T,F,F]]] --> [T,T,[F,T,F]] -> [T,T,F] --> T
FTTTF | [F,[F,T,T],[T,T,[F,T,T]]] --> [F,T,[T,T,T]] -> [F,T,T] --> T
FTTFT | [T,[F,T,F],[T,F,[F,T,T]]] --> [T,F,[T,F,T]] -> [T,F,T] --> T
FTFTT | [T,[F,T,T],[F,T,[F,T,F]]] --> [T,T,[F,T,F]] -> [T,T,F] --> T
FFTTT | [T,[F,F,T],[T,T,[F,F,T]]] --> [T,F,[T,T,F]] -> [T,F,T] --> T

There is an efficient solution, which hopefully someone will find. In the meantime, I guess brute force sort of works...

Mathematica, 121 bytes
An anonymous function which takes its second argument as a list of the lists of true positions in the vector of booleans.
f[n_][s_]:=If[n<3,(Intersection@@s)[[1]],{#/. 2->1,#2/.{2->1,3->2},#3}&@@(1+f[n-1]/@(s-1/.{{0->1},{1->2,0->1},{0->2}}))]

Formatted slightly nicer:
f[n_][s_] := If[n < 3, (Intersection @@s)[[1]],
   {# /. 2 -> 1, #2 /. {2 -> 1, 3 -> 2}, #3} & @@
    (1 + f[n - 1] /@ (s - 1 /. {{0 -> 1}, {1 -> 2, 0 -> 1}, {0 -> 2}}))]

\$\def\maj{\mathrm{maj}}\def\T{\mathrm{True}}\def\F{\mathrm{False}}\$
If there are fewer than three variables, intersect the constraint vectors to see if there is a common "True" in all of the constraints. If there is one, then the constant function (x_1,x_2) --> x_i works, otherwise it is impossible (and will throw an error by trying to take the first element of an empty list).
Otherwise, substitute \$f_1=f(x_1,x_1,x_2,x_3,\ldots,x_{n-1})\$, \$f_2=f(x_1,x_2,x_2,x_3,\ldots,x_{n-1})\$, and \$f_3=f(x_1,x_2,x_1,x_3,\ldots,x_{n-1}))\$, recursively solve each of these, then set \$f=\maj(f_1(x_1,x_3,x_4,\ldots,x_n), f_2(x_1,x_2,x_4,\ldots,x_n),f_2(x_2,x_3,x_4,\ldots,x_n))\$.
Explanation:
This is a recursive algorithm that reduces the problem of finding a solution of an \$n\$ variable problem to finding three solutions to \$n-1\$ variable problems. The key observation that makes this work is that for \$f\$ one of the functions we are looking for we have:
\$f(x_1,\ldots,x_n)=\maj(f(x_1,x_1,x_3,x_4,\ldots,x_n),f(x_1,x_2,x_2,\ldots),f(x_3,x_2,x_3,\ldots))\$
In the first position, we replaced \$x_2\$ with \$x_1\$, in the second position \$x_3\$ with \$x_2\$ and in the third position \$x_1\$ with \$x_3\$.
Once you know this identity, the algorithm is clear: when there are two or fewer variables, the problem is trivial. Otherwise, recursively solve the three problems of representing \$f(x_1,x_1,x_3,x_4,\ldots,x_n)\$, \$f(x_1,x_2,x_2,x_4,\ldots,x_n)\$, and \$f(x_3,x_2,x_3,x_4,\ldots,x_n))\$ and take the majority of them.
Why is this true? Well the majority function satisfies two properties:

It is "complementary". That is, if \$!x\$ is the negation of \$x\$, then \$\maj(!x,!y,!z)=!\maj(x,y,z)\$. As a consequence, every function we can build out of the majority function is complementary.

It is monotonic. That is, \$\maj(x,y,\F)\leq \maj(x,y,\T)\$. In general, if we say that \$\F\leq \T\$ and say \$(x_1,\ldots,x_n)\leq (y_1,\ldots, y_n)\$ if \$x_i\leq y_i\$ for all \$i\$, then I say a function \$f\$ is monotonic if \$(x_1,\ldots x_n)\leq(y_1,\ldots, y_n)\$ implies \$f(x_1,\ldots x_n)\leq f(y_1,\ldots, y_n)\$. The composition of monotonic functions is monotonic so every function we can build out of the majority function is monotonic.

It turns out that complementary monotonic functions are exactly the class of functions that can be built out of majority gates.
Now, we show that for \$f\$ a complementary monotonic function, our identity holds:
\$f(x_1,\ldots,x_n)=\maj(f(x_1,x_1,x_3,x_4,\ldots,x_n),f(x_1,x_2,x_2,x_4,\ldots,x_n),f(x_3,x_2,x_3,x_4,\ldots,x_n))\$
Let's set \$f_1(x_1,x_2,x_3,\ldots,x_n)=f(x_1,x_1,x_3,x_4,\ldots,x_n)\$, \$f_2(x_1,\ldots,x_n)=f(x_1,x_2,x_2,x_4,\ldots,x_n)\$ and \$f_3(x_1,\ldots,x_n)=f(x_3,x_2,x_3,x_4,\ldots,x_n)\$. To show that \$f=\maj(f_1,f_2,f_3)\$, we need to show that for any input, at least two of \$f_1\$, \$f_2\$, and \$f_3\$ are equal to \$f\$. We divide up into cases based on the values of \$x_1\$, \$x_2\$ and \$x_3\$. If \$x_1=x_2=x_3\$ then \$f_1=f_2=f_3=f\$.
Suppose not all of \$x_1\$, \$x_2\$, and \$x_3\$ are the same. By permuting the variables of \$f\$, we can assume that \$x_1=x_2\$ and \$x_3\$ is different and because \$f\$ is complementary, it suffices to deal with the case \$x_1=x_2=\F\$ and \$x_3=\T\$. In this case, \$(x_1,x_1,x_3)=(\F,\F,\T)=(x_1,x_2,x_3)\$, \$(x_1,x_2,x_2)=(\F,\F,\F)\leq (x_1,x_2,x_3)\$ and \$(x_3,x_2,x_3)=(\T, \F, \T) \geq (x_1,x_2,x_3)\$. By monotonicity we deduce that \$f_2\leq f_1=f\leq f_3\$. If \$f=\F\$ then \$f_2\leq \F\$ implies \$f_2=\F=f\$ and if \$f=\T\$ then \$f_3\geq \T\$ implies \$f_3=\T\$. Thus, at least two of \$f_1\$, \$f_2\$, and \$f_3\$ are equal to \$f\$ in all cases so \$f=\maj(f_1,f_2,f_3)\$.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Alternatively shift columns and rows of a 2D array
Objective
Given a 2D array of any size, write a program or function to shift alternatively the columns and rows
Example
a b c d e
f g h i j
k l m n o

All elements in the first column shift down one row, the second column shift up one row, the third shift down one row and so on, wrapping when they reach the edge.
k g m i o
a l c n e
f b h d j

All elements in the first row shift to the right, the second to to the left, the third to the right etc., wrapping when they reach the edge.
o k g m i
l c n e a
j f b h d

I will follow the tradition of selecting the shortest working code as the best answer

Can the array be any size, or specifically 3x5?

i was looking for any filled 2D array. sorry for not mentioning it. Ill add an edit

To be honest, the improper formatting makes the question look as if it was an off-topic question from a lazy SO user.

(BTW, don't accept an answer too soon)

I apologise for that. Please feel free to edit it and properly format it

@kshishoo Welcome to PPCG, I've made minor edits on the question, feel free to rollback if you don't agree with them.

@rod Your edits were quite helpful, i will try and keep the same format in mind should i post other questions/challenges

@kshishoo For future challenges you can use the Sandbox  to check for duplicates and/or gather some feedback before posting on main site

but i not see the test cases... where are? the ii Matrix it is a test case?

It's frowned upon to accept an answer so quickly.

@EriktheOutgolfer my apologies. i thought 48 hours would be enough, How long should i leave the question up before selecting an answer. (i can also still unselect the best answer and wait)

@kshishoo I'd wait a week, but I'd recommend not accepting an answer at all, that could discourage some people from answering after an answer has been accepted.

Husk, 7 bytes
‼ozṙİ_T

Try it online!
Explanation
‼ozṙİ_T  Implicit input: a list of lists.
‼        Do this twice:
      T   Transpose,
 oz       then zip with
    İ_    the infinite list [-1,1,-1,1,-1,1,..
   ṙ      using rotation. This rotates the rows in alternating directions.

MATL, 13 bytes
,!tZy:oEq2&YS

Try it online!
Explanation
,        % Do twice
  !      %   Transpose. Takes input implicitly the first time
  t      %   Duplicate
  Zy     %   Size. Gives a vector with numbers of rows and of columns
  :      %   Range from 1 to the first entry of the vector (number of rows)
  o      %   Parity: gives 0 or 1 for eacn entry
  Eq     %   Times 2, minus 1: transforms 0 into -1
  2      %   Push 2
  &YS    %   Circularly shift along the second dimension. This shifts the
         %   first row by 1 (that is, to the right), the second by -1 (to
         %   the left), etc.
         % End (implicit). Display (implicit)

J, 26, 21 19 bytes
-5 bytes thanks to miles
(|."_1~_1^#\)@|:^:2

Explanation:
^:2 - repeate twice the following:
@|: - transpose and
#\  - find the length ot the prefixes (1, 2, 3 ... rows)
_1^ - raise -1 to the above powers, creating a list of alternating -1 1 -1 1...
|."_1~ - rotate each row of the input array with offset from the above list
Try it online!
Original version:
(($_1 1"0)@#|."0 1])@|:^:2

How it works
^:2 - repeate twice the following:
|: - transpose and
|."0 1] - rotate each row of the input array, offsets in the list:
@# - the number of rows in the array
($_1 1"0) - alternate _1 1 (3 -> _1 1 _1)
Try it online!

You can generate the _1 1.. using (|."_1~_1^2|#\)@|:^:2 also

@miles Thanks, that's a great piece of code!

@miles in fact I don't need the 2| part

Yes, you actually don't, that's another 2 bytes saved.

Wolfram Language (Mathematica), 55 bytes
Nest[MapIndexed[RotateLeft[#,(-1)^#2]&,Thread@#]&,#,2]&

Try it online!

Python 2, 83 bytes
x=input()
exec'x=[l[i%2*2-1:]+l[:i%2*2-1]for i,l in enumerate(zip(*x))];'*2
print x

Try it online!

APL+WIN, 30 bytes
Prompts for screen input of a 2d array
((↑⍴m)⍴¯1 1)⌽((1↓⍴m)⍴¯1 1)⊖m←⎕

JavaScript (ES6),  116  76 bytes
m=>(g=m=>m[0].map((_,x)=>m.map(_=>m[y++%h][x],h=m.length,y=x&1||h-1)))(g(m))

Try it online!
Commented
m => (                 // m[] = input matrix
  g = m =>             // g is the main helper function taking a matrix m[]
    m[0].map((_, x) => // for each column at position x in m[]:
      m.map(_ =>       //   for each row of m[]:
        m[y++ % h][x], //     yield the x-th value of the row (y mod h) and increment y
        h = m.length,  //     h = number of rows
        y = x & 1      //     start with y = 1 if x is odd,
            || h - 1   //     or h - 1 if x is even
      )                //   end of inner map()
  )                    // end of outer map()
)(g(m))                // invoke g twice on the input matrix

APL (Dyalog Unicode), 26 bytes
{(¯1 1⍴⍨≢⍵)⌽(¯1 1⍴⍨≢⍉⍵)⊖⍵}

Try it online!
Prefix Dfn.
How?
{(¯1 1⍴⍨≢⍵)⌽(¯1 1⍴⍨≢⍉⍵)⊖⍵}⍝ Main function, prefix. Input matrix is ⍵.
                        ⊖⍵}⍝ Rotate the columns of ⍵ according to the left arg:
            (       ⍉⍵)    ⍝ Transpose ⍵ (makes a 3x5 matrix become 5x3)
                   ≢       ⍝ Tally (yields the number of rows of the matrix)
                  ⍨        ⍝ Swap arguments of the following fn/op
                 ⍴         ⍝ Shape
             ¯1 1          ⍝ This vector. This yields a vector of ¯1 1 with size = number of columns of ⍵.
          ⌽                ⍝ Rotate the rows of ⍵ according to the left arg:
{(¯1 1⍴⍨≢⍵)                ⍝ Does the same as the preceding expression, without transposing ⍵.

APL (Dyalog Unicode), 15 bytes (SBCS)
{⍵⌽⍨¯1*⍳≢⍵}∘⍉⍣2

Try it online!

JavaScript (ES6), 94 91 bytes
a=>(g=a=>a[0].map((_,i)=>(b=a.map(a=>a[i]),i%2?[...b.slice(1),b[0]]:[b.pop(),...b])))(g(a))

There's probably a golfier way to do the rotation...

Pyth, 15 bytes
L.e.>b^_1k.Tbyy

Try it online
Explanation
L.e.>b^_1k.Tbyy
L           b      Define a function on a list...
          .T       ... which transposes it...
 .e.>b^_1k         ... and rotates each row alternating left and right.
             yyQ   Apply twice to the (implicit) input array.

q/kdb+, 32 bytes
Solution:
{rotate'[#:[x+:]#-1 1](+)x}/[2;]

Example:
q)3 5#.Q.a / reshape "a..o" into 3 row, 5 column grid
"abcde"
"fghij"
"klmno"
q){rotate'[#:[(+)x]#-1 1](+)x}/[2;]3 5#.Q.a
"okgmi"
"lcnea"
"jfbhd"

Explanation:
Flip the grid in order to apply rotation to columns, the second iteration flips once again thus the rotation is applied to the rows on the second pass.
Rotation is based a the list -1 1 -1 1.. of the length of the row/column being rotated.
A healthy 9 bytes have been golfed off from this easier-to-read version
{rotate'[count[flip x]#-1 1;flip x]}/[2;] / ungolfed solution
{                                  }/[2;] / perform lambda 2 times
 rotate'[                  ;      ]       / perform rotate on each-both
                            flip x        / flip x<->y of grid
                      #-1 1               / take from list -1 1
         count[flip x]                    / the length of the flipped grid

Jelly, 10 bytes
ZJ-*ṙ"@Zµ⁺

Try it online!

Clean, 93 bytes
import StdEnv,StdLib
k=[0,1:k]
^l=[[[last a:init a],tl a++[hd a]]!!b\\a<-transpose l&b<-k]

^o^

As a partial function literal, that happens to look like a face.
Try it online!

05AB1E, 14 bytes
2FøvyNÉiÀëÁ}})

Try it online!
Explanation
2F               # 2 times do:
  ø              # zip
   vy            # for each row(y), index(N) do:
     NÉiÀ        # if N is odd, rotate left
         ëÁ      # else rotate right
           }}    # end if and inner loop
             )   # wrap in list

APL NARS, 36 bytes, 18 chars
c←b∘b←{⍵⌽⍨-×-\⍳≢⍵}∘⍉

This {⍵⌽⍨-×-\⍳≢⍵} would rotate each row of the matrix argument follow the vector -1 1 -1 1 etc(that has its vector length the length of the argument matrix rows).  Test:
  ⎕←a←3 5⍴⎕A
ABCDE
FGHIJ
KLMNO
  ⎕←c a
OKGMI
LCNEA
JFBHD

Let us continue this discussion in chat.

bash et al, 84
Non-competing shell solution.
This is based around a function that alternates the direction of the rotation of the rows. The same procedure done on the transposed array will rotate the columns. For example transpose | rotate | transpose | rotate.
The alternating rotation can be done on single character arrays with sed like this:
sed -E 's/(.*) (.)$/\2 \1/; n; s/^(.) (.*)/\2 \1/'

The transposition can be done with rs or datamash:
rs -g1 -T
datamash -t' ' transpose

Taken together:
r() { sed -E 's/(.*) (.)$/\2 \1/; n; s/^(.) (.*)/\2 \1/'; }
t() { rs -g1 -T; }
<f t | r | t | r

Output:
o k g m i
l c n e a
j f b h d

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Regrowing trees
Background
Here you have another work-inspired challenge, but from my wife's work in this case. Imagine you have a service that returns the list of nodes in a tree structure (much like the files and folders in a file system), but in no particular order. For every node you get a tuple with its name and the name of its parent.
So if you get [["C","B"],["D","C"],["A",""],["B","A"]] (format: [NodeName,ParentName]), you could rebuild the tree structure and get a leaf with the path /A/B/C/D (A has no parent, then it is at the top level, then B is a child of A, C is a child of B and D is a child of C).
You could also get [["C","B"],["D","C"],["A",""],["B","A"],["E","B"]], so the rebuilt tree would contain two leaves: one with the path /A/B/C/D (the same as in the previous example) and a new one with the path /A/B/E as the node E has B as its parent. Note that the nodes in the list are not duplicated (the leaves D and E have parts of their paths coincident but the common parts do not appear twice in the original list of nodes).
Challenge
Given a list of nodes as described above, rebuild the tree and output the paths for all the leaves in the tree structure, in no particular order as long as you return them all.
Rules

The input will be a list of tuples with two elements each: the name of the current node and the name of its parent. If you don't like strings you can use arrays of chars. You can choose the order of the elements in the tuple (the node name first or the parent name first).
The output format can be: a list of paths as strings like ["/A/B/C/D","/A/B/E"] for the second example; a list of path nodes for each leaf, as in [["A","B","C","D"],["A","B","E"]] for the same example; or even a dictionary (something like ["A":["B":["E":[],"C":["D":[]]]]]). Or you can just print the list of paths to STDOUT.
There won't be nodes without a parent given explicitly.
The node names will be strings of alphanumeric ASCII characters [a-zA-Z0-9] of any length. So you can use any other printable ASCII character as separator if you decide to print or return the paths as strings.
There won't be duplicated tuples in the list.
There won't be cyclic paths in the list of nodes.
The node names are unique and case sensitive. Nodes aa and AA are not the same node.
If you get an empty list of nodes, return an empty list/dictionary of leaves (or just print nothing).

Test cases
In:  [["C","B"],["D","C"],["A",""],["B","A"],["E","B"]]
Out: /A/B/C/D
     /A/B/E
Alt: [["A","B","C","D"],["A","B","E"]]
Alt: ["A":["B":["E":[],"C":["D":[]]]]]

In:  [["D3","D8"],["D5","d1"],["s2","S1"],["S1",""],["d1",""],["D8","D5"],["F4","s2"],["F7","S1"],["e3","D5"]]
Out: /d1/D5/D8/D3
     /d1/D5/e3
     /S1/s2/F4
     /S1/F7
Alt: [["d1","D5","D8","D3"],["d1","D5","e3"],["S1","s2","F4"],["S1","F7"]]
Alt: ["d1":["D5":["e3":[],"D8":["D3":[]]]],"S1":["F7":[],"s2":["F4":[]]]]

In:  [["Top",""]]
Out: /Top
Alt: [["Top"]]
Alt: ["Top":[]]

In:  []
Out:
Alt: []
Alt: []

This is code-golf, so may the shortest code for each language win!

This comes from the sandbox (for those who can see deleted posts).

"The output format depends on you, as long as the paths for each leaf can be reconstructed" - doesn't that apply to the input and therefore allow a no-op?

@JonathanAllan The input will be a list of tuples with two elements each: the name of the current node and the name of its parent. no, I don't think so (btw I actually feel like this challenge is a no-op in general, but I'm not sure)

@EriktheOutgolfer the task is to "output the paths for all the leaves in the tree structure", which I think is the same as "reconstructing the paths for each leaf".

@JonathanAllan in fact, I think you're right, I didn't think of that. I'll try to change that sentence. UPDATE: I have limited the output formats, fortunately the current existing answer uses the dictionary option.

Can I take an n x 2 where each row is a pair?

@Giuseppe yes, you can.

Can I take the input as a dictionary from child to parent?

@Mnemonic mmm no, no dictionaries on input, sorry.

Is invalid input handling considered? e.g. [["C","B"],["C","A"],["A",""],["B","A"]] (making C a child of both B and A) or [["C","B"],["A","C"],["B","A"]] (making a cyclic).

@Draco18s no, you don't have to worry about those cases.

Haskell, 53 bytes
(""#)
e[]=[[]]
e a=a
p#l=[s:c|(q,s)<-l,p==q,c<-e$s#l]

Try it online!
Takes input as a pair (parent,child) because I find that order easier to read. Output is the "list of lists of strings" style.
The # operator takes a parent name on the left and the list of nodes on the right. First it iterates through the nodes that have that parent. Then it recurs, looking for that node's children and prepending the node to the list. If it has no children e will put in an empty list to terminate the sublist (otherwise nothing would ever get added to the output).
This code assumes that node names are unique which I thought must be the case because if there were two nodes like /foo/bar/baz and /bar/baz it would be impossible to tell where to put "baz".

You're right, node names are unique, I'll add that to the question. Nice answer!

JavaScript (ES6), 59 bytes
a=>a.map(([c,p])=>g(p)[c]=g(c),g=s=>g[s]||(g[s]={}))&&g['']

Returns undefined if there are no top-level nodes. (+4 bytes to return an empty dictionary.)

Pyth, 21 bytes
J.dQVf!}T_JJNWN=N@JNN

If we could take a dictionary, we could drop the first 4 bytes and replace the Js with Qs.
Try it online
Explanation
J.dQVf!}T_JJNWN=N@JNN
J.dQ                    Convert the input to a dictionary and call it J.
     f!}T_JJ            Find the leaves (the keys of J that aren't values).
    V       N           For each leaf, print the label...
             WN=N@JNN   ... and climb the tree, printing along the way.

Ruby 87 75 bytes
->d{k=d.flatten;k.map{|i|k.count(v=i)<2&&loop{v=(d.assoc(p v)||break)[1]}}}

inspired by this answer
Try it online!


text:
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 code-golf, so the shortest code in bytes for each language wins.

Sandbox link

Can we take input as a list of three digits (0-9)?

@HyperNeutrino As long as 3 digits are inputted into your method/function, you can do whatever form you please.

...and this is why meeting rooms should have names.

@JonathanAllan It's a lot harder for new people to find "Dolphin Room" than "Room 218" (assuming that room numbers are assigned in order). A compromise would be alphabetically ordering the names, but then you only have 26.

How does 963->936 count as a single digit mistake?  That's a transposition error.

@KellyLowder should have been 933 so I've fixed it up.

@JonathanAllan I'll schedule a meeting in the Allegheny room. You know where that is...right? ;)

@Draco18s Not yet, and neither would I if it were a number. Names have more redundancy making for more robust communication, so unless the layout is like a hotel names make more sense.

@JonathanAllan There's a hotel I've been in a number of times (for conventions) and I always need to go to the map to find those conference rooms. They aren't even arranged in a sensible manner (ie alphabetically) and are spread across two floors. Every other place is a room-by-number which encodes its location within it (assuming you're in the right building). But yes, it is much harder to corrupt a room's name than you are its number.

Related, I once worked in IT where there was a professor who had trouble with the room technology several weeks running. He was in Bradley 210 (which I knew, Bradley being the name of the building. The building next door--Matheson--was connected via a sky bridge on the 3rd floor. Bradley was 5 stories tall, Matheson 4). He could never tell me what room he was in correctly. One time he told me he was in "Matheson 605" which patently didn't exist, and got none of the digits right.

@Draco18s I once worked in a place, with professors, and a building called Matheson, and a sky bridge on the 3rd floor between 2 buildings (where buildings had differing somewhat strange numbering since they were built into a hill), and I had to go back and see if we worked at the same place (no Bradley building where I was haha).

@briantist No hill at where I was, and I honestly forgot the name of the other building. Tried to look it up, failed, grabbed a random name (as it wasn't actually important). >> Also the Matheson building has been gone for several years now. FWIW, my place was Drexel University.

@Draco18s yeah definitely not the same place, but it was a funny set of coincidences :-p

@briantist Indeed! :D

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!

One could also use other distance functions such as DamerauLevenshteinDistance instead of EditDistance which would also include transposition errors.

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]

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

Try it online!

28 bytes in the same version as you're using or 27 bytes in the rewrite.

R, 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!

a whole bunch of little things: you have an extra space in the second line; abusing the precedence of : over */+- can shave off a few bytes in the first line, getting rid of do.call, treating a as a matrix and transposing it saves all around 39 bytes: Try it online!

You are good at this! Thanks for the feedback.

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!

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

Some small things to golf. (String b)-> can be just b->, and you can remove the trailing ;. As for actual things to golf: You only use a once, so you can remove String[]a=...; and use "12,024,0135,26,157,2468,359,48,579,68".split(",")[...] directly. Also, Byte.parseByte can be new Byte.  In total: 177 bytes.

@KevinCruijssen thanks, those are some tricks I'll have to learn :)

Tips for golfing in Java and Tips for golfing in  might be interesting to read through in case you haven't yet. :)

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 0s 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>

I see this [for(...)] in a lot of code golfs, but I don't fully understand it, and I can't seem to find it in any documentation. Could you explain it or post a link to an explanation?

save 6 bytes [...[12,240,1350,26,157,2468,359,48,579,78][c]+'']

@AntonBallmaier [for(...)] was one of several array comprehension syntax proposals that never made it into ECMAscript. It allowed you to loop over an iterator and succinctly filter and/or map over the results. (I found it particularly useful when doing double iteration.)

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!

@ceilingcat Hm. TiO says 108 bytes.

I don’t think TIO counts UTF-8 bytes correctly in C. Try changing the language to bash or something else and watch the byte count change.

@ceilingcat Yeah, was wonky locally too. Saved file is 114, true enough.

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!

Save 4 bytes with: in`0x134cd9a07d1e58feab643f7db24102`[int(v)::10] (I tried int('…',36) too but it’s one byte longer.)

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

Try it online!
-1 thanks to Jonathan Allan.
Explanation being updated...

I honestly have no clue about how this is parsed, let alone how it works. An explanation would be greatly appreciated.

@cairdcoinheringaahing sorry, no time now

-1 byte: Wẋ3 -> ḷþ

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+10jth 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).

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.

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)

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

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


text:
Enumerate an array, grouping duplicates
The objective of this challenge is to take an array of positive integers, and enumerate its indices, grouping like elements.
An enumeration without any duplicates is done by just outputting an array of pairs (value, index), for example, [3, 4, 13, 9, 2] => [[3,1],[4,2],[13,3],[9,4],[2,5]].
However, if a given element appears a second time, it isn't given its own pair, but is instead added to the group of its first occurrence. If in our above example we replaced the 9 with 3, then in the output we would remove [9,4] and replace [3,1] with [3,1,4].
In the output, groups must be ordered by their first occurrence, and indices must be in ascending order. The element must be first in a group, before its indices. Output may be 0 or 1 indexed. You may assume the array has at least one element.
Test cases:
Input           | Output (One-indexed)
[3, 2, 2, 3]    | [[3, 1, 4], [2, 2, 3]]
[17]            | [[17, 1]]
[1, 1]          | [[1, 1, 2]]
[1, 1, 2]       | [[1, 1, 2], [2, 3]]
[1, 2, 3, 4]    | [[1, 1], [2, 2], [3, 3], [4, 4]]
[1, 1, 1, 1]    | [[1, 1, 2, 3, 4]]

This is code-golf, fewest bytes wins!

Would it be acceptable for the indides to be output as strings, e.g. [[17,"1"]]? (Don't know yet if I can save any bytes that way, still working on it!)

@shaggy sure, that's fine

may we output to stdout using a consistent separator? For example, 1 1 2\n2 3 for the fourth test case?

although I suppose that then you couldn't see the two-dimensional structure of the last test case at it would be 1 1 2 3 4

@Giuseppe No, that's fine. In all cases there would be a kind of 'implicit' [] wrapped around the output.

Possible duplicate.

Can we output something like [[3, [1, 4]], [2, [2, 3]]] instead?

@ConorO'Brien Sorry, no. I can't allow that because it will make existing answers be non-optimal.

@Pavel that's no reason :p but sure

Dyalog APL, 5 bytes
(⊂,)⌸

Try it online!
,⌸ for 2 bytes almost works, but has trailing zeroes :/

What in the world does ⌸ do?

@Mr.Xcoder gets the indexes of each thing and calls the left operator with the thing and indices where it exists

Since the isue with ,⌸ is trailing zeroes, and zeroes will never be in the input, would it be possible to drop all zeroes in less than 3 bytes?

@Pavel the reason that there are the zeroes is that the result is a matrix, which has to have exact dimensions, so there's only 1 byte for dropping the zeroes for any byte gain. I feel like this might be golfable though.

"fancy af" array output format: Try it online!

Doesn't it count as more than 5 bytes when non-ascii characters are used? Try It Online says it's 9 bytes.

J, 12 bytes
~.,&.><@I.@=

Zero-indexed.
Try it online!
If you can remove all of the work I'm doing with boxes, you can probably reduce the bytecount by quite a bit. I'm going to see if I can figure that out.
Explanation
This is probably too early to be explaining (there ought to be more golfs).
~. ,&.> <@I.@=
             =  Self-classify (comparison of each unique element to array)
            @   Composed with
          I.    Indices of ones (where it's equal)
         @      Composed with
        <       Boxed (how we deal with arrays of unequal length)
   ,&.>         Joined with
      >          Unbox each
   ,             Concatenate
    &.           Box again
~.              Unique elements

That array output format is fancy af

@Pavel it's also taking a lot of bytes Π.Π

05AB1E, 10 bytes
ÙεDIQƶ0K)˜

Try it online!
Explanation
Ù             # remove duplicates
 ε            # apply to each element
  D           # duplicate
   IQ         # compare for equality with input
     ƶ        # multiply each element by its index (1-based)
      0K      # remove zeroes
        )˜    # wrap in a flattened list

Python 3, 83 82 bytes
-1 byte thanks to Mego

lambda x:[[n]+[j for j,m in enumerate(x)if m==n]for n in sorted({*x},key=x.index)]

Try it online!

j+1 -> j (indices may be zero-indexed)

Haskell, 48 bytes
import Data.List
f l=nub[k:elemIndices k l|k<-l]

Try it online!

Attache, 15 bytes
Flat=>Positions

Try it online!
This is an interesting case of =>, the operator form of Map. When given two functional arguments f and g, Map returns a function f => g[x] over x. That is, the RHS is applied to the input, then the LHS is mapped.
The builtin Positions generates an array representing the grouping of entries by indices. By default, when not supplied with a second argument, Positions will use the first argument. Flat is then mapped over each item, as that is what the question requires.
Alternative solutions
31 bytes
MapArgs[Concat#~Indices,Unique]

Try it online!
A pretty short, builtin-less alternative. MapArgs is a function like Map, except you can feed extra arguments into it. For example, MapArgs[{_1 + _2}, 1..3, 3] is [4, 5, 6]. Like Map, it becomes curried when supplied with two functional arguments. The function be mapped is Concat#~Indices, which is a fork. This fork is applied to the Unique items of the input and the input itself. This translates to Concat[_, Indices[_2, _]] (with the arguments of Indices swapped through ~), which pairs the element being mapped (_) with the indices of said element _ in the input array, which is _2 (as ffed through MapArgs).
43 bytes
{Flat=>Zip[Unique[_],Indices[_,Unique[_]]]}

Try it online!
This is really just a more verbose (yet a tad more readable) combination of solutions #1 and #2.

Jelly, 6 bytes
Q;"ĠṢ$

Try it online!
Explanation:
Q;"ĠṢ$
Q      Keep the first occurrence of each element
     $ Last two links as a monad
   Ġ    Group indices of equal elements, then sort the resulting list of groups by the element they point to
    Ṣ   Sort; used to re-order the list of groups based on first occurrence instead
  "    Vectorize link between two arguments (the first occurrences and the group list)
 ;      Concatenate

Doesn't work for the last test case. The array should be nested another layer, the output is alway two-dimensional.

@Pavel yes it does, I just forgot to add a footer (answer is a function)

Ok then, cool. Explanation soon, yes? :P

@Pavel added explanation

Pyth, 7 bytes
0-indexed.
{+VQxRQ

Try it here! Alternative.
How?

{+VQxRQ – Full program.

     RQ – For each element...
    x   – Get all its indices.
 +V     – And apply vectorised concatenation.
   Q    – With the input.
{       – Deduplicate.

K (oK), 10 bytes
Solution:
(!x),'.x:=

Try it online!
Examples:
(!x),'.x:=,17
,17 0
(!x),'.x:=1 1
,1 1 2
(!x),'.x:=1 0 1
(1 1 2
2 3)
(!x),'.x:=1 2 3 4
(1 0
2 1
3 2
4 3)

Explanation:
Evaluation is performed right-to-left. I still think this is golf-able further...
(!x),'.x:= / the solution
         = / group input into dictionary, item!indices
       x:  / save as variable x
      .    / value of x (the indices)
    ,'     / concatenate (,) each-both (') with
(  )       / do this together
 !x        / the key of x (i.e. the items)

Notes:

14 bytes without declaring x, (,/)'+(!;.)@'=, gave up with this approach...

You may return 0-indexed result, so I think you can skip the 1+.

MATL, 8 bytes
u"@tG=fh

Try it at MATL Online
Explanation
        # Implicitly get the input
u       # Compute the unique values
"       # For each unique value, N
  @     # Push the value N to the stack
  t     # Duplicate N
  G     # Grab the input
  =f    # Get the 1-based indices of the elements that equal N
  h     # Horizontally concatenate N with the indices
        # Implicitly display the result

ooooohhh that's clever! I had like 18 bytes trying to use &f but never did get it to work.

Actually, 24 bytes
;;╗⌠╝╜r⌠╜E╛=⌡░⌡M@Z⌠♂i⌡M╔

Try it online!
Explanation:
;;╗⌠╝╜r⌠╜E╛=⌡░⌡M@Z⌠♂i⌡M╔
;;                        make two copies of input
  ╗                       save a copy to register 0
   ⌠╝╜r⌠╜E╛=⌡░⌡M          map over input:
    ╝                       save the element in register 1
     ╜r                     indices for input
       ⌠╜E╛=⌡░              filter:
        ╜E                    element in input at index
          ╛=                  equals element for outer map (from register 1)
                @Z        swap, zip input with map result
                  ⌠♂i⌡M   flatten each element in zipped list
                       ╔  uniquify

Wolfram Language (Mathematica), 40 bytes
Saved a byte thanks to Martin Ender.
KeyValueMap[{#,##&@@#2}&]@*PositionIndex

Try it online!

How does @*PositionIndex work?

@Pavel @* is composition of functions. PositionIndex basically does all the job, but returns an association instead of a list.

{#,##&@@#2}& saves a byte.

Julia 0.6, 37 bytes
Thanks to Pavel for 1 byte off.

y->[[x;findin(y,[x])]for x=unique(y)]

Try it online!

Remove the space between ] and for for -1 byte.

SWI-Prolog, 165 117 bytes
-48 bytes thanks to Prolog golfing tips.
h(I):-I+[]-1.
[H|T]+R-N:-(select([H|A],R,[H|L],S),!,append(A,[N],L);append(R,[[H,N]],S)),O is N+1,(T+S-O,!;write(S)).

Try it online!
Explanation
% The predicate that prints the grouped duplicates. It's a wrapper because we
% need some extra arguments to keep state:
enumerate_duplicates(Input) :- enumerate(Input, [], 1).

% In the golfed code, operators are used to represent this predicate.
% See https://codegolf.stackexchange.com/a/153160
% Go through the input, build up the result on the way and print it.
enumerate([Head|Tail], Result, Index) :-
    (
        % If our current Result already contains a list that starts with the
        % current first element in our input, Head, NewIndexes will become the
        % new "tail" of that list in our next result list:
        select([Head|OldIndexes], Result, [Head|NewIndexes], NextResult),
        % Don't backtrack before this if goals below this fail:
        !,
        % The as-yet-unknown NewIndexes above should in fact be the same as
        % OldIndexes with our current Index appended:
        append(OldIndexes, [Index], NewIndexes)
    % Use ; instead of separate predicate rules.
    % See https://codegolf.stackexchange.com/a/67032
    ;
        % If our current Result did not already contain Head, append a new list
        % for it with the current index:
        append(Result, [[Head, Index]], NextResult)
    ),
    % Increment our index counter:
    NextIndex is Index + 1,
    (
        % And continue with the rest of our input:
        enumerate(Tail, NextResult, NextIndex),
        % Don't backtrack if the above succeeded:
        !
    ;
        % If Tail is no longer a multi-element list, we're done. Print:
        write(NextResult)
    ).

R, 56 bytes
function(x)lapply(unique(x),function(y)c(y,which(x==y)))

Try it online!

This is my first attempt at codegolf, so any feedback is welcome!

Welcome to PPCG! Nice first answer.

Hey there Florian! Very nice answer. This is actually a snippet rather than a program or function -- it assumes the input is hardcoded into x, but there has to be a way of reading input -- typically we use scan or define a function. Additionally, it has to output, so'd have to wrap this in a print or a cat.

but for golfing: You don't have to use braces around the function body, removing a pair of bytes.

I count 56 bytes but alternative approaches are possibly golfier.

see this question for more handy R golfing tricks :)

Thanks guys! And the link to the r tips is certainly useful!

you'll need to make some edits (changing to a function, as I've suggested) to make this a valid submission, but it's still an excellent answer, so once those changes are made I'll give this a +1.

@Giuseppe, I still have to get used a bit to the rules and the use of header/code/footer, but I think my submission matches the requirements now! R does not seem to be the best for codegolfing though, haha.

@Florian R isn't so bad as you think (except on string challenges...) so long as you remember you're golfing against other R golfers! Feel free to ping me in chat if you have questions. There's a couple of R golfers who are active, and they'll definitely offer suggestions, and appreciate yours as well! Welcome to golfing :)

JavaScript (ES6), 64 bytes
0 indexed
a=>a.map((v,i)=>a[-v]?a[-v].push(i):a[-v]=[v,i]).filter(x=>x[0])

Note, this assume input numbers being positive, so v > 0
Test slightly modified (1 indexed) to match the test cases

var F=
a=>a.map((v,i)=>a[-v]?a[-v].push(i+1):a[-v]=[v,i+1]).filter(x=>x[0])

test = [ // output 1 indexed
  [3, 2, 2, 3],//    | [[3, 1, 4], [2, 2, 3]]
  [17], //           | [[17, 1]]
  [1, 1], //         | [[1, 1, 2]]
  [1, 1, 2], //      | [[1, 1, 2], [2, 3]]
  [1, 2, 3, 4], //   | [[1, 1], [2, 2], [3, 3], [4, 4]]
  [1, 1, 1, 1] //    | [[1, 1, 2, 3, 4]]
]

test.forEach(t => {
  x = F(t)
  console.log(JSON.stringify(t)+ ' -> ' + JSON.stringify(x))
})

APL NARS, 24 bytes, 12 chars
{∪⍵,¨⍸¨⍵=⊂⍵}

-4 bytes thanks to Adam
test:
  f←{∪⍵,¨⍸¨⍵=⊂⍵}

  ⎕fmt f 3 2 2 3
┌2────────────────┐
│┌3─────┐ ┌3─────┐│
││ 3 1 4│ │ 2 2 3││
│└~─────┘ └~─────┘2
└∊────────────────┘
  ⎕fmt f 17
┌1──────┐
│┌2────┐│
││ 17 1││
│└~────┘2
└∊──────┘
  ⎕fmt f 1 1
┌1───────┐
│┌3─────┐│
││ 1 1 2││
│└~─────┘2
└∊───────┘
  ⎕fmt f 1 2 3 4
┌4──────────────────────────┐
│┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐│
││ 1 1│ │ 2 2│ │ 3 3│ │ 4 4││
│└~───┘ └~───┘ └~───┘ └~───┘2
└∊──────────────────────────┘
  ⎕fmt f 1 1 1 1
┌1───────────┐
│┌5─────────┐│
││ 1 1 2 3 4││
│└~─────────┘2
└∊───────────┘

Shave a 4 bytes/2 chars: {∪⍵,¨⍸¨⍵=⊂⍵}

Japt, 14 9 bytes
0-indexed.
â £ð¶X iX

Try it
â £ð¶X iX
â             :Deduplicate
  £           :Map each X
   ð          :  Get 0-based indices of elements in the input
    ¶X        :    That are equal to X
       iX     :  Prepend X

JavaScript (ES6), 68 bytes
0-indexed.
a=>a.map(p=(x,i)=>1/p[x]?b[p[x]].push(i):b.push([x,p[x]=i]),b=[])&&b

Test cases

let f =

a=>a.map(p=(x,i)=>1/p[x]?b[p[x]].push(i):b.push([x,p[x]=i]),b=[])&&b

console.log(JSON.stringify(f([3, 4, 13, 9, 2]))) // [[3,0],[4,1],[13,2],[9,3],[2,4]]
console.log(JSON.stringify(f([3, 4, 13, 3, 2]))) // [[3,0,3],[4,1],[13,2],[2,4]]
console.log(JSON.stringify(f([3, 2, 2, 3]    ))) // [[3,0,3],[2,1,2]]
console.log(JSON.stringify(f([17]            ))) // [[17,0]]
console.log(JSON.stringify(f([1, 1]          ))) // [[1,0,1]]
console.log(JSON.stringify(f([1, 1, 2]       ))) // [[1,0,1],[2,2]]
console.log(JSON.stringify(f([1, 2, 3, 4]    ))) // [[1,0],[2,1],[3,2],[4,3]]
console.log(JSON.stringify(f([1, 1, 1, 1]    ))) // [[1,0,1,2,3]]

Input numbers are != 0, that could be useful to avoid the 1/x trick

PHP 4.1, 88 bytes
Yeah, it is pretty long.
This assumes a default php.ini file (short_open_tag = On and register_globals = On).
<?foreach($A as$k=>$v){!$b[$v]&&$b[$v]=array($v);$b[$v][]=$k;}print_r(array_values($b));

This presents the array in an human-readable way.
The values can be passed by POST, GET and COOKIE, inside the key "A".

For a modern version, one can use (90 bytes):
<?foreach($_GET[A]as$k=>$v){if(!$b[$v])$b[$v]=[$v];$b[$v][]=$k;}print_r(array_values($b));

The result is the same, except all values have to be passed over GET parameters inside the key "A".

Perl 6,  63  61 bytes
*.pairs.classify(*.value).map({.key,|.value».key}).sort(*.[1])

Test it (0-based)
{sort *.[1],map {.key,|.value».key},classify *.value,.pairs}

Test it (0-based same algorithm)
Expanded:
# WhateverCode lambda (this is the parameter)
*\                                            # [3,2,2,3]

# get a list of Pairs (zero based index => value)
.pairs                                        # (0=>3,1=>2,2=>2,3=>3)

# classify based on the values (unordered result)
.classify(*.value)                            # {2=>[1=>2,2=>2],3=>[0=>3,3=>3]}

# simplify the structure
.map({
  .key,         # the value
  |.value».key  # slip in the indexes
})                                            # ((3,0,3),(2,1,2))

# sort based on first index
.sort(*.[1])

PHP 7.4+, 71 bytes
*73 bytes to quote the $_GET key and avoid Warnings.
Snippet: (Demo)
<?foreach($_GET[A]as$k=>$v){$b[$v][0]=$v;$b[$v][]=$k;}print_r([...$b]);

Based on rep, I assume IsmaelMiguel knows the best way to post php code in this community so I am building from his foundation.  It is not clear to me if <? is to be included/counted in my snippet.  As this is my maiden post, I am happy for anyone to explain if there is any unnecessary syntax. p.s. I also read Tips for golfing in PHP which seems to me like a terrific candidate for migration to Meta.
The improvements made to Ismael's snippet are:

Unconditional assignment of the first element in each subarray (value overwriting)
Splatpacking instead of array_values() to reindex the output.

Husk, 6 bytes
mS:¥¹u

Try it online!

Perl 5, 63 + 1 (-a) = 64 bytes
map$k{$_}.=$".++$i,@F;say$_.$k{$_}for sort{$k{$a}-$k{$b}}keys%k

Try it online!

Clean, 61 60 bytes
import StdEnv,StdLib
$l=removeDup[[e:elemIndices e l]\\e<-l]

Try it online!
Output is 0-indexed

Ruby, 54 52 bytes
->a{a.map{|i|[i]+(0..a.size).select{|j|a[j]==i}}|[]}

This version allows nil (53 bytes):
->a{a.map{|i|[i]+(0...a.size).select{|j|a[j]==i}}|[]}

Try it online!

The challenge specifies the array will only contain positive integers, and there will be at least one element. nil is not a positive integer.

@Pavel thanks, I checked but missed it somehow

Kotlin, 83 bytes
{it.mapIndexed{i,c->c to i}.groupBy({(a,b)->a},{(a,b)->b}).map{(a,b)->listOf(a)+b}}

Beautified
{
    it.mapIndexed { i, c -> c to i }
        .groupBy({ (a, b) -> a }, { (a, b) -> b })
        .map { (a, b) -> listOf(a) + b }
}

Test
var f: (List<Int>) -> List<List<Int>> =
{it.mapIndexed{i,c->c to i}.groupBy({(a,b)->a},{(a,b)->b}).map{(a,b)->listOf(a)+b}}

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

val tests = listOf(
        Test(listOf(3, 2, 2, 3), listOf(listOf(3, 0, 3), listOf(2, 1, 2))),
        Test(listOf(17), listOf(listOf(17, 0))),
        Test(listOf(1, 1), listOf(listOf(1, 0, 1))),
        Test(listOf(1, 1, 2), listOf(listOf(1, 0, 1), listOf(2, 2))),
        Test(listOf(1, 2, 3, 4), listOf(listOf(1, 0), listOf(2, 1), listOf(3, 2), listOf(4, 3))),
        Test(listOf(1, 1, 1, 1), listOf(listOf(1, 0, 1, 2, 3)))
)

fun main(args: Array<String>) {
    for (c in tests) {
        val o = f(c.input)
        if (o != c.output) {
            throw AssertionError("${c.input} -> $o != ${c.output}")
        }
    }
}

TIO
TryItOnline

This sollution is a snippet, not a complete function or program. It requires the variable i to be predefined. You can make this valid by converting it to a lambda that takes a parameter i.

Reworked to solve issue raised by @Pavel

 Swift 4, 107 bytes
... Yikes.
{a in Dictionary(grouping:a.enumerated()){$0.1}.sorted{$0.1.first!.0<$1.1.first!.0}.map{[$0]+$1.flatMap{$0.0}}}

Ungolfed:
let f = { (input: [Int]) -> [[Int]] in
    return Dictionary(grouping: input.enumerated(), by: { $0.element })
        .sorted { pairA, pairB in // Sort by order of first appearence (lowest offset)
            return pairA.value.first!.offset < pairB.value.first!.offset
        }.map { element, pairs in
            return [element] + pairs.map{ $0.offset /* +1 */} // add 1 here for 1 based indexing
        }
}

It's too bad that dictionary loses ordering, forcing me to waste so many characters on sorting back again. This sort of abuse of implicit closure arguments ($0, $1, ...) and implicit tuple members (.0, .1, ...) is uhhhhh not pretty.

Factor, 56 bytes
[ dup members swap '[ _ dupd indices swap prefix ] map ]

Try it online!

jq, 31 bytes
[unique[]as$b|[$b]+indices($b)]

This really just uses a jq variable to allow the indices() function to reference data that's not readily available otherwise.
[                             ] - makes the output valid JSON
 unique[]as$b                   - stores each unique number in var "$b"
             |[$b]              - convert number to an array
                   indices($b)  - get all matching positions in an array
                  +             - combined the arrays

Try it online!

Arturo, 57 bytes
$[a][map unique a'x[@[x]++select 1..size a'y->x=a\[y-1]]]

Try it
$[a][                           ; a function taking an argument a
    map unique a 'x [           ; map over unique numbers in a and assign current number to x
        @[x]                    ; x as a list
        ++                      ; prepended to
        select 1..size a 'y ->  ; the indices in a where...
            x = a\[y-1]         ; x equals the value in a at the current index
    ]                           ; end map
]                               ; end function


text:
Converting ISBN-13 to ISBN-10
Introduction
In this challenge your task is to generate the ISBN-10 code for books given its ISBN-13 code, assuming that such a code exists. Such an ISBN-13 code consists of several parts separated by -:
978-GG-PPPP-TTT-C

The letters G (group), P (publisher), T (title) and C (checksum) all stand for one digit. For the purpose of this challenge the grouping and the computation of C (see this challenge) are not interesting and we'll drop all hyphens to make this task simpler.
An ISBN-10 number has a very similar layout:
GG-PPPP-TTT-c

The letters G,P and T are the same as for the 13 digits ISBN, however c is different (and is computed using a different algorithm). The digit c is chosen in a way such that the following equivalence holds (digits in order):
10*G + 9*G + 8*P + … + 3*T + 2*T + 1*c = 0 (mod 11)

Example
Let us consider the ISBN number 9780345391803: To get its corresponding ISBN-10 code we simply drop the leading 978 and the checksum 3 yielding 034539180.
Next we need to compute the new checksum:
10*0 + 9*3 + 8*4 + 7*5 + 6*3 + 5*9 + 4*1 + 3*8 + 2*0 = 185

The next number divisible by 11 is 187, so the new checksum is 2 and thus the resulting ISBN-10 code 0345391802.
Rules

Your input will always have a corresponding ISBN-10 number (ie. it is exactly 13 digits long and starts with 978)
The input doesn't necessarily have to be a valid ISBN-13 (eg. 9780000000002)
You're guaranteed that the resulting ISBN won't end with X
You may take input as an integer or string (with or without hyphens) however a precomputed list of digits are not allowed
Your output must be a valid ISBN-10 number (with or without hyphens)
Your output may be an integer or string (again no lists of digits)

Testcases
9780000000002 -> 0000000000
9780201882957 -> 0201882957
9781420951301 -> 1420951300
9780452284234 -> 0452284236
9781292101767 -> 1292101768
9780345391803 -> 0345391802

Note the leading zeroes!

It doesn't affect solutions at all, but just for the sake of being That Guy, your description of how the parts of an ISBN (either -10 or -13) are separated is incorrect. The registration group element is variable length, and the number of digits for subsequent parts can vary between, and within, registration groups. For example, in both 0-684-84328-5 and 99921-58-10-7, the first part (0 and 99921 respectively) is the registration group, the second part is the publisher, and so on.

10/10 sample ISBN choices

Retina,  44  39 28 bytes
>,L3,-2`.+
.
$.>`**
_{11}

_

Try it online!
Explanation
Time to show off some new Retina features. :)
>,L3,-2`.+

We match the entire input with .+, return that match L, but select only the characters 3 (zero-based) to -2 (penultimate), inclusive. We also print the result without a trailing linefeed (>).
Now, subtracting things in Retina is a bit annoying. But luckily, we're working modulo 11, so we can just invert the coefficients of the linear combination (mod 11) and add everything up. In other words, if the constraint is:
10*G + 9*G + 8*P + … + 3*T + 2*T + 1*c = 0 (mod 11)

then we get:
c = 1*G + 2*G + 3*P + … + 8*T + 9*T (mod 11)

That simplifies things a lot here:
.
$.>`**

We replace each character with that thing at the bottom. * is Retina's repetition operator. It's right-associative and it has implicit operands $& on the left and _ on the right, so the substitution is actually short for $.>`*$&*_. $&*_ creates a string of d underscores, where d is the digit we're currently replacing. Then $.>` is the length of the string up to and including the match.1 Hence, the entire expression results in a unary representation of the nth term of our linear combination.
_{11}

Doing the actual modulo is trivial in unary: we just drop all complete sets of 11 underscores.
_

Finally, we count how many underscores remain and print the result, which completes the ISBN-10.

1 How does $.>` give the length of the string up to and including the match? You might be familiar with $` in regex substitutions, which gives you the string up to (but excluding) the match. By inserting a >, we can shift the context of the $` to the separator between the current match and the next (which is an empty string between the current digit and the next). That separator's $` will include the current match. So $>` is a shorter way to write $`$&. Finally, for all $x-type substitution elements, Retina lets you insert a . after the $ to get its length.

What is this modulo 11 magic?! That'll save me 4 bytes... but I don't gettit!

@streetster Basically, -2 ≡ 9 (mod 11) (because adding or subtracting 11 from a number doesn't change its "value" in the congruence class mod 11). And addition and multiplication respects congruence classes, so you can replace any value in a linear combination with an equivalent value under the current modulo. The reason I'm talking about negative numbers is really just that I've rearranged the equation to have c on one side and all the other terms (as negatives) on the other.

I think I get it now. So you move c over to become -c = ... and rather than multiplying by 10 9 8... you subtract 11 from each to get -1 -2 -3... and then multiply everything by -1 to get c.

Would you mind explaining why the final stage is only replacing the trailing underscores? I've spent a while trying to figure out what is causing that but I can't seem to reproduce it. This update looks amazing by the way, nice job!

@FryAmTheEggman Thanks :) At that point, the string contains only underscores. We've already printed the first nine digits in the first stage.

05AB1E, 17 15 13 12 bytes
¦¦¦¨DSƶO11%«

Try it online!
Explanation
¦¦¦            # remove the first 3 characters
   ¨           # remove the last character
    D          # duplicate
     S         # split to list of digits
      ƶ        # multiply each by its 1-based index
       O       # sum
        11%    # mod by 11
           «   # concatenate

PowerShell, 96 84 bytes
$y=-(([char[]]($x="$args"-replace'^978|.$')|%{--$a*[int]"$_"})-join'+'|iex)%11;$x+$y

Try it online!
Takes input "$args", does a regex -replace to get only the pertinent part, stores that into $x as a string. Then we cast that as a char-array and loop through each letter. Inside the loop, we pre-decrement $a (which defaults to 0) and multiply out according to the checksum calculation. Note the cast to int, else this would use ASCII values.
We then -join those numbers together with + and pipe that to iex (Invoke-Expression and similar to eval). We take that %11 and store that checksum into $y. Finally, we string concatenate $x + $y, and leave that on the pipeline. Output is implicit.
Saved 12 bytes thanks to Emigna.

I don't really know powershell, but I think something like this can work for 84

@Emigna Yes, of course. Modulus arithmetic and my brain don't play nicely.

Octave, 46 41 39 37 bytes
@(a)[c=a(4:12) 48+mod(7+c*(1:9)',11)]

Try it online!
The code takes input as a string, and returns a string.
The code breaks down as follows:
@(a) creates an anonymous function.
With [c=a(4:12)   ... ] we extract the characters that form the main code, saving a copy to c for later use, and adding another copy to the final output string.
Based on @MartinEnter's clever way of swapping 10:-1:2 into 1:10, we can easily generate that range and transpose it to get a column vector. c*(1:10)' does array multiplication of the row vector c and range column vector. This is equivalent to doing an element-wise multiplication then summing.
The checksum would normally be mod(11-sum,11) to calculate the number required for the sum to be a multiple of 11. However, because c was a character string, the sum will actually be larger than it should be by 2592 (48*54) because we multiplied by numbers that were 48 larger than the actual value.
When we perform the modulo, it will automatically get rid of all but 7 of that 2592. As such, and accounting for the negation of the range, the actual calculation becomes 48+mod(7+sum,11). We add on 48 to the result to convert back to an ASCII character.
The checksum character is appended to the end of the result, and the value returned.

Jelly, 12 bytes
ṫ4ṖȮV€xJS%11

This is a full program that uses strings for I/O.
Try it online!
How it works
ṫ4ṖȮV€xJS%11  Main link. Argument: s (string of length 13)

ṫ4            Tail 4; discard the first three characters.
  Ṗ           Pop; discard the last characters.
   Ȯ          Output; print the result to STDOUT and return it.
    V€        Eval each; turn digit characters into digits.
       J      Indices; yield [1, ..., 13].
      x       Repeat the first digit once, the second digit twice, etc.
        S%11  Take the sum, modulo 11.
              (implicit) Print the checksum to STDOUT.

JavaScript (ES6), 59 56 bytes
s=>(s=s.slice(3,-1))+[...s].reduce(n=>n+s[i++]*i,i=0)%11

f=
s=>(s=s.slice(3,-1))+[...s].reduce(n=>n+s[i++]*i,i=0)%11
//s=>(s=s.slice(3,-1))+(n=0,[...s].map((c,i)=>n+=c*-~i),n)%11
//s=>(s=s.slice(3,-1))+(n=0,[...s].map(c=>n+=c*i++,i=1),n)%11
//s=>(n=0,[...(s=s.slice(3,-1))].map((c,i)=>n+=c*-~i),s+n%11)
//s=>(s=s.slice(3,-1,n=i=0))+eval(`for(c of s)n+=c*-~i++`)%11

console.log(...[
  '9780000000002',
  '9780201882957',
  '9781420951301',
  '9780452284234',
  '9781292101767',
  '9780345391803'
].map(f))

-3 bytes thanks to @Shaggy's suggestion.

57 bytes?

Or maybe even 56 bytes.

So why not input as array of digits? 54 bytes

Japt, 16 15 bytes
Came up with this down the pub the other night and forgot all about it.
s3J
U+¬x_*°TÃuB

Try it

1 byte saved thank to ETHproductions

Think you can save a byte with s3J and U+¬x_*°TÃuB

Weird; could've sworn I'd tried that. Thanks, @ETHproductions.

Wait, no, I'd forgotten the U - D'oh!

Perl 5, 49 + 1 (-p) = 50 bytes
s/^...|.$//g;$\=(eval s/./"-$&0+".$i++*$&/ger)%11

Try it online!

K (oK), 29 25 24 23 bytes
Solution:
x,$11!7+/(1+!9)*x:-1_3_

Try it online!
Examples:
x,$11!7+/(1+!9)*x:-1_3_"9780000000002"
"0000000000"
x,$11!7+/(1+!9)*x:-1_3_"9780345391803"
"0345391802"
x,$11!7+/(1+!9)*x:-1_3_"9781292101767"
"1292101768"
x,$11!7+/(1+!9)*x:-1_3_"9780452284234"
"0452284236"

Explanation:
Evaluation is performed right-to-left.
Two tricks taken from other solutions:

multiply by 1 2 3... instead of 10 9 8...
multiply ASCII values and then add 7 to the sum to balance out

Breakdown:
x,$11!7+/(1+!9)*x:-1_3_ / the solution
                     3_ / drop three items from the start
                  -1_   / drop one item from the end
                x:      / save this as variable x
               *        / multiply by
         (    )         / all this together
            !9          / til, !9 => 0 1 2 3 4 5 6 7 8
          1+            / add 1 => 1 2 3 4 5 6 7 8 9
      7+/               / sum (+) over (/), start from 7
   11!                  / mod by 11
  $                     / convert back to a string
x,                      / join with x

Notes:

-4 bytes thanks to Martin Enders's "just invert the coefficients" magic.
-1 byte thanks to Tom Carpenter for removing the need to convert to integers (by adding 7 to the sum)
-1 byte start the accumulator at 7

Pyth, 16 bytes
%s.e*ksbpP>Q3hT

Try it here!
Pyth, 17 bytes
%s*VsMKpP>Q3SlK11

Try it here!
Explanation
%s.e*hksbpP>Q3hT || Full program. Uses string for input and output.

            Q    || The input.
           > 3   || With elements at indexes smaller than 3 trimmed.
          P      || Pop (remove the last item).
         p       || Print the result without a linefeed, but also return it.
  .e             || Enumerated map. For each (index, value), assign two variables (k, b).
       sb        || b converted to an integer.
    *hk          || And multiplied by k + 1.
 s               || Summation.
%                || Modulo by:
               T || The literal 10.
              h  || Incremented by 1.

C (gcc), 96 95 87 86 85 bytes
(-1 thanks to ceilingcat)
*f(s,r,c,d)char*s,*r;{for(d=13;--d;s+=*++s<48)r=d>8?c=3,s:r,c-=~d**s;*s=58-c%11;s=r;}

Try it online!
To be called as f(s), where s is a pointer to the first element of a modifiable character array. Modifies the input array, returns a pointer into the input array.

Hexagony, 77 61 bytes
,,,,'~'11=\.A&.=\./';"-'"{4.8}}\'.A.>.,<\'+'%!@}/=+'+{./&{{&/

Try it online!

Colored:

Here is a larger version. There are some path crossings, but because all of those cells are . (no-op in Hexagony), you don't need to worry about them:
(I also tried to keep the old mirrors, but sometimes I need to change something)

The linear command executed is:
,,,,'48}}
,
while memory > 0:
    ';"-'"{+'+{=A&=''A
    if memory < 0:
        undefined behavior
    &{{&}
    ,
'"''+~'11='%!@

Explanation: Instead of keeping a counter and do multiplication at each digit, this program:

keep a "partial sum" variable and "total sum" variable (p and t)
for each digit read: add it to partial sum, and add the partial sum to total sum.
print (-p-t)%11, where % always return positive results.

Jelly, 14 bytes
ṫ4ṖµV€×JS%11;@

Test suite!
Jelly, 17 bytes
Ṛḣ⁵µVD×JḊSN%11;ḊṚ

Try it online! or Test suite!
Takes input and outputs as a string.

Python 2, 62 bytes
lambda n:n[3:12]+`-sum(i*int(n[13-i])for i in range(2,11))%11`

Try it online!
Takes a string as input; and outputs a string.

ECMAScript 6, 86 67 bytes
a=>(c=a.substr(3,9))+([...c].map(v=>g+=--i*v,e=i=g=11)?(e-g%e)%e:0)

Try it online!

Thanks for Arnauld's comment, switched from reduce to map and got rid of return keyword.

Welcome to PPCG! Answers must be either full programs or callable functions (although they may be unnamed functions), not just snippets. I believe the shortest option in JavaScript is usually an unnamed lambda.

@MartinEnder thanks, I have edited my answer

Welcome on board! Some tips: Variable initialization can usually be put as extra parameters of map(), reduce() etc. With some additional rewriting, it's often possible to get rid of {} and return. Also, in this particular case, map() is probably shorter than reduce(). (Here is a 65-byte version.)

I'm pretty sure f= isn't necessary. Also, you can initialize c at the spread for something like this: a=>{i=10;s=[...c=a.substr(3,9)].reduce((g,v)=>+g+(i--)*v,0)%11;return c+=s?11-s:0} (-4 bytes)

Retina 0.8.2, 72 51 bytes
...(.*).
$1¶$1
r`.\G
$&$'
r`.\G
$*
1{11}

¶(1*)
$.1

Try it online! Because I haven't learned Retina 1.0 yet. Explanation:
...(.*).
$1¶$1

Delete the unwanted characters and make a second copy of the appropriate digits.
r`.\G
$&$'

Suffix each digit in the second copy with its suffix. This effectively repeats each digit in the suffix by its position.
r`.\G
$*

Convert the digits in the second copy to unary thus adding them together.
1{11}

Reduce modulo 11. (There are only 9 digits in the first copy, so this can never affect it.)
¶(1*)
$.1

Convert the result back to decimal and remove the newline again.

APL (Dyalog Unicode), 26 24 bytes
∊⍕¨(⊢,11|⊢+.×⍳∘≢)3↓¯1↓⍎¨

Try it online!
Tacit prefix function. Takes input as string.
2 bytes saved thanks to @ngn.
How?
∊⍕¨(⊢,11|⊢+.×⍳∘≢)3↓¯1↓⍎¨    ⍝ Main function.
                       ⍎¨    ⍝ Execute each; turns the string into a vector of digits.
                 3↓¯1↓       ⍝ Drop (↓) the last (¯1) and the first 3 digits.
   (           ≢)            ⍝ Tally; returns the number of digits in the vector.
             ⍳∘               ⍝ Then (∘) index (⍳) from 1
            ×                ⍝ Multiply the resulting vector [1..9]
         ⊢+.                 ⍝ Dot product with sum with the original vector;
                             ⍝ This will multiply both vectors, and sum the resulting vector.
      11|                    ⍝ Mod 11
     ,                       ⍝ Concatenate
    ⊢                        ⍝ With the original vector
 ⍕¨                          ⍝ Format each; returns a vector of digits as strings.
∊                            ⍝ Flatten to get rid of the spaces.

Ruby, 69 68 64 bytes
->n{v=n[3,9];c=11;v+"#{(c-v.chars.map{|i|i.to_i*c-=1}.sum)%11}"}

Try it online!

Clean, 104 102 98 bytes
import StdEnv
$s#s=s%(3,11)
#i=sum[digitToInt d*p\\d<-s&p<-[10,9..]]+10
=s++[toChar(i/11*11-i+58)]

Try it online!

Kotlin, 83 bytes
i.drop(3).dropLast(1).let{it+(11-(it.mapIndexed{i,c->(10-i)*(c-'0')}.sum()%11))%11}

Beautified
i.drop(3).dropLast(1).let {
    it + (11 - (it.mapIndexed { i, c -> (10 - i) * (c - '0') }.sum() % 11)) % 11
}

Test
data class Test(val input: String, val output: String)

fun f(i: String) =

i.drop(3).dropLast(1).let{it+(11-(it.mapIndexed{i,c->(10-i)*(c-'0')}.sum()%11))%11}

val tests = listOf(
        Test("9780000000002", "0000000000"),
        Test("9780201882957", "0201882957"),
        Test("9781420951301", "1420951300"),
        Test("9780452284234", "0452284236"),
        Test("9781292101767", "1292101768"),
        Test("9780345391803", "0345391802")
)

fun main(args: Array<String>) {
    for (c in tests) {
        val answer = f(c.input)
        val good = answer == c.output
        println("$good ${c.input} -> ${c.output} | $answer")
    }
}

TIO
TryItOnline

PHP, 64 bytes
Unfortunately, in PHP (-$c)%11 is the same as -($c%11); so I have to get the difference to at least the largest sum possible (55*9 = 495 = 45*11) instead of just using -$c%11.
for($f=11;--$f>1;print$d)$c+=$f*$d=$argn[13-$f];echo(495-$c)%11;

or
for($c=45*$f=11;--$f>1;print$d)$c-=$f*$d=$argn[13-$f];echo$c%11;

Run as pipe with -nR or try them online.

Java 10, 110 bytes
l->{var s=l+"";int c=0,i=3;for(;i<12;)c+=(13-i)*(s.charAt(i++)-48);return(l-(long)978e10)/10*10+(11-c%11)%11;}

Takes input and outputs as a long integer. Try it online here.
Ungolfed version:
l -> { // lambda taking a long as argument
    var s = l + ""; // convert the input to a String
    int c = 0, // the check digit
    i = 3; // variable for iterating over the digits
    for(; i < 12 ;) // go from the first digit past 978 to the one before the check digit
        c += (13 - i) * (s.charAt(i++) - 48); // calculate the check sum
    return (l - (long) 978e10) // remove the leading 978
           /10 *10 // remove the original check digit
           + (11 - c % 11) % 11; // add the new check digit
}