text:
Merge two values
You have two values each of which is either 0 representing "unknown", or one of 1,2,3. Merge them into a single value as follows:

If both values are nonzero and equal, output that value:
(3,3) -> 3
If both values are nonzero but unequal, output 0 for unknown:
(1,2) -> 0
If one value is zero and the other is not, output the nonzero value:
(2,0) -> 2, (0,1) -> 1
If both values are zero, output zero:
(0,0) -> 0

Test cases:
There are 16 possible input pairs.
  | 0 1 2 3
--+--------
0 | 0 1 2 3
1 | 1 1 0 0
2 | 2 0 2 0
3 | 3 0 0 3

(0, 0) -> 0
(0, 1) -> 1
(0, 2) -> 2
(0, 3) -> 3
(1, 0) -> 1
(1, 1) -> 1
(1, 2) -> 0
(1, 3) -> 0
(2, 0) -> 2
(2, 1) -> 0
(2, 2) -> 2
(2, 3) -> 0
(3, 0) -> 3
(3, 1) -> 0
(3, 2) -> 0
(3, 3) -> 3

Leaderboards

var QUESTION_ID=165314,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

The fourth rule fits in the first rule, so I dont know why you separated them.

Nitpick: The 4th point is redundant, you can just remove "nonzero" from the first point. EDIT: Wow, what a ninja @Fatalize is.

Also, 3 isn't really necessary here, although it does increase the number of possible inputs.

You say the 4th rule fits in the first rule, but I see it as redundant with the third rule.

I considered condensing the rules, but thought it would be clearest to just list all the zero/nonzero cases and leave the optimization up to the golfers.

This needs a leaderboard, the first page is starting to get answers already beaten on the second one.

Good idea, could you please one? I only have mobile access for some time.

Thanks for the leaderboard, although... are other people seeing the languages with links wrongly alphabetized?

Python 3, 27 25 bytes
lambda x,y:(x|y)>>(x*y&2)

Try it online!

I like that this breaks for inputs over 3. How did you come up with this?

Basically lots of trial and error.

Interesting. For a moment I thought of automating a search through limited-length expressions involving two ints and a few operators, but the space is much too big even at around 20 bytes. Some intelligence is required!

Jelly, 4 bytes
gf|S

Try it online!
How it works
gf|S  Main link. Left argument: x. Right argument: y.

g     Compute a, the gcd of x and y.
  |   Compute b, the bitwise OR of x and y.
 f    Filter; yield all common elements of [a] and [b].
   S  Take the sum.

APL (Dyalog), 5 bytes
⌈×∧=⌊

Try it online!
Useful reference
∧=⌊: Returns 1 if the lowest common multiple is equal to the minimum. This is only true if one of the values is zero, or both are equal. Alternatively I could have =*⌊
⌈×: The maximum multiplied by the above.

Shakespeare Programming Language, 296 bytes
Z.Ford,.Ajax,.Act I:.Scene I:.[Enter Ford and Ajax]Ajax:Listen to thy heart.Ford:Listen to thy heart.Am I as fat as you?Ajax:If so,let us Scene C.Am I as fat as zero?If so,let us Scene C.Ford:Am I as fat as zero?If not,you zero.open heart.let us Scene V.Scene C:.Ajax:open heart.Scene V:.[Exeunt]

Try it online!
First participation to a code-golf challenge, so let's start with one of my favorite joke languages !
Explanation :
Declaration of the two variables Ford and Ajax (shortest variable names available)
Z.Ford,.Ajax,.

First Scene : Put the two values into the variable, then test them for equality, then test Ajax against 0. If the value that we have to return is stored in the variable Ford, go to Scene C.
Act I:.
Scene I:.
[Enter Ford and Ajax]
Ajax:
Listen to thy heart.
Ford:Listen to thy heart.
Am I as fat as you?
Ajax:
If so,let us Scene C.
Am I as fat as zero?
If so,let us Scene C.

If Ford is 0, print Ajax, else set Ajax as 0 then print Ajax. Then go to the end of the program.
Ford:Am I as fat as zero?
If not,you zero.
open heart.
let us Scene V.

Scene C : Print Ford
Scene C:.
Ajax:open heart.

Scene V: End of the program.
Scene V:.
[Exeunt]

221 bytes

@JoKing your version is undeniably better than mine, I think it would be better if you posted it as an answer as the reasoning behind the program is quite different and I don't want to take the credit for your work

Ruby, 21 bytes
->a,b{(a|b)*531[a*b]}

Try it online!
Because Ruby
Short explanation:

a|b is bitwse OR, so it gives us the right number if a==b or one of them is zero.

Magic number 531 is 2^9+2^4+2^1+2^0, and the [] operator extracts a single bit. This means: multiply by 1 if a*b is 0, 1, 2, 4 or 9, multiply by 0 otherwise.

This won't work for values > 3

Haskell, 25 bytes
x!y=0^((x-y)^2*x)*y+0^y*x

Try it online!

Pyth, 8 7 bytes
@{+0SQ3

Try it online!
@{+0SQ3   Implicit: Q=input()

    SQ    Sort input
  +0      Prepend 0
 {        Deduplicate
@     3    Get 4th element (index 3), modular indexing

Case 1 - Both values nonzero and equal
Sorted Input   [3,3]
Prepend 0      [0,3,3]
Deduplicate    [0,3] - index 3 yields 3

Case 2 - Both values nonzero and unequal
Sorted Input   [1,2]
Prepend 0      [0,1,2]
Deduplicate    [0,1,2] - index 3 yields 0

Case 3 - Exactly one value zero
Sorted Input   [0,1]
Prepend 0      [0,0,1]
Deduplicate    [0,1] - index 3 yields 1

Case 4 - Both values zero
Sorted Input   [0,0]
Prepend 0      [0,0,0]
Deduplicate    [0] - index 3 yields 0

Alternate solution, also 7 bytes
*eSQ}s{

Try it online
*eSQ}s{QQ   Trailing Q's inferred

      {Q    Deduplicate input
     s      Take the sum
    }   Q   Is this in the input? True treated as 1, false as 0
*           Multiplied by
 eSQ        Max from input (end of sorted input)

Previous version, 8 bytes
@+0{-QZ3

@xnor Thanks for spotting that, it should be fixed now

@{+0Q3 works for 6 bytes.

JavaScript (Node.js), 17 bytes, port somehow from Python answer
a=>b=>a*b&2?0:a|b

Try it online!
JavaScript (Node.js), 21 bytes
a=>b=>a-b?a*b?0:a+b:a

Try it online!

?0:... Could you do ||, or does precedence mess that up?

@StanStrum ?0: mean return zero if cond is not zero, || return non-zero if cond is not zero

Java 8, 20 bytes
Curried lambda. Stolen from here.
a->b->(a|b)>>(a*b&2)

Stax, 8 bytes
Ç∞∟∙◄╥*♣

Run and debug it
Unpacked, ungolfed, and commented, it looks like this.
    e.g.        [2, 0]
c:s [2, 0] 2    calculate the "span" of the input array (max(a) - min(a))
+   [2, 0, 2]   append the span to the input array
o   [0, 2, 2]   sort the 3-element array
E   0 2 2       explode the 3 elements into 3 separate stack entries
a   2 2 0       rotate the third stack element to the top of stack
!   2 2 1       logical not, produces 1 iff the top value was 0
*   2 2         multiply
                implicitly print top of stack

Run this one

Brain-Flak, 32 bytes
{(({}[({})]<>)){{}<>}(<>)}{}({})

Try it online!

(first submission so please don't kick too hard)
Python 2, 57 44 43 bytes
lambda a,b:(0 if a*b else a+b)if a-b else a

Try it online!
(compressed a bit after looking at first python answer)

33 bytes

Crossed out 44 is still 44 ;(

@JoKing huh wut? Your solution is great, i tried to do it with arithmetics, but failed and fell back to if/else

C (gcc), 25 bytes
f(a,b){a=a^b&&a*b?0:a|b;}
pseudo-code:
foo(A,B)
    if A XOR B and A*B are > 0
        return 0
    else
        return A OR B`

C (gcc), 26 bytes
f(a,b){a=a*b?a-b?0:a:a+b;}

Try it online!
Expanation / Ungolfed:
int f(int a, int b) { // implicit-int (C89)
    // return replaced with assignment: link
    return a*b ? // if a and b are both not zero, then
        a-b ? // if a != b
        0 : // a != b, so return 0
        a // a == b, so return a
    : a+b // one of a,b is zero, so return whichever is nonzero
    ;
}

MATL, 9 bytes
dGp*~GX>*

Try it online!
Explanation:
           % Implicit input as a vector with two elements implicitly. Stack: [0,2]
d          % The difference between the two elements. Stack: [2]
 G         % Push input again. Stack: [2], [0,2]
  p        % The product of the last element (the input). Stack: [2], [0]
   *       % Multiply the two elements on the stack. Stack: [0]
    ~      % Negate. Stack: [1]
     G     % Push input again. Stack: [1], [0,2]
      X>   % Maximum value. Stack: [1], [2]
        *  % Multiply the two elements on the stack. Stack: [2]
           % Implicit output

Failed outgolf: t?td~*]X>

GNU sed, 23 bytes
s/^0?(.)\1?0?$/\1/
t
c0

(must be run with -r flag)
Try it online!

Welcome to PPCG :) The current consensus is that flags not be counted (I'm on my phone so can't link the relevant Meta).

Oh cool! I'll edit later since I'm also on my phone; a free -3 bytes is a great welcome to PPCG :)

QBasic, 34 bytes
Different approach!
INPUT a,b
?(a OR b)*-(a*b=0OR a=b)

Observe that the nonzero values in the output grid are all the bitwise OR of the two input numbers. This is just a OR b in QBasic. We want to output this value when a*b=0 OR a=b, and 0 otherwise, which we can do by multiplying by the negative of the aforementioned conditional (negative, since truthy is -1 in QBasic).

Batch, 38 36 35 30 bytes
@cmd/cset/a"(%1|%2)>>(%1*%2&2)

Port of @Dennis's Python answer, as conditionals are too expensive in Batch.

Swift, 118 bytes
func c(n1:Int,n2:Int){n1==n2 ? print("\(n1)") : (n1*n2 != 0 ? print("0") : (n1==0 ? print("\(n2)") : print("\(n1)")))}

Welcome to PPCG! I don't know Swift, but you can probably save a lot of bytes by making the variable names 1 character each, and removing whitespace around operators like != and the ternary.

Hi, welcome to PPCG! As mentioned by @Οurous, you can change n1 and n2 to single chars to shorten them; remove some white-spaces and parenthesis, and remove some spaces. In addition, ==0 can be <1 and !=0 can be >0, since we know only the inputs 0,1,2,3 are possible. Never programmed in Swift before either, but I got it down to 91 bytes like this: func c(a:Int,b:Int){a==b ?print("\(a)"):a*b>0 ?print("0"):a<1 ?print("\(b)"):print("\(a)")} Try it online.

In addition, it seems you can shorten it to 51 bytes like this: func c(a:Int,b:Int){print(a==b||a*b<1 ?max(a,b):0)} Try it online. Again welcome to PPCG, and enjoy your stay!

In addition to @KevinCruijssen's golfs, you can turn your submission  into an anonymous closure to save 87 bytes: {$0==$1||1>$0*$1 ?max($0,$1):0} Try it online!

brainfuck, 25 bytes
,>,[>]<<[[->->+<<]>[>]]>.

Input is two byte values (not ascii)

J, 8 7 bytes
1 byte saved by H.PWiz.
>.*=^<.

Try it online!
A J port of H.PWiz's APL solution
= are the numbers equal? (results in 1 or 0)
^ to the power of
<. the smaller number
* multiplied by
>. the larger number

>.*=^<. for 7 bytes

@ H.PWiz Thank you! Clever use of = and^!

05AB1E, 9 8 bytes
àIËIP_+*

-1 byte thanks to @MagicOctopusUrn.
Try it online or verify all test cases.
Explanation:
à         # Take the maximum of the input-list
          #  [0,2] → 2
IË        # Are all elements in the input-list equal?
          #  [0,2] → 0
  IP_     # Take the product of the input-list, and verify if it equals 0
          # (`_` transforms 0 into 1; everything else into 0)
          #  [0,2] → 0 (product) → 1 (==0)
     +    # Add them together (since only 1 is truthy in 05AB1E, this is basically an OR)
          #  0+1 → 1
*         # Multiply both values on the stack
          #  2*1 → 2

Generalized explanation:
IËIP_+    # If both values are equal, or one of them is a zero:
 à        #  Output the maximum of the two values
          # Else:
          #  Output 0

Ës0å~iZë0 was mine; nice one. Not actually sure you can beat 9 bytes by much.

I take that back à®Ë®P_+* where _ is logically equivalent to >Θ

_ turns 0 into 1, all other values into 0.

@MagicOctopusUrn Thanks! When I made this answer I was looking at the docs to see if there was a == 0 command, didn't knew _ does exactly that. Should be useful for other challenges in the future as well. TIL. :)

Python 2, 34 28 bytes
lambda i,j:(i|j,0)[00]

Try it online!
-6 with thanks to @Dennis

[00] saves a few bytes.

Brachylog, 10 bytes
=h|∋0&⌉|∧0

Try it online!

Javascript ES6, 25 22 21 20 bytes
a=>b=>a?b-a?!b*a:a:b

14 13 bytes, If the arguments are provided in sorted order
a=>b=>a%b?0:b

Javascript, 35 bytes
f=(m,n)=>(m||n)&&(m!=n)?(m>n?m:n):0

05AB1E, 6 bytes
ê0ýÙ7è

Try it online!
Port(ish) of my Pyth answer.
TIO header/footer taken from Emigna's answer

QBasic, 38 36 35 bytes
INPUT a,b
?(a*b>0)*(b-a*(a<>b))+a+b

Partly inspired by Erik's IF ... THEN ... ELSE answer, here's a math-only solution.
How I got here
Important note for understanding math-with-conditionals: in QBasic, the results of comparison operators are 0 and -1, not 0 and 1.
We start with Erik's code:
IF a*b THEN?a*-(a=b)ELSE?a+b

In other words, if a and b are both nonzero, then print a*-(a=b) (a if a=b, otherwise 0); else (at least one of a and b is zero), output a+b (the nonzero number, or 0 if they're both zero).
There's already some math with conditionals going on here. Let's take it a step farther and see if we can eliminate the IF statement entirely. We'll have to use a*b>0 for the outer condition: a*b can have multiple different truthy values, which is fine for IF but causes problems for math.
c=a*b>0
?c*a*(a=b)+(c+1)*(a+b)

This is the standard trick of IF-elimination. When c is true, c*a*(a=b) is -a*(a=b) and (c+1)*(a+b) is 0; when c is false, c*a*(a=b) is 0 and (c+1)*(a+b) is a+b. So this expression gives the same results as the IF ... THEN ... ELSE. The only problem is, it makes our program 40 bytes instead of 38. Maybe we can shorten it by rearranging the math.
c=a*b>0
?c*a*(a=b)+c*(a+b)+a+b

Still 40 bytes...
c=a*b>0
?c*(a+b+a*(a=b))+a+b

Now our program is back to 38 bytes. But since we're only using c once, we don't have to assign it to a variable anymore:
?(a*b>0)*(a+b+a*(a=b))+a+b

Now we're down to 36 bytes.
But wait there's more... That a+b+a*(a=b) expression looks a bit redundant. a*(a=b) is -a if a=b and 0 otherwise. When we add it to a, we get 0 if a=b and a otherwise. Maybe we can achieve the same thing in fewer bytes by reversing the condition.
b+a*-(a<>b)

At first, this doesn't look shorter. But we can save a byte by subtracting instead of adding a negative:
b-a*(a<>b)

And there we have our 35-byte solution.

Nice trick over there...

Shakespeare Programming Language, 187 bytes
,.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck]Ajax:Listen tothy!Puck:Listen tothy!Be
you nicer zero?If notyou be I.Am I worse a cat?If notam I as big as you?If notyou zero.Open heart

Try it online!

Vyxal, 15 bytes
?0⁼?0⁼∨??⁼∨??∴*

Try it Online!
Surprisingly no Vyxal answer yet. Return the max, multiplied by the boolean value indicating whether the values are equal or one of them is zero.

Vyxal, 6 bytes
s0pU3i

Try it Online!
Thanks @lyxal for this version which ports the Pyth answer.

Try it Online! for 9 bytes.

or port Pyth for 6 bytes

Japt, 12 9 bytes
Takes input as an array of integers.
×&2?0:Ur|

Try it online!

I had the same, but with logical OR (ª) instead of bitwise.

Jelly, 7 6 bytes
×¬o=a»

Try it online! or Try all combinations!
How?
×¬o=a»   Dyadic link
×        Multiply the two arguments.
 ¬       Logical not. Gives 1 if one argument is 0, 1 otherwise.
   =     Are the two arguments equal?
  o      Logical or the result of = and ¬.
     »   Greater of the two arguments.
    a    Logical and. Gives the greater of the two arguments if they are equal
         or if one of them is zero and gives 0 otherwise.

Using the method in the APL answer, we get the same byte count. One byte longer than that answer because lowest common multiple is two bytes.
6 bytes
«=æl×»

Try it online!

I also note an alternate method below

@H.PWiz Oh, I thought you were using the same method as the one in the link

I give two methods ∧=⌊ and =*⌊. The second of which is prefered by Jelly

@H.PWiz I don't speak APL, I was just using the method you described. What does =*⌊ do?

It's pretty much the same as Jelly, except that ⌊ is minimum. Or one could use × in both languages

Clean, 46 43 42 bytes
import StdEnv
?[a,b]|a<1||a==b=b=0

?o sort

Try it online!
Anonymous composition :: [Int] -> Int, sorts the pair and then matches off the first member.
Doing it as a composed lambda is the same length:
import StdEnv

(\[a,b]|a<1||a==b=b=0)o sort

Python 3, 30 bytes
lambda a,b:0==a*b*(a-b)and a|b

Try it online!
-5 bytes thanks to Oliver
-1 byte thanks to Jo King

TI-Basic, 10 bytes
max(Ans)not(prod(Ans)ΔList(Ans

Multiply maximum value by result of (some element equals zero OR elements are equal)

Yay for opcodes!

C (gcc), 22 bytes
f(x,y){x=x*y&2?0:x|y;}

Try it online!

Does this produce output?

In gcc and without optimizations, yes. It's undefined behavior though. It works because gcc computes x*y&2?0:x|y in the eax register, which is where a proper return statement would move it.

Ah, right. Shouldn't the language of this submission be C (GCC) on x86 then? Or is that not the established convention?

Haskell, 27 bytes
a#b=max a b*0^(a*b*(a-b)^2)

Try it online!

Octave, 28 bytes
@(a,b)~(a*b*(a~=b))*max(a,b)

Try it online!
or
@(a,b)(a==b|~(a*b))*max(a,b)

Try it online!

Explanation:
The maximum value should be outputted if a*b=0 or if a==b. The function takes a and b as inputs. It multiplies a*b, thus getting a zero if one of them is zero, and checks that a~=b, thus getting a zero if the two are equal. We negate both, so that both conditions gives us a truthy value telling us that we should output the maximum value. We then multiply this boolean (0/1) by the maximum value, and outputs it.

26 bytes

05AB1E, 7 bytes
`α*P_*Z

Try it online!
Explanation
`α        # absolute difference of the inputs
  *       # multiplied by the inputs
   P      # product of the result
    _     # logically negated
     *    # multiplied by the inputs
      Z   # max

JavaScript (ES6)
27 bytes
A rather long formula, but without any conditional statement.
a=>b=>(a|4)*(b|4)*6%61%27&3

Try it online!
17 bytes
Simply a port of Dennis' method.
a=>b=>a*b&2?0:a|b

Try it online!

Elixir, 34 bytes
Pretty simple in a functional programming language, just get the first match. No maths here!
fn a,a->a
a,0->a
0,a->a
_,_->0 end

Try it online!

Retina 0.8.2, 20 18 bytes
-2 bytes thanks to Martin Ender.
(.)\1|0
$1
..|^$
0

Try it online!

You can save two bytes by combining the stages a bit: https://tio.run/##BcGhDYBAEERR/@uA5DCXmd0iaIIQEAgMgiCv9@W99/ru56y5rUe1vmweYjK9j31CVRIyCpRY2DhwEiJMBJGkSJNB5g8

@MartinEnder This looks a lot better now, thanks.

R, 35 bytes
rep(unique(sort(c(0,scan()))),4)[4]

Try it online!
Shameless port of Sok's well-explained Pyth answer.

Befunge-93, 20 bytes
&::&*#v_&+.@
@.*!-&<

Try it online!
Explanation
this boils down to:
if(A * B = 0) {
    output (A + B)
    end
} else {
    output A * (A = B)
    end
}

Shakespeare Programming Language, 216 208 bytes
,.Ajax,.Ford,.Act I:.Scene I:.[Enter Ajax and Ford]Ajax:Listen tothy!Ford:Listen tothy!Am I as bad as you?If soyou zero.Is the product ofyou I worse a cat?If soyou be the sum ofyou I.If notyou zero.Open heart

Try it online!
As psuedo-code:
f(a,b):
  if a==b:
    b=0
  if a*b<1:
    b=a+b
  else:
    b=0
  return b

Befunge-93, 17 bytes
&::&-!_&*!\&+*.@.

Try it online!
As psuedo-code:
f(a,b):
  if a-b==0:
    print(b)
  else:
    print((!(a*b))*(a+b))

Python 2, 42 34 bytes
lambda a,b:(0in(a,b)or a==b)*(a|b)

EDIT: -8 thanks to @TIO and @JonathanAllan

a==0 or b==0 can be expressed shorter as 0 in(a,b). TIO

Because the max(a,b) only has any effect when either one of a or b are zero or when a and b are equal it can be replaced by a bit-wise or: (a|b). Some of your spaces are redundant too... lambda a,b:(0in(a,b)or a==b)*(a|b) is 34 bytes (although Dennis's 25 byte solution, lambda x,y:(x|y)>>(x*y&2), also works in Python 2).

JavaScript, 24 Bytes
x=>y=>!x*y|!y*x|(x==y)*x

Allows all numbers, no conditional, doesn't require sorted input

Welcome to PPCG! I don't think this gives the right result for x=0, y=3.

Welcome to PPCG. Great first answer. But sadly this doesn't give the right answer for some values. Also to make it easier for others, you should always provide a link for testing

Prolog (SWI), 27 bytes
N+N+N.
N+0+N.
0+N+N.
_+_+0.

Try it online!
The most naive translation ever.

Glee, 24 22 20 bytes
Idea to append zero taken from Sok’s Pyth solution.
=>n,0& *>0\+ >1~ *n\>>
=>n,0& *>0\+ <2*n\>>             $$<2 instead of >1~ (not > 1)

Explanation:
a b=>n,0& *>0\+ <2*n\>>
a b=>n                      3 1     2 2     0 3     0 0     assign a b to n
      ,0                    3 1 0   2 2 0   0 3 3   0 0 0   catenate 0
        &                   0 1 3   0 2     0 3     0       unique elements
          *>0               011     01      01      0       mark all > 0 (boolean)
             \+             2       1       1       0       reduce by addition
                <2          0       1       1       1       result <2 ?
                  *n        0 0     2 2     0 3     0 0     multiply with n
                    \>>     0       2       3       0       largest element

Old version
=>n--[2]=0|(n\* =0)*n\>>

Explanation for a pair of numbers (a b):
                              result for a b pairs
                               3 1    2 2    0 3
a b=>n--[2]=0|(n\* =0)*n\>>
a b                            3 1    2 2    0 3   create vector (a b)
   =>n                                             assign vector to n
      --                       0 _2   0 0    0 3   calculate the first difference vector of n (monadic --)
        [2]=0                  0      1      0     result vector at index 2 equal to 0 ? (boolean)
              (n\*             3      4      0     n reduced by multiplication
                   =0)         0      0      1     equal to 0 ? (boolean)
             |                 0      1      1     OR (boolean) (dyadic |)
                      *n       0 0    2 2    0 3   multiplied by n (dyadic *)
                        \>>    0      2      3     largest element (monadic \>>)

QBasic 1.1, 38 bytes
INPUT A,B
IF A*B THEN?A*-(A=B)ELSE?A+B

-1 thanks to DLosc.
Input is two comma-separated integers.

Attache, 32 bytes
{If[_=_2,_,If[Min!__,0,Max!__]]}

Try it online!
Takes input as two arguments, such as f[0, 1] = 1.
Other solutions
34 bytes
{If[Same!_,_@0,If[Min!_,0,Max!_]]}

Try it online! The same as above, but takes input as an array
39 bytes
{ToBase[47483073034,5][FromBase&4!_]-1}

Try it online!
Hardcodes the solution in a base-5 integer. More interesting IMO but longer.

Surely base 4 suffices?

Pyth, 11 bytes
e+Z.-+xFQQ{

Try it here
Explanation
e+Z.-+xFQQ{
     +xFQQ      Prepend the XOR of the inputs to the inputs.
   .-     {Q    Remove one copy of the deduplicated (implicit) input.
 +Z             Prepend 0.
e               Take the last.

Alternative solution, 11 bytes
e+0.-F{B+xF

Pyth, 10 bytes
-iFQ&.AQnF

Try it online!

JavaScript (Node.js), 20 bytes
a=>b=>a-b&&a*b?0:a|b

Try it online!

Tcl, 43 bytes
proc M a\ b {expr !$a?$b:!$b?$a:$a-$b?0:$a}

Try it online!

C#, 4827 bytes
(x,y)=>x==y?x:(x*y>0?0:x|y)

Try it online
Thanks @Charlie for the TIO link & helping trim 21 chars off the code

Welcome to the site! I don't know C#, but is it possible to remove the space between > a=? Also, would you mind editing in a link to an online tester, such as Try it online! so that others can test your submission?

You can use this link in your answer, which also reduces your byte-count to just 27 bytes, as a simple lambda expression is a valid answer in code golf.

@cairdcoinheringaahing I have now included TIO link to my answer (Thanks to @Charlie). the space (and the variable) apparently seems to be not required, I wasn't aware on the guidelines around how to use lambda expressions for code golf answers, thanks again to Charlie for pointing it out.

Husk, 4 bytes
-1 thanks to H.PWiz.
!4uΘ

Try it online!

12-basic, 36 bytes
FUNC M(A,B)?(A or B)*(!A~!B|A==B)END

This can probably be shortened.
~ is bitwise XOR (as well as bitwise NOT when used as a unary operator) (Just like in Lua)

Please link to implementation in the answer.

dc, 28 bytes
[pq]sqsidli=qd0rli*0!=qli++p

Try it online!
I'll keep mulling over this, it feels like it must be golfable. [pq]sq just makes a print & quit macro. sidli stores one of our values in the register i, duplicates the other value, and then recalls i. =q consumes two values on the stack, and executes macro q if they're equal (so, prints the one value left behind). d0r duplicates the value on the stack again, and then puts a 0 on the stack in between them. li*0!= loads i, multiplies the two values, and runs q to print the 0 that we left on the stack if the two values were not equal. If none of these things has happened yet, we li to load i, and we now have three values on the stack - two zeroes and our one non-zero value. ++ add the three together, and print.

Perl 5 -p, 25 bytes
/ /;$_=($'|$`)>>($'*$`&2)

Try it online!
Steals the method from @Dennis's Python answer.

PHP - 52 bytes
<?=($a=$argv[1])==($b=$argv[2])?$a:($a*$b?0:$a|$b);

Try it online!
Explanation:
$a==$b  Check for equality, display first value if equal
$a*$b   If multiplication equates to non-zero, display 0 (Unknown) else...
$a|$b   Display the non-zero value.

PHP, 42 40 bytes
[,$a,$b]=$argv;echo$a*$b&&$a-$b?0:$a|$b;

Run with php -r ''   or Try it online.
breakdown
[,$a,$b]=$argv; // import input
echo
    $a*$b       // if both not 0
    &&$a-$b     // and unequal
        ?0      // then print 0
        :$a|$b  // else print the non-zero value, if there is one
;

Q'Nial7, 40 bytes
n is OP A B{2>sum(cull A B 0>0)*max A B}

n is OP A B{                           }    operation n with parameters A B (pair of numbers)
                       A B 0                append 0 to pair of numbers
                  cull                      create list of unique elements
                            >0              create booleans of elements that are > 0
              sum(            )             sum up the booleans
            2>                              sum > 2 ? (boolean)
                               *max A B     multiply boolean with max of A B

result:
     n 0 3
3
     n 1 2
0
     n 2 2
2
     n 0 0
0


text:
Is it an exercise set?
We all know that a lot of exercises only affect one half of your body, so you have to do them twice, once for each side. Such exercises have two counterparts, one for the left side and one for the right. However, there's no need to execute the two counterparts consecutively, as long as the exercises for both sides are in the same order. You may as well switch between sides in your exercise program, but it wouldn't make sense to start some exercises with one side and some with the other.
Challenge
An exercise part is a list of non-zero integers, where its second half consists of the integers of the first half negated and in the same order, and the signs of the integers on each half are equal. The sign of the first half of an exercise part is its leading side.
An exercise set is zero or more exercise parts with the same leading side concatenated together.
Given a list of non-zero integers as input, determine if it is an exercise set. The integers aren't necessarily unique. The list's length isn't necessarily even.
Your solution may not use any of the standard loopholes. You may use any two different consistent values for output. This is code-golf, so the shortest solution wins.
Examples
[-5, -1, -7, -6, -5, 5, 1, 7, 6, 5] is an example of an exercise part. The first half is [-5, -1, -7, -6, -5], and the last half is [5, 1, 7, 6, 5], which is each integer in the first half negated. Additionally, the first half's integers are all of the same sign. This exercise part's leading side is -1.
[3, 6, 5, -3, -6, -5, 1, 6, 4, 3, -1, -6, -4, -3] is an example of an exercise set. Its individual exercise parts are [3, 6, 5, -3, -6, -5] and [1, 6, 4, 3, -1, -6, -4, -3], and they both have leading side 1.
[4, -4, -5, 5], despite only consisting of valid exercise parts, isn't an exercise set, since the first part, [4, -4], has leading side 1, while the second part, [-5, 5], has leading side -1.
Test cases
Valid test cases:
[]
[1, -1]
[1, -1, 1, -1]
[-6, 6, -5, -4, -3, 5, 4, 3]
[-1, -5, -8, 1, 5, 8, -7, -6, -5, -3, 7, 6, 5, 3]
[-1, -5, -8, 1, 5, 8, -1, 1]

Invalid test cases:
[1]
[1, -2]
[1, 2, -3, -1, -2, 3]
[1, 2, 3, -3, -1, -2]
[-1, -5, -8, 1, 5, 8, 7, 6, 5, 3, -7, -6, -5, -3]
[1, 2, 3, 5, 1, 2, 3, 5]
[1, 2, -5, 4, -6, 5, 5, -6]
[1, 2, -1, 3, -2, -3]
[1, -2, 1]
[-1, -1, 1]
[1, -1, 1]

The empty case is an annoyance. And to interpret the words of the challenge I'm not sure if there is a valid way to assign "not exercising at all" to either one side or the other of "is it an exercise set?" But to be honest I'm just whining.

@ngm Was just about to comment this.. Empty list is an annoying edge case.. Personally I would state the input contains at least one item. Apart from that nice challenge, though!

@ngm It's truthy by terms of vacuous truth. Consider it to be proper relaxation. ;)

It's nice to know I can golf and exercise at the same time.

@ngm "It's nice to know I can golf and exercise at the same time." We got more of those kind of challenges. ;)

This is hard AF in 05AB1E.

Python 2, 69 67 bytes
a,b=x=[[],[]];k=0
for n in input():x[n>0]+=n*n,n*k>0;k=n
print a==b

Try it online!

Jelly, 10 bytes
ṁṠŒg$+2/FẸ

Try it online!

JavaScript (ES6), 54 bytes
Optimized version, inspired by Dennis' Python answer.
Returns 0 or 1.
a=>a.map(b=p=x=>b[+(x<0)]+=[x*x,p*(p=x)>0])|b[1]==b[0]

Try it online!

Original version, 74 bytes
a=>a.map(x=>b[i^=p*(p=x)<0&&-~(b[i]+=0)]+=[,x*x],b=[p=0,i=0])|b[1]+0==b[0]

Try it online!
How?
We store the first halves of all exercise parts in b[0] and the second halves in b[1], switching between b[0] and b[1] each time the sign is changing. Entries are squared to get rid of the sign. We prefix each entry with a comma and suffix each part with a 0.
There's some extra logic to handle the 'empty input' edge case at basically no cost (see the comment near the end of the source code).
a =>                    // given the input array a[]
  a.map(x =>            // for each x in a[]:
    b[i ^=              //   access b[i]:
      p * (p = x)       //     we keep track of the previous entry in p
      < 0 &&            //     if p and x have opposite signs:
      -~(b[i] += 0)     //       append a '0' to b[i] and update i: 0 -> 1, 1 -> 0
    ] += [, x * x],     //   append a comma followed by x² to b[i]
    b = [p = 0, i = 0]  //   start with p = 0, i = 0 and b = [0, 0]
  ) |                   // end of map()
  b[1] + 0              // this will append a '0' to b[1] if it was turned into a string
                        // or let it unchanged if it's still equal to zero (integer),
                        // which handles the 'empty input' edge case
  == b[0]               // compare the result with b[0]

R, 91 bytes
Inputs a whitespace-separated vector of numbers. Outputs FALSE for valid and TRUE for invalid.
x=scan()
y=x<0
z=rle(y)
"if"(sum(x|1),any(x[y]+x[!y],z$v==rev(z$v),z$l[!0:1]-z$l[!1:0]),F)

rle gives the run length encoding, in this case of the sequence of positive and negative values.
The completely and totally unfair empty edge case ;) adds a whopping 15 bytes.
Many bytes shaved off by @Giuseppe.
Here is a 92 byte version expressed as a function which is better for testing:
Try it online!

Java 8, 186 183 185 bytes
a->{int i=a.length-1,t,j;boolean r=i%2>0,f;if(i<0)return!r;for(f=a[i]<0;i>0;){for(r&=f==(t=a[j=i])<0;j>0&&t>>>31==a[--j]>>>31;);for(t=i-j,i-=2*t;j>=0&j>i;)r&=a[j+t]==-a[j--];}return r;}

+2 bytes due to a bug-fix for test cases of size 3 (almost all permutations of 1 and -1 at the end of my TIO-link).
Can definitely be golfed.. The challenge looks to-the-point, but it's pretty hard to implement. Especially the test case [4,-4,-5,5] was annoying to fix.. But it works now. Will golf it down from here.
Try it online.
Explanation:
a->{                   // Method with integer-array parameter and boolean return-type
  int i=a.length-1,j,  //  Index integers (`i` starting at the last index)
      t;               //  Temp integer
  boolean r=i%2>0,     //  Result-boolean, starting at true if the input-list is even
          f;           //  Flag-integer
  if(i<0)              //  If the input was empty (edge case)
    return!r;          //   Return true
  for(f=a[i]<0;        //  Set the flag-boolean to "Is the current item negative?"
      i>0;){           //  Loop down over the array
    for(r&=f==(t=a[j=i])<0;
                       //   Set `s` to the current number
                       //   And verify if the initial flag and `s` have the same sign
        j>0            //   Loop `j` from `i` down as long as `j` is larger than 0,
        &&t>>>31==a[--j]>>>31;);
                       //   and both `s` and the current item have the same sign
                       //    Decreasing `j` by 1 every iteration
    for(t=i-j,         //   Set `t` to `i-j` (amount of same signed adjacent values)
        i-=2*t;        //   Decrease `i` by two times `t`
        j>=0           //   Loop as long as `j` is larger than or equal to 0,
        &j>i;)         //   and also larger than `i`
      r&=a[j+t]==-a[j--];}
                       //    Verify if the pairs at index `j+t` and `j`
                       //    are negatives of each other
  return r;}           //  Return if `r` is still true (if all verifications succeeded)

Python 2, 147 130 113 112 106 bytes
from itertools import*
def f(s):l=[map(abs,g)for v,g in groupby(s+[0],0 .__cmp__)];print l[1::2]==l[:-1:2]

Try it online!

Saved:

-27 bytes, thanks to Dennis

lambda n:cmp(n,0) can become 0 .__cmp__. all(a==b for a,b in zip(l[::2],l[1::2])) can become l[:-1:2]==l[1::2].

Retina 0.8.2, 57 bytes
^\b|,\b
$&=
(.)(\d+),(?=\1)
$2_
-|=

.$
$&,
^((\w+,)\2)*$

Try it online! Takes comma-separated input, but link includes header that processes test cases. Explanation:
^\b|,\b
$&=

Insert a marker before each positive integer.
(.)(\d+),(?=\1)
$2_

Change the commas between integers of the same sign to underscores.
-|=

Delete the remaining signs.
.$
$&,

Append a comma if the input is not empty.
^((\w+,)\2)*$

Check that the string consists of pairs of runs of the same integers.

Brachylog, 18 14 bytes
~c{ḍz{ṅᵈ¹ṡ}ᵛ}ᵛ

Try it online!
Saved 4 bytes thanks to @ErikTheOutgolfer.
Explanation
                    Succeed if and only if:
~c                  You can deconcatenate the input list…
  {         }ᵛ      …and verify that for each of the sublists:
   ḍ                  Split it in half
    z                 Zip the elements of each half together
     {    }ᵛ          Verify that for each couple:
      ṅᵈ¹               The first integer is the negation of the second one
         ṡ              Take the sign of the first one
                      All signs should be equal in a sublist
                    All leading signs of the sublists should be equal

Python 2, 111 bytes
x=input()
o=[];p=[]
for a,b in zip(x,x[1:]):
 if 0<a*x[0]:
	p+=a,-a
	if b*a<0:o+=p[::2]+p[1::2];p=[]
print o==x

Try it online!

JavaScript (Node.js), 155 bytes
b=>eval('i=b.length-1;r=i%2;0>i&&!r;for(f=0>b[i];0<i;){for(r&=f==(s=0>b[j=i]);0<j&&s&0>b[--j]|!s&0<b[j];);t=i-j;for(i-=2*t;0<=j&j>i;)r&=b[j+t]==-b[j--]}r')

Try it online!

Inspiration was @KevinCruijssen's answer
Also thanks to him for correcting 2 test cases of mine

Since yours is inspired from my Java answer, you should change r=0<i to r=i%2, since the test cases [1,-1,1] and [-1,1,-1] are failing at the moment. Byte-count remains the same for JS, though.

@KevinCruijssen : Thanks, done

Stax, 13 bytes
Ç¥├W╦╣∩T~≥▌╨c

Run and debug it

APL (Dyalog Classic), 48 bytes
{0::1⋄0≠+/×¨⍵:0⋄(~0∊⊢∨2|⍳∘⍴)2{⍺≡-⍵}/⍵⊂⍨1,2≠/×¨⍵}

Try it online!

source: Stack Exchange

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

sort: votes


text:
Professor at MIT can read minds!
The task is taken from an MIT lecture by Prof. Devadas called You can read minds. A detailed explanation of the trick can be found in the linked video, or in this document. I'll try to explain it in simpler terms.
It turns out this was invented in the 1930's, and is known as the "Five-Card Trick of Fitch Cheney".

The trick goes like this:

Five random cards are chosen from a deck of cards. The audience and your assistant get to see them, but you don't.
Your assistant (with whom you have practiced) will select four of those cards and show them to you in a specific order. Note that the hidden card is not randomly picked from the 5 cards. The assistant picks a/the card that will make the trick work.
You will deduce, based on the information you can gather from the four cards what the fifth card is.

How?
Keep the following two points in mind:

When choosing 5 random cards, you are guaranteed that at least two cards have the same suit1.
The image below shows a circle with all the ranks2. Since it's a circle, it's possible to count: J, Q, K, A, 2, 3 (i.e. modular counting).
You are guaranteed that the hidden card does not have the same rank as the first, since they will be of the same suit (explained below). It's always possible to choose the first card and the hidden cards such that the hidden card is between 1 and 6 ranks higher than the first (when counting in circles). If the first card is 1, then the hidden card will be 2,3,4,5,6 or 7. If the first card is J, then the hidden card will be Q,K,A,2,3 or 4 and so on.

The algorithm:
The first card: This card will have the same suit as the hidden card. The card will also be the reference point you'll use when figuring out the rank of the hidden card.
The 2nd, 3rd and 4th cards decodes a value in the inclusive range 1 ... 6. We'll call the three cards S, M, L (smallest card, middle card, largest card). The values will be encoded like this (lexicographic order):
S M L   -> 1
S L M   -> 2
M S L   -> 3
M L S   -> 4
L S M   -> 5
L M S   -> 6

So, if the rank of the first card is 5, and the remaining three cards have ranks 4 Q 7 (they are ordered S L M), then the last card has rank 5+2=7. You may choose if the ace should be the highest or lowest card, as long as it's consistent.
If several cards share rank, then the suit will determine the order, where C < D < H < S.

Input format:
The four cards will be given as H3 (three of hearts), DK (King of diamonds) and so on. You may choose to take the input the other way around as 3H and KD instead.
The input can be on any convenient format, but you can't combine the list of suits in one variable and the list of ranks in another. 'D5', 'H3' .. and  [['D',5],['H',3] ... are both OK, but 'DHCH',[5,3,1,5] is not. You can't use numbers instead of letters, except for T.
Output
The hidden card, in the same format as the input.

Example
Let's do a walkthrough:
Input:
D3 S6 H3 H9

We know the hidden card is a diamond, since the first card is a diamond. We also know that the rank is 4,5,6,7,8 or 9 since the rank of the first card is 3.
The remaining cards are ordered 6,3,9 ==> M,S,L, which encodes the value 3. The hidden card is therefore 3+3=6 of diamonds, thus the output should be D6.
Test cases:
C3 H6 C6 S2
C9            # The order is LMS (H6 > C6, and 2 < 6). 3+6=9

SQ S4 S3 ST   # (ST = S10. Format is optional)
S2            # The order is MSL. 12+3=2

HA CA DA SA
H2            # The order is SML. 14+1=2

This is code-golf, so the shortest solution in each language wins. Explanations are encouraged!

1There are four suits (Clubs, Diamonds, Hearts and Spades).
2There are 13 ranks, 2,3,4,5,6,7,8,9,10,J,Q,K,A. You may choose to use T instead of 10.

JavaScript (ES6), 130 102 bytes
Takes input as an array of strings in "Rs" format, where R is the rank and s is the suit. Expects "T" for 10's. Aces are low.
a=>(s='A23456789TJQK')[([[R,[,S]],B,C,D]=a.map(c=>[s.search(c[0])+14,c]),R+=D<C|2*((D<B)+(C<B)))%13]+S

Try it online!
How?
We first convert each card into an array [rank, card] where rank is a numeric value in [14...26] and card is the original string.
[[R, [, S]], B, C, D] = a.map(c => ['A23456789TJQK'.search(c[0]) + 14, c])

The rank and suit of the first card are stored in R and S respectively. The three other cards are stored in B, C and D.
For instance, ['3c','6h','6c','2s'] becomes:
[ [ 16, '3c' ], [ 19, '6h' ], [ 19, '6c' ], [ 15, '2s' ] ]
    ^^    ^     <---------->  <---------->  <---------->
    R     S          B             C             D

We then compare each pair in [ B, C, D ]. These elements are implicitly coerced to strings when they are compared with each other:
[ 19, '6h' ] --> '19,6h'

Because both rank and card are guaranteed to consist of exactly two characters, it is safe to compare in lexicographical order.
We compute:
(D < C) | 2 * ((D < B) + (C < B))

Below are all the possible combinations:
 B, C, D | v0 = D < B  | v1 = C < B  | v2 = D < C  | v2|2*(v0+v1)
---------+-------------+-------------+-------------+--------------
 S, M, L |    false    |    false    |    false    |      0
 S, L, M |    false    |    false    |    true     |      1
 M, S, L |    false    |    true     |    false    |      2
 M, L, S |    true     |    false    |    true     |      3
 L, S, M |    true     |    true     |    false    |      4
 L, M, S |    true     |    true     |    true     |      5

Finally, we build the output card using R, S and the above result:
'A23456789TJQK'[(R += D < C | 2 * ((D < B) + (C < B))) % 13] + S

Your variant isn't useless, it's just the wrong choice of base and power! Use 92427**3 and modify k+7 to k+8 to save 1 byte: a=>(k='A23456789TJQK'+92427**3)[[[r,s],...x]=a.map((c,i)=>[k.search(c[0])+10,c[1],i]),(r-k[x.sort().map(c=>k=k*2|c[2])|k+8])%13]+s

187**97 and k+15 also works, but I'm pretty sure those are the only two sets that are shorter for this algorithm.

@asgallant Nice find!

@asgallant 1/34547 with k+14 also works.

Python 2, 143 140 138 136 127 125 124 123 121 bytes
lambda(S,V),*l:S+N[F(V)+int(`map(sorted(l,key=lambda(s,v):(F(v),s)).index,l)`[1::3],3)*3/10]
N='23456789TJQKA'*2;F=N.find

Try it online!
Aces are high

Encodes the three cards by finding their position in a sorted list of the cards (0=smallest, 1=middle, 2=largest):
cards:   [SK, C4, H4]
sorted:  [C4, H4, SK]

ranks:   [ 2            index of SK in sorted
ranks:   [ 2,  0        index of C4 in sorted
ranks:   [ 2,  0,  1    index of H4 in sorted
ranks:   [ 2,  0,  1] = L,S,M

This is converted to an integer in base 3 and multiplied by 3, and divided by 10:
int('201',3) = 19 -> 19*3//10 = 5

The different encodings are:
cards            base3    *3   /10
[0, 1, 2]  012     5      15     1
[0, 2, 1]  021     7      21     2
[1, 0, 2]  102     11     33     3
[1, 2, 0]  120     15     45     4
[2, 0, 1]  201     19     57     5
[2, 1, 0]  210     21     63     6

Saved:

-2 bytes, thanks to ovs

I thought about how I could solve this using a ternary approach when I wrote the challenge, but I didn't figure out a nice way to do it... Multiplying by 3 was clever! Nice answer :)

@StewieGriffin Thanks :)
Now I add a 0 to the end and divide by 10, which looks to be equivalent.

@Arnauld. I've updated the description to hopefully make it a bit clearer what I'm doing.

Jelly, 33 bytes
ØDḊḊ;“TJQKA”p“CDHS”
¢iⱮµḊŒ¿×4+Ḣị¢

Try it online!
Explanation
The first line is niladic. It yields a list of the 52 cards
ØDḊḊ;“TJQKA”p“CDHS”
ØD                   Digits: '0123456789'
  ḊḊ                 Dequeue twice: '23456789'
    ;                Append with...
     “TJQKA”         ...the string 'TJQKA': '23456789TJQKA'. These are the ranks
            p        Cartesian product with...
             “CDHS”  ...the suits.
                     This yields the list of all cards in lexicographic order:
                                 ['2C', '2D', '2H', '2S',
                                  '3C', ...         'AS']

In the main link, ¢ calls the result of the first link which is the list of cards.
¢iⱮµḊŒ¿×4+Ḣị¢
¢              List of cards
 iⱮ            Index of each (Ɱ) of the inputs in the list.
   µ           New monadic link. The list of indices become this links argument.
    Ḋ          Remove the first one.
     Œ¿        Index of the permutation of the last three items. Gives a number 1-6
               as described in the problem statement.
       ×4      Multiply this by 4 so that when we add to the index of the first
               card we end up in the same suit.
         +Ḣ    Add the first index.
           ị   Use this number to index into...
            ¢  ...the list of cards.

You can't use 1 for ace.

@EriktheOutgolfer changed back to A

You can use the register to save a byte

APL (Dyalog Unicode), 49 bytesSBCS
⊃x⌽⍨⊃i-4×2-⌊1.8⊥⍋1↓i←⎕⍳⍨x←,⍉'CDHS'∘.,2↓⎕D,'TJQKA'

Try it online!
Overview: 'CDHS'∘.,2↓⎕D,'TJQKA' generates the outer product, so a 2d matrix with (C2 C3 C4 ...), (D2 D3 D4 ...), .... We then transpose this matrix to get (C2 D2 H2 ...), ... and then flatten that.
Thanks to @ngn for the 2-⌊1.8⊥, which takes the order of cards (SML=1 2 3) and grades them (like the 1 to 6 in the OP).
Code explanation:
⊃x⌽⍨⊃i-4×2-⌊1.8⊥⍋1↓i←⎕⍳⍨x←,⍉'CDHS'∘.,2↓⎕D,'TJQKA'
                                       ⎕D,'TJQKA' ⍝ Concatenate a list of numbers with TJQKA
                                     2↓           ⍝ Drop 2 (removes "01")
                                  ∘.,             ⍝ Generate the outer product of this prefixed with
                            'CDHS'                ⍝ The suits
                           ⍉                      ⍝ Invert rows/columns
                          ,                       ⍝ Flatten (matrix -> array)
                        x←                        ⍝ Store in x
                      ⍳⍨                          ⍝ Inverted ⍳⍨: find the indices, in our cards,
                     ⎕                            ⍝ of the argument cards
                   i←                             ⍝ Store these indices in i
                 1↓                               ⍝ Remove the first index
                ⍋                                 ⍝ Grade: get ordered indices
         2-⌊1.8⊥                                  ⍝ The magic happens here: get the number from 1 to 6
       4×                                         ⍝ Multiply by 4 to get the same "back" on the card
    ⊃i-                                           ⍝ Substract the result from our first index (which we had discarded)
⊃x⌽⍨                                              ⍝ (Modulated) Index into x (our cards) with this value

Retina, 218 208 bytes
[JQK]
1$&
T`AJQK`1123
*' G0`
\d+
5**
' G, 1,`
T`CD\HS`d
\d
*
/^(_+)¶\1/(/¶(_+)¶\1/(K`1
/^(_+)¶_+¶\1/(K`2
))K`4
/^(_+)¶_+¶\1/(K`3
/¶(_+)¶\1/(K`5
)))K`6
\d
$+3-$&
(\d+)-(\d+)
$1*_$2*
_{13}(_+)|(_{1,13})
$.($1$2

Try it online!
Explanation:
[JQK]
1$&
T`AJQK`1123

Replaces Aces, Jacks, Queens and Kings with 1, 11, 12 and 13. The first two lines prepend a 1 before the letter, and the last transliterates the second digit.
*' G0`

The * indicates that this stage should not modify the working string. This may make the stage seem pointless, but it will be useful later. The ' splits the working string at every space, and G0 takes the first one (so it finds the first card).
\d+
5**
' G, 1,`'

The first two lines multiply the numbers on the cards by 5, then turn them into unary (for example, 5 is represented as _____), so that we can add smaller amounts for suits later. The final line splits on spaces and keeps the last three cards.
T`CD\HS`d
\d
*

This converts Clubs, Diamonds, Hearts and Spades to 0, 1, 2 and 3 respectively, and turns the number into unary. Since it is now on the attached of the number part of the card, it will give a unique value for the card, determining how high it is.
/^(_+)¶\1/(/¶(_+)¶\1/(K`1
/^(_+)¶_+¶\1/(K`2
))K`4
/^(_+)¶_+¶\1/(K`3
/¶(_+)¶\1/(K`5
)))K`6

This finds the ordering of the cards, and the value to add to the first card. For example, on the first line /^(_+)¶\1_+/( matches orders that have the middle value larger than the first value. It creates an if-else loop for what to do (as this order matches permutations 1, 2 and 4). K marks a constant.
\d
$+3-$&

Remember earlier when we used * to indicate that a stage wouldn't affect the working string? This is where we use it. This stage is a replace stage; it replaces the number to add by $+3-$&. $+3 accesses the * stage, and gets the suit and number of the first card, - acts as a seperator, and $& is the match. So the working string is now {suit}{original number}-{number to add}
(\d+)-(\d+)
$1*_$2*

This turns the two numbers into unary and adds them together.
_{13}(_+)|(_{1,13})
$.($1$2

The top line captures either the number or the number - 13 (so that we don't get outputs of e.g S16). The bottom line turns the captured number back into base 10, and the result is printed implicitly.

Fixed! I reversed a regex so that it prioritised numbers larger than 13

Charcoal, 64 62 bytes
≔⪪⭆⁺⭆⁸⁺²ιTJQKA⭆CDHS⁺λι²δ≔Ｅ⟦ηζε⟧⌕διυ§δ⁺⌕δθ×⁴⊕⁺∧⌕υ⌊υ⊗⊕¬⌕υ⌈υ‹⊟υ⊟υ

Try it online! Link is to verbose version of code. Uses T for 10 and sorts A high. The permutation index was not very easily decoded; a different permutation order would have saved me at least three bytes. Explanation:
⁺⭆⁸⁺²ιTJQKA

Add 2 to all the integers 0 to 7, then concatente them and suffix TJQKA for the picture cards and ace. This saves 2 bytes over a string literal, although it turns out that having A high would have saved a byte through string compression anyway.
≔⪪⭆...⭆CDHS⁺λι²δ

Map over the cards and the suits, concatenting the two together. Since this would normally produce a nested array, the results are instead concatenated into a single string which is then split up into pairs of characters again.
≔Ｅ⟦ηζε⟧⌕διυ

Find the positions of the second, third and fourth cards.
⊕⁺∧⌕υ⌊υ⊗⊕¬⌕υ⌈υ‹⊟υ⊟υ

Compute the 1-indexed permutation index. The first two permutations have the smallest card first; this is tested via ⌕υ⌊υ. The other two pairs of permutations are differentiated as to whether the largest card is first; this is tested via ⌕υ⌈υ. Logical and arithmetic operations then map these tests to the values 0, 2 and 4; this is then increased by 1 depending on the comparison between the third and fourth cards, tested via ‹⊟υ⊟υ. Finally the index is incremented to give the desired encoding.
§δ⁺⌕δθ×⁴...

Multiply that by 4 repesenting the distance between cards of the same suit, add on the position of the first card, and cyclically index and print the result.

Python 2, 147 bytes
lambda a:a[0][0]+R[h(map(a[1:].index,sorted(a[1:],key=lambda c:(I(c[1]),c))))+I(a[0][1])]
R='A23456789TJQK'*2;I=R.index
h=lambda(x,y,z):x*2+(y>z)+1

Try it online!

144 bytes

Pyth, 42 bytes
+hhQ@J+`M}2Tmk"JQKA"+hhKm,xJtdhdQhx.pStKtK

Really ugly...
Try it online: Demontration or Test Suite

T-SQL, 200 bytes
Input is a table variable. Using T for 10, aces are low
Format for cards rank/suit KH,6D,TS
DECLARE @ TABLE(c char(2),i int identity(4,-1))
INSERT @
VALUES('2C'),('5H'),('4S'),('3C')

SELECT
substring(max(h+h),max(charindex(q,h)*w)+sum(power(3,i)*r)/10-4,1)+max(right(c,w))FROM(SELECT
rank()over(order
by w,charindex(q,h),c)%4r,*FROM(SELECT'A23456789TJQK'h,i/4w,left(c,1)q,*FROM @)d)y

Try it online ungolfed
Notice how the SML(1-6) value is calculated:
Logically S,M,L(1,2,3) is converted to a numeric value

first card is valued 27*sequence value
second card is valued 9*sequence value
third card is valued 3*sequence value

J, 68 bytes
r=.'23456789TJQKA'
{:@{.,~0{r|.~1+(r i.0{{.)+(>,{r;'CDHS')A.@/:@i.}.

Try it online!
Note: -3 off TIO bytes because the f=. doesn't count.  Will attempt to golf further and add explanation tomorrow.

JavaScript (Node.js), 124 bytes
s=>(k='23456789TJQKA')[p=t=>k.search(s[t][0])+32+s[t][1],u=p(0),(u[0]+u[1]-2*(p(1)<p(2))-2*(p(1)<p(3))-(p(2)<p(3)))%13]+u[2]

Try it online!
JavaScript (Node.js), 125 bytes
s=>(k='23456789TJQKA')[p=s.map(t=>k.search(t[0])+32+t[1]),u=p[0],(u[0]+u[1]-2*(p[1]<p[2])-2*(p[1]<p[3])-(p[2]<p[3]))%13]+u[2]

Try it online!

05AB1E, 37 bytes
2TŸ.•3u§•S«.•ôì•âíJuDIkćsD{œJsJk>4*+è

Port of @dylnan's Jelly answer, but unfortunately 05AB1E doesn't have the permutation index builtin..
Try it online or verify all test cases.
Explanation:
2TŸ                # Push the list [2,3,4,5,6,7,8,9,10]
   .•3u§•S         # Push compressed string "jqka", converted to a list of characters
          «        # Merge the lists together
.•ôì•              # Push compressed string "cdhs"
     â             # Create each possible pair
      í            # Reverse each pair
       Ju          # Join each pair together, and convert to uppercase
D                  # Duplicate the deck
 Ik                # Get the index of the cards of the input-list in the deck
   ć               # Extract head; pop and push remainder and head
    s              # Swap to get the remainder
     D{            # Create a sorted copy
       œ           # Get the permutations of that
        JsJk       # Get the index of the unsorted permutation in this permutations list
            >      # Increase it by 1 (since 05AB1E has 0-based indexing)
             4*    # Multiply it by 4
               +   # Add it to the extracted head
                è  # And index it into the duplicated deck
                   # (after which the result is output implicitly)

See this 05AB1E tip of mine (section How to compress strings not part of the dictionary?) to understand why .•3u§• is "jqka" and .•ôì• is "cdhs".

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


text:
Recording xiangqi moves
The game of xiangqi, also known as Chinese chess, is a chess-like game popular in China, Vietnam, Taiwan, and other East Asian countries. The colours of the two sides in xiangqi are red and black. There are 16 black pieces in xiangqi: the 1 general (G), 2 advisor (A), 2 elephant (E), 2 horse (H), 2 chariot (R), 2 cannon (C), and 5 soldier (S). The vertical lines are known as files (columns), and the horizontal lines are known as ranks (rows).

A notation system partially described in A Manual of Chinese Chess and used by several computer software implementations describes moves in relative terms as follows:
[single-letter piece abbreviation][former file][operator indicating direction of movement][new file, or in the case of purely vertical movement, number of ranks traversed]

The file numbers are counted from each player's right to each player's left. For black, the file numbers are shown in the picture, white background.
In case there are two identical pieces in one file, symbols + (front, higher rank) and - (rear, lower rank) are used instead of former file number. If there are more than two, +(highest rank), 2(2nd highest rank), 3(3rd highest rank), ... is used. It's fine either you use the number or - to mean the lowest rank if more than two exist. If more than one file contain multiple identical pieces, both former file and order can't be omitted, but the piece abbreviation can be omitted.
[former order in the file][single-letter piece abbreviation][operator indicating direction of movement][new file, or in the case of purely vertical movement, number of ranks traversed]
[former order in the file][former file][operator indicating direction of movement][new file, or in the case of purely vertical movement, number of ranks traversed]

A plus sign(+) is used to indicate forward movement. A minus sign(-) is used to indicate backwards movement. A dot or period(.) or equal sign(=) is used to indicate horizontal or lateral movement. For a piece that moves diagonally, the plus or minus sign is used rather than the period.
Thus, if the five soldiers are at (5,6), (7,6), (9,6), (5,8), (7,8), then each of them moving one rank forward are expressed as -5+1, -7+1, S9+1, +5+1, +7+1; two horses at (3,4) and (3,8) each moving to (4,6) are expressed as -H+4 and +H-4; five soldiers are at (5,6), (7,6), (5,4), (5,8), (7,8), then each of them moving one rank forward are expressed as 25+1, -7+1, 35+1, +5+1, +7+1; two horses at (3,4) and (5,8) each moving to (4,6) are expressed as 3H+4 and 5H-4.
Given the current position and destination of the piece to move, and a list/set containing all positions of the same kind of pieces, output its expression. Input format is quie flexible. Shortest code win.
Samples: (use format that first item of the array is moved)
S [(5,6), (7,6), (9,6), (5,8), (7,8)] (5,7) -> -5+1 or -S5+1
S [(7,6), (5,6), (9,6), (5,8), (7,8)] (7,7) -> -7+1 or -S7+1
S [(9,6), (5,6), (7,6), (5,8), (7,8)] (9,7) -> S9+1
S [(5,8), (5,6), (7,6), (9,6), (7,8)] (5,9) -> +5+1 or +S5+1
S [(7,8), (5,6), (7,6), (9,6), (5,8)] (7,9) -> +7+1 or +S7+1
H [(3,4), (3,8)]                      (4,6) -> -H+4
H [(3,8), (3,4)]                      (4,6) -> +H-4
H [(3,8)]                             (4,6) -> H3-4
S [(5,4), (5,8), (7,8), (5,6), (7,6)] (5,5) -> 35+1 or -5+1 or 3S5+1 or -S5+1
S [(5,6), (5,8), (7,8), (5,4), (7,6)] (5,7) -> 25+1 or 2S5+1
S [(5,8), (5,6), (7,8), (5,4), (7,6)] (5,9) -> +5+1 or +S5+1

Pieces starting places and moving rules about from place(x0,y0), to place(x,y) and their distance r, if that helps:
G (5,1)      r=1 & 3<x<7 & y<4
A (4,1)(6,1) r^2=2 & 3<x<7 & y<4
E (3,1)(7,1) r^2=8 & y<6
H (2,1)(8,1) r^2=5
R (1,1)(9,1) (x-x0)(y-y0)=0
C (2,3)(8,3) (x-x0)(y-y0)=0
S (1,4)(3,4)(5,4)(7,4)(9,4)
             r=1 & y>=y0 & (y>y0 | y>5)

You should consider adding a minimum formatting, such as 'Task summary / Input / Output / Detailed rules'. This looks like an interesting challenge but is really hard to read as-is.

Stax, 63 bytes
÷Qa9═wë•Θ╣äUuâ£▼+∙8WU▓kw≈▲!.┤α@∟┐₧╨═ºî⌂z▼0╬⌂6╕ú▄O&⌂¼^Mgâ╗╕.î¡☼:

Run and debug it
Takes input as <position before> <piece type> [<other pieces>] <position after>.
Unpacked:
;x\EE-c:+"=+-"@s|aaE=s,h?$+Ydx]+MEsxh|I@|oc%vcaHX-xn^$'-?'+?z?,b'S<*!,h$*++y+

Run and debug it
Explanation:
The first part calculates the last part: The direction of movement and the resulting file/change in rank:
;x\EE-c:+"=+-"@s|aaE=s,h?$+Yd
;x                            Push position after and before
  \                           Zip -> [[file after, file before], [rank after, rank before]]
   E                          Push files and ranks separately
    E-                        Difference in ranks (after - before)
      c:+                     Copy and get the sign (-1, 0, +1)
         "=+-"@               Index into the string "=+-" (-1 means last one)
               s|a            Get the absolute value of the difference in rank
                  aE=         Check whether file before = file after (pure vertical movement)
                     s        Swap with abs of difference in rank
                      ,h      Get file after
                        ?     If file before = file after:
                                abs(rank after - rank before)
                              Else:
                                file after
                              (this is the number in the end)
                         $    Convert to string
                          +   Concat the sign (-=+) and number.
                           Yd Store in Y register and delete from stack.

The second part calculates the index in the file (+, - or a digit):
x]+MEsxh|I@|oc%vcaHX-xn^$'-?'+?z?
x]+                               Append the position before to the list of other pieces
   ME                             Push list of files, then list of ranks
     s                            Swap the two
      xh|I                        Find indices with file = file before
          @                       Get ranks of these
           |o                     Calculate destination index of each element if the ranks were sorted
             c%v                  Get length of the array - 1
                                    (no. of other pieces in file)
                ca                Get the array of dest. indices again
                  HX              Get the last index (= index of the moving pieces)
                                    and store in register X
                    -             Then subtract from the no. of other pieces
                     xn^          ... and increment the result
                                    -> That's the index from big rank to small
                        $         ... and convert to string
                         '-?      If register X = 0 (lowest rank): "-"
                                  Else: The index from big to small
                            '+?   If index from big to small = 0 (high rank): "+"
                                  Else: Result from above
                               z? If length of array = 1: ""
                                  Else: Result from above

So this means:

If there are no other pieces in this rank, ""
Else if we have the highest rank, "+"
Else if we have the lowest rank, "-"
Else, the index of the rank as a string

These conditionals work in a somewhat special way: First, all the conditions are produced, most important to least important, then the true branch of the first condition is made (the index as a string). After this we push the falsy value for each condition, least important to most important, directly before performing the conditional ?.
The third part checks whether we need to add the file number:
,b'S<*!,h$*
,           Get the piece type
 b          Copy both the result of part 2 and the piece type
  'S<       Test whether the piece type is NOT "S"
              (actually less than "S", because all other piece types come before S in ASCII)
     *      Repeat the result of part 2 by the result of this test:
            "" if the piece type is "S"
            the result of part 2 otherwise
      !     Negate this, "" is falsey.
            => This means NOT (part 2 is empty AND NOT piece type is "S")
            => Part 2 is empty iff this is the only piece in the file
            => NOT (only piece in file AND NOT piece type is "S")
            => NOT only piece in file OR piece type is "S"
       ,h   Push the file before
         $  and convert it to string
          * Repeat that string by the result of above check:
            "" unless other pieces in file or piece type is "S"

So, after parts 1-3, the stack looks like this:
<position in the file (+, -, or number)> <piece type> <file if necessary>

And the Y register contains the movement itself (from part 1).
The final part combines these into a single string:
++y+ "<position in the file>" "<piece type>" "<file if necessary>"
+    "<position in the file>" "<piece type><file if necessary>"
 +   "<position in the file><piece type><file if necessary>"
  y  "<position in the file><piece type><file if necessary>" "<movement>"
   + "<position in the file><piece type><file if necessary><movement>"

This final result is implicitly output.

Wow, you just answered a question that went unanswered for 2 years. Nice job!

[5,8] "S" [[5,6]]                      [5,9] file should be omitted


text:
Validate Sudoku (N by N)
Challenge :
Create a random (pseudo random) Sudoku board with dimension n x n

Input :
Given :

n where :
2 < n < 100

Output :
true / false depending on whether the board is valid or not.

Examples :
For n = 3 :
[7, 8, 4, 1, 5, 9, 3, 2, 6], [5, 3, 9, 6, 7, 2, 8, 4, 1], [6, 1, 2, 4, 3, 8, 7, 5, 9],

[9, 2, 8, 7, 1, 5, 4, 6, 3], [3, 5, 7, 8, 4, 6, 1, 9, 2], [4, 6, 1, 9, 2, 3, 5, 8, 7],

[8, 7, 6, 3, 9, 4, 2, 1, 5], [2, 4, 3, 5, 6, 1, 9, 7, 8], [1, 9, 5, 2, 8, 7, 6, 3, 4]

This is ^ the random generated board.
Output : true

Note :

This is code-golf so shortest code in bytes (for each programming language) wins.
Given input n will always be an integer (non-decimal value) and between the two mentioned constrains

In my opinion, this is too close to this, but I won't hammer it...

We're supposed to create a random board then decide whether it is valid? Maybe simply generating a random valid board would be a better challenge.

@StewiwGriffin I’ve read both challenges carefully and I think that the differences are insignificant, so I chose to hammer-close it as a dupe. If I would have had the option to VTC but not hammer, I would have done so.

@Mr.Xcoder : I disagree with you

I think it's a duplicate, too. There is already a challenge for validating, so the only difference is that you need to generate a random 9x9 matrix. So basically the entire hard (challenge) part already exists elsewhere on the site.

@MuhammadSalman Feel free to, this is solely my opinion.

@MuhammadSalman If you change the challenge to my suggestion above I think it would be reopened and it would be a good challenge

@dylnan Still not that different. Then it's just do { x = random_board(); } while ( invalid_board(x) );

@user202729 true. Maybe if you were asked to generate a valid board at size of the input that didn’t need to be random it wouldn’t be the same method


text:
Sort a string by a given ordering
Your challenge is to sort a string, but rather than by the normal alphabetical order (abc..xyz), you will be sorting strings by a specified alphabet.
You must write a program or function that takes two inputs: An alphabet A and an string S. Both will only contain lowercase English letters, and both will contain at least one character.
You must move letters in S so that the letter that appears first in A appears first, then whichever letter appears second in A, etc. There may be some letters in S that do not appear in A, these should be left at the end and not moved around relative to each other.
Test cases:
A       S               Result
axd     haxuizzxaxduxha aaaxxxxdhuizzuh
a       xyz             xyz
abc     dcba            abcd
il      nmiuplliu       iillnmupu
asdf    qwerty          qwerty

Fewest bytes wins!

Can we print/return an array of singleton strings? Can we take one string and one array of singleton strings as input?

@Dennis Yes, both are fine representations of strings.

Can we take either or both inputs as an array of individual characters?

@Shaggy A string is a character array, so yes.

05AB1E, 4 bytes
Rvy†

Try it online!
Explanation
R     # Reverse the alphabet
 vy   # For each letter ...
   †  # Push S with the current letter filtered to the front

Smarter than Σ²sk>.

Too bad about R€† working as expected though :). Sometimes that can work as a smaller vy loop. Nice answer man.

Python 3, 50 47 46 44 bytes
-3 bytes thanks to ngn!
-1 byte thanks to mypetlion
lambda a,s:s.sort(key=lambda c:a.find(c)%27)

Try it online!
Takes in a string as the alphabet and a list of chars as the string and sorts the list in place.
The %27 ensures that if the character is not in the alphabet, the index returned puts it after the rest of the alphabet.

-a[::-1].find(c) -> (a+c).find(c)

(a+c).find(c) -> a.find(c)%27 to save 1 byte

Haskell, 42 bytes
a#s=[c|c<-a,d<-s,c==d]++[c|c<-s,all(/=c)a]

Try it online!
a#s=                     -- take alphabet a and string s
        c<-a             -- for all c in a
             d<-s        --   for all d in s
    [c|       c==d]             keep c if c equals d
   ++                    -- append
    [c|c<-s        ]     --   all c of s
         ,all(/=c)a      --   that are not in a

Perl 6,  55  43 bytes
->\A,\S{[~] S.comb.sort:{%(A.comb.antipairs){$_}//∞}}

Try it
->\A,\S{[~] S.comb.sort:{A.index($_)//∞}}

Try it
Expanded:
-> \A, \S {
  [~]  # reduce using &infix:«~» (shorter than `.join`)

    S.comb.sort: # split into character list and sort by:

      {  # bare block lambda with implicit parameter $_

        A.index( $_ ) # get the position

        //  # if it is undefined (not in `A`)
        ∞   # return Inf instead (so it comes at end of result)
      }
}

Since there will only be up to 26 different characters in the input, and ∞ is 3 bytes, you can replace it with 27 and it'll still work and save a byte.

Stax, 6 bytes
{xrINo

Run and debug it
This sorts by a block that does this.

Reverse the alphabet.
Get the index of each character in the reversed alphabet. Missing yields -1.
Negate the index.

Haskell, 40 34 bytes
-6 bytes huge thanks to Laikoni.
foldr(\c->r(==c)<>r(/=c))
r=filter

Try it online!
The first line is an expression that takes two arguments: S and A.

Nice! You can even drop f= because anonymous functions are allowed.

Furthermore (<>) is now in Prelude, so this can be shortened to foldr(\c->r(==c)<>r(/=c)) for 34 bytes: Try it online!

Python 2, 38 bytes
def f(a,s):s.sort(None,a[::-1].find,1)

a must be a string, s a list of strings of length 1. f sorts s in place.
Try it online!
Alternate version, string I/O, 48 bytes
lambda a,s:`sorted(s,None,a[::-1].find,1)`[2::5]

Try it online!
How it works
s.sort(None,a[::-1],1) is shorthand for s.sort(cmp=None,key=a[::-1],reverse=1).
From the docs:

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

TIL sort can take 4 arguments.

Only in Python 2. Python 3 deprecated cmp and made key and reverse keyword-only arguments, so its list.sort takes only one positional argument.

K (ngn/k), 9 bytes
{y@>-x?y}

Try it online!
{...} is a function with arguments x and y
x?y finds for each element in y the index of its first occurrence in x; if an element is not found in x, its index is considered 0N (-263)
- negates all indices except that it keeps the 0N-s intact, because 263≡-263 (mod 264)
> returns a sort-descending permutation
y@ indexes y with that

J, 5 bytes
]/:i.

Dyadic verb, taking the alphabet on its left and the string to be sorted on the right.
i.  finds the indeces of string's characters in the alphabet, the alphabet length if not found.
   'axd' i. 'haxuizzxaxduxha'
3 0 1 3 3 3 3 1 0 1 2 3 1 3 0

/: sorts its left agrument according to the order specified in the right one.
] the rigth argument (the string)
  'haxuizzxaxduxha' /: 3 0 1 3 3 3 3 1 0 1 2 3 1 3 0
aaaxxxxdhuizzuh

Try it online!

APL (Dyalog Unicode), 5 bytesSBCS
Anonymous tacit prefix function, taking [string,ordering] as argument.
⍋⍨/⌷⊃

Try it online!
…/ Reduce by the following function:
  …⍨ namely the reversed-arguments version of the following function:
  ⍋ grade the right string according to the left ordering (missing letters go at the end)
⌷ use that to index into…
⊃ the first element of the argument (i.e. the string)

Python 2, 35 50 bytes
lambda a,s:sorted(s,key=lambda c:-a[::-1].find(c))

Try it online!
Takes a and s as strings; returns a list of singelton strings.
Note: Ouch! Gained 15 bytes to fix...

Ha! This is actually exactly the same as my original code for my answer. Great minds think alike

@Jo King: Stop controlling my thoughts! :)

Charcoal, 13 bytes
Ｆθ×ι№ηιΦη¬№θι

Try it online! Link is to verbose version of code. Explanation:
 θ              First input
Ｆ               Loop over characters
     η          Second input
      ι         Current character
    №           Count matches
   ι            Current character
  ×             Repeat
                Implicitly print
        η       Second input
       Φ        Filter
           θ    First input
            ι   Current character
          №     Count matches
         ¬      Logical not
                Implicitly print non-matching characters

JavaScript (SpiderMonkey), 50 bytes
Takes input in currying syntax (a)(s), where a is a string and s is an array of characters. Returns an array of characters.
a=>s=>s.sort((b,c)=>(g=c=>-1/a.search(c))(b)-g(c))

Try it online!
How?
We define the helper function g() as:
c => -1 / a.search(c)

which returns:

1 if c does not belong to the alphabet
a float value in [-Inf, 0) based on the position of c in the alphabet otherwise (-Inf, -1, -1/2, -1/3, etc.)

We sort s[ ] by computing g(b) - g(c) for each pair of characters (b, c) passed to the callback of sort().
Because the implementation of sort() in SpiderMonkey is stable, all characters of s[ ] that do not belong to the alphabet are simply moved at the end in order of appearance and are let unchanged when they are compared with each other.

JavaScript (ES6), 61 bytes
Takes input in currying syntax (a)(s), where both a and s are arrays of characters. Returns a string.
a=>s=>a.map(C=>s=s.filter(c=>c!=C||!(o+=c)),o='')&&o+s.join``

Try it online!

Jelly, 4 bytes
fⱮ;ḟ

A dyadic link accepting the string on the left and the alphabet on the right (as lists of characters) and returning the result (also as a list of characters).
Try it online!
How?
fⱮ;ḟ - Link: string; alphabet                                    e.g. smallnotxl; xl
 Ɱ   - map (for each character in the alphabet):                      1=x; 2=l
f    -   filter keep (keep occurrences of this character from string)   x    lll -> xlll
   ḟ - filter discard (discard all alphabet characters from string)   smanot
  ;  - concatenate                                                    xlllsmanot

R, 69 62 58 bytes
function(a,s)c(rep(a,rowSums(outer(a,s,"=="))),s[!s%in%a])

Try it online!
Input and output are vectors of individual characters.
Explanation:
function(a,s)c(                              ,           ) #combine:
                   a,                                      #[each char in a
               rep(                                        #each repeated
                     rowSums(               )              #the number of
                             outer(a,s,"==")               #occurrence in s]
                                              s            #with s
                                               [ s%in%a]   #all chars in a
                                                !          #omitted

Brain-Flak (BrainHack), 118 bytes
{({}(<>))<>}{}<>{<>([[]()]<{<>(({})<({}<>[({}<>)]){(<()>)}{}{}>)<>}<>({}<{({}<>)<>}<>>)>[]){({}()<(({}))>)}{}{}<>{}}<>

Try it online!
Input is the first string, followed by a null, followed by the second string.  A version that uses a newline as the separator instead adds 24 bytes:
Brain-Flak, 142 bytes
(()){{}(({}(<>))[(()()()()()){}]<>)}{}<>{<>([[]()]<{<>(({})<({}<>[({}<>)]){(<()>)}{}{}>)<>}<>({}<{({}<>)<>}<>>)>[]){({}()<(({}))>)}{}{}<>{}}<>

Try it online!
Explanation
# Move A to other stack reversed
# Zeroes are pushed under each character for later.
# (This is the only part that needs to change in order to use newline as separator.)
{({}(<>))<>}{}<>

# For each character in A, starting at the end:
{

  # Track current length of S.
  <>([[]()]<

    # For each character in S:
    {

      # While keeping character from A
      <>(({})<

        # Move character from S to second stack and push difference
        ({}<>[({}<>)])

        # Delete character if equal
        {(<()>)}{}{}

      >)

    <>}

    # Move S back to first stack while maintaining character from A
    <>({}<{({}<>)<>}<>>)

  # Push difference between old and new lengths of S
  >[])

  # Insert character from A at beginning of S that many times
  {({}()<(({}))>)}{}{}

<>{}}<>

C (gcc), 97 bytes
f(D,d,S,s,i,o)char*D,*S;{
  while(d--){
    for(i=o=s;i--;)S[i]-D[d]?S[--o]=S[i]:0;
    while(o--)S[o]=D[d];
  }
}

All whitespaces (spaces and newlines) in the code above are only for readability and should be removed.
The dictionary is passed in D and have length d, the string is passed in S and have length s. i and o should be omitted.
Try it online!

Pyth,  9  5 bytes
ox+vz

Try it here!

ox+vz    Full program. Input format: "S" \n "A".
o        Sort the characters of S by (variable: N)...
 x       ... N's index in...
  +vz    ... A + N

Perl 5 with -pF, 43 bytes
$_=<>;print$F[0]x s/@{[shift@F]}//g while@F

Try it online!

Isn't there a flag that gives you $_=<>; for free?

@Pavel yeah, sorry I'm using it to populate @F, but I didn't add it to the header! I'll do that now! Thank you!

You can cut 10 bytes off this and still use the same logic: Try it online!

Java 8, 98 bytes
a->s->{for(int i=a.length;i-->0;s=s.replaceAll("[^"+a[i]+"]","")+s.replaceAll(a[i],""));return s;}

Try it online.
Explanation:
a->s->{       // Method with String-array and String parameters, and String return-type
  for(int i=a.length;i-->0;
              //  Loop backwards over the alphabet
    s=        //   Replace the current `s` with:
      s.replaceAll("[^"+a[i]+"]","")
              //    All the current characters of `a` in `s`
      +s.replaceAll(a[i],""));
              //    Concatted with everything else
  return s;}  //  Return the modified `s`

Couldn't go lower, even with Java 11's new String.repeat(int) method. Nice! :)

@OlivierGrégoire Oh, didn't knew early access to Java 11 was already available. That .repeat(n) looks promising, though. :D

Prolog (SWI), 136 bytes
X/_/[X|_].
X/Y/[Z|R]:-Y\=Z,X/Y/R.
i(_,X,[],[X]).
i(A,X,[Y|R],[X,Y|R]):-X/Y/A.
i(A,X,[Y|R],[Y|S]):-i(A,X,R,S).
A*S*T:-foldl(i(A),S,[],T).

Try it online! Example usage:
[i,l]*[n,m,i,u,p,l,l,i,u]*S.
S = [i, i, l, l, n, m, u, p, u]

Clean, 61 bytes
import StdEnv
$a s=[c\\c<-a,k<-s|k==c]++[c\\c<-s|all((<>)c)a]

Try it online!
Defines the function $ :: [Char] [Char] -> [Char].
Unsurprisingly, this is literally nimi's Haskell answer but longer.

Jelly, 7 bytes
i@oİ$¥Þ

Try it online!

APL+WIN, 12 bytes
Prompts for screen input of S then A:
s[(,⎕)⍋s←,⎕]

Try it online! Courtesy of Dyalog Classic

PynTree, 13 bytes
§yz:ṡzCæf+yxx

Try it online!
Port of Jo King's Python answer.
Explanation
§yz:ṡzCæf+yxx  Anonymous lambda
§              lambda  ,
 y                    y
  z                     z
   :                     :
    ṡ                     sorted( ,lambda x:
     z                           z
      C                                     (          )( )
       æf                                    (   ).find
         +                                     +
          y                                   y
           x                                    x
            x                                            x


text:
Beginners 10x10 multiplication matrix
I was looking for a very easy task to look how short of a code can be produced on a beginners exercise.
The goal is to produce a simple table that looks like this common java/c# code is about 4 lines. So get your golfing-languages ready ;) Try to align the matrix in any way it is readable.

1 2 3    .. 10

2 4 6    .. 20

3 6 9    .. 30

. . .    .. .

10 20 30 .. 100

EDIT: The first answer below shows a propper alignment and solution

Can you provide an example of the desired output ? Or are you asking us to print the 10*10 matrix ?

yes, just the 10x10 matrix

Looks like a simplified version of Print this Multiplication Table and Addition/Multiplication table generator. Not much challenging. Though occasionally the extremely simple questions' popularity is much higher. Unless closed. So I suggest to specify whether input will be provided, output must be text or formatted array is fine and whether the numbers need some kind of alignment.

Nice first challenge, but you would be wise to specify more clearly what exactly is required. E.g. may we return a list of ten lists? Don't use the word "Try"; either require it or say it isn't required. Etc.

If you do require alignment, which alignments are acceptable (left, right, all columns same width, single/multiple space separating columns, additional white space left and/or right, etc.)?

Please give one or more complete correct outputs. One might think that the output actually needs all the dots.

There's some grammatical problem in the sentence The goal is to produce a simple table that looks like this common java/c# code is about 4 lines.

Although not exactly duplicate, I think that this challenge is too similar to be interesting. It will only be closed if there are 5 people (or a gold badge holder) agree with that and nobody vote to reopen.

I don't think anybody has mentioned this yet, but welcome to PPCG!

My answer before it was closed

@sergiol Annoying when a question gets closed just when you wanted to post an answer, isn't it? ;) My answer in Java 10 and my answer in 05AB1E. Both probably golfable (second one especially, I'm pretty new to 05AB1E).

Strange, it looks like the system somehow allowed me to post an answer when it was already closed! Nevertheless, I think it is not very nice to close a challenge, which is not technically an exact duplicate, when it has already accumulated a dozen of answers!

@KevinCruijssen: The maximum you can do about it is voting to reopen!

@KirillL. Can I suggest you voting to reopen?

@sergiol I already did...

I would vote to reopen but I have a gold badge, and I think this should be closed as unclear rather than a dupe.

@Giuseppe: For me the output sample made very clear what the question's poster want people to answer.

MATL, 5 bytes
10:&*

Try it online!
10:    % Range: [1,2,3,4,5,6,7,8,9,10]
   &*  % Multiply the range by itself transposed, with broadcasting.

Outputs:
 1   2   3   4   5   6   7   8   9  10
 2   4   6   8  10  12  14  16  18  20
 3   6   9  12  15  18  21  24  27  30
 4   8  12  16  20  24  28  32  36  40
 5  10  15  20  25  30  35  40  45  50
 6  12  18  24  30  36  42  48  54  60
 7  14  21  28  35  42  49  56  63  70
 8  16  24  32  40  48  56  64  72  80
 9  18  27  36  45  54  63  72  81  90
10  20  30  40  50  60  70  80  90 100

Ruby, 48 45 44 bytes
1.upto(10){|x|puts"%4d"*10%[*x.step(100,x)]}

Try it online!
-3 bytes thanks to manatwork then -1 thanks to Kirill L.
But I still think there must be a better way.

You not need the parenthesis around the "%4d"*10. And instead of x*10 you can write just 100 then the placeholders in the format string will limit it to 10.

Now, when there are no parentheses, you don't need the space after puts either. As for a better way, it looks not so easy, e.g. an alternative approach gives still the same 44 bytes

Jelly, 5 bytes
⁵×þ`G

Try it online!
Prints the following text:
  1   2   3   4   5   6   7   8   9  10
  2   4   6   8  10  12  14  16  18  20
  3   6   9  12  15  18  21  24  27  30
  4   8  12  16  20  24  28  32  36  40
  5  10  15  20  25  30  35  40  45  50
  6  12  18  24  30  36  42  48  54  60
  7  14  21  28  35  42  49  56  63  70
  8  16  24  32  40  48  56  64  72  80
  9  18  27  36  45  54  63  72  81  90
 10  20  30  40  50  60  70  80  90 100

Another 5-byter.

I'm so fascinated by those languages like Jelly, Brainfuck etc.... But I think I will never understand how to write code with these. Is there any 'tutorial' you can recommend?

For Jelly, I can recommend its dedicated wiki. However, I suggest not accepting an answer this early, and in fact not accepting an answer at all because that doesn't encourage competition.

Octave, 18 17 bytes
1 byte saved thanks to @StewieGriffin
disp((x=1:10)'*x)

Try it online!
Or, as @maxb points out: more readable, same length:
x=1:10;disp(x'*x)

You could simply do x=1:10;disp(x'*x). Same amount of bytes, and more readable.

@maxb Good idea; updated

... and more readable. That's almost a reason to not update the answer!

R, 32 bytes
write(format((x=1:10)%o%x),1,10)

Try it online!

write(format(1:10%o%1:10),1,10) is shorter by one byte.

Python 2, 64 55 bytes
i=1
exec"print'%4d'*10%tuple(range(i,11*i,i));i+=1;"*10

Try it online!

Brainfuck, 1147 bytes
++[[<+++>-->----<]>]<<<<+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<--------.-.<<+.>>++.>..<++.>..<++.>..<++.>..<-------.-.>.<+.+.>.<-.+++.>.<---.+++++.>.<-----.+++++++.>.<------.--.<<.>>+++.>..<+++.>..<+++.>..<--------.+.>.<-.++++.>.<----.+++++++.>.<------.-.>.<+.++.>.<--.+++++.>.<----.---.<<.>>++++.>..<++++.>..<-------.+.>.<-.+++++.>.<----.--.>.<++.++.>.<--.++++++.>.<-----.-.>.<+.+++.>.<--.----.<<.>>+++++.>..<----.-.>.<+.++++.>.<---.--.>.<++.+++.>.<--.---.>.<+++.++.>.<-.----.>.<++++.+.>.<.-----.<<.>>++++++.>..<-----.+.>.<-.+++++++.>.<------.++.>.<-.---.>.<+++.+++.>.<--.--.>.<++.++++.>.<---.-.>.<++.------.<<.>>+++++++.>..<------.+++.>.<--.-.>.<+.++++++.>.<-----.++.>.<-.--.>.<++.+++++.>.<----.+.>.<.---.>.<++++.-------.<<.>>++++++++.>..<-------.+++++.>.<----.++.>.<-.-.>.<++.----.>.<++++.++++.>.<---.+.>.<.--.>.<+++.-----.>.<++++++.--------.<<.>>+++++++++.>..<--------.+++++++.>.<------.+++++.>.<----.+++.>.<--.+.>.<.-.>.<++.---.>.<++++.-----.>.<++++++.-------.>.<++++++++.---------.<<.>>+.-.>.<++.--.>.<+++.---.>.<++++.----.>.<+++++.-----.>.<++++++.------.>.<+++++++.-------.>.<++++++++.--------.>.<+++++++++.---------.>.<+.-..

Try it online!
Thanks for Jo King for this solution !
Old answer, 1164 bytes
+++++[>+++++[>++>+<<-]>>+>++<<<<-]>>-->++<+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<--------.-.>>.<<++.>..<++.>..<++.>..<++.>..<-------.-.>.<+.+.>.<-.+++.<.>---.+++++.<.>-----.+++++++.<.>------.--.>>.<<+++.>..<+++.>..<+++.>..<--------.+.>.<-.++++.>.<----.+++++++.>.<------.-.>.<+.++.>.<--.+++++.>.<----.---.>>.<<++++.>..<++++.>..<-------.+.>.<-.+++++.>.<----.--.>.<++.++.>.<--.++++++.>.<-----.-.>.<+.+++.>.<--.----.>>.<<+++++.>..<----.-.>.<+.++++.>.<---.--.>.<++.+++.>.<--.---.>.<+++.++.>.<-.----.>.<++++.+.>.<.-----.>>.<<++++++.>..<-----.+.>.<-.+++++++.>.<------.++.>.<-.---.>.<+++.+++.>.<--.--.>.<++.++++.>.<---.-.>.<++.------.>>.<<+++++++.>..<------.+++.>.<--.-.>.<+.++++++.>.<-----.++.>.<-.--.>.<++.+++++.>.<----.+.>.<.---.>.<++++.-------.>>.<<++++++++.>..<-------.+++++.>.<----.++.>.<-.-.>.<++.----.>.<++++.++++.>.<---.+.>.<.--.>.<+++.-----.>.<++++++.--------.>>.<<+++++++++.>..<--------.+++++++.>.<------.+++++.>.<----.+++.>.<--.+.>.<.-.>.<++.---.>.<++++.-----.>.<++++++.-------.>.<++++++++.---------.>>.<<+.-.>.<++.--.>.<+++.---.>.<++++.----.>.<+++++.-----.>.<++++++.------.>.<+++++++.-------.>.<++++++++.--------.>.<+++++++++.---------.>.<+.-..

Try it online!
Oh god, this ended up way longer than I expected.
Here is how i did it :
Store values 48 ('0'), 32 (space) and 10 (new line)
+++++[>+++++[>++>+<<-]>>+>++<<<<-]>>-->++<
Print 1st line
+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<+.>..<--------.-.>>.<<
Print 2nd line
++.>..<++.>..<++.>..<++.>..<-------.-.>.<+.+.>.<-.+++.<.>---.+++++.<.>-----.+++++++.<.>------.--.>>.<<
Etc.
+++.>..<+++.>..<+++.>..<--------.+.>.<-.++++.>.<----.+++++++.>.<------.-.>.<+.++.>.<--.+++++.>.<----.---.>>.<< Etc.
++++.>..<++++.>..<-------.+.>.<-.+++++.>.<----.--.>.<++.++.>.<--.++++++.>.<-----.-.>.<+.+++.>.<--.----.>>.<<
+++++.>..<----.-.>.<+.++++.>.<---.--.>.<++.+++.>.<--.---.>.<+++.++.>.<-.----.>.<++++.+.>.<.-----.>>.<<
++++++.>..<-----.+.>.<-.+++++++.>.<------.++.>.<-.---.>.<+++.+++.>.<--.--.>.<++.++++.>.<---.-.>.<++.------.>>.<<
+++++++.>..<------.+++.>.<--.-.>.<+.++++++.>.<-----.++.>.<-.--.>.<++.+++++.>.<----.+.>.<.---.>.<++++.-------.>>.<<
++++++++.>..<-------.+++++.>.<----.++.>.<-.-.>.<++.----.>.<++++.++++.>.<---.+.>.<.--.>.<+++.-----.>.<++++++.--------.>>.<<
+++++++++.>..<--------.+++++++.>.<------.+++++.>.<----.+++.>.<--.+.>.<.-.>.<++.---.>.<++++.-----.>.<++++++.-------.>.<++++++++.---------.>>.<<
+.-.>.<++.--.>.<+++.---.>.<++++.----.>.<+++++.-----.>.<++++++.------.>.<+++++++.-------.>.<++++++++.--------.>.<+++++++++.---------.>.<+.-..

1147 bytes. You were printing null bytes on the second line

There's got to be an algorithmic way of printing the numbers instead of kolmogorov'ing it

APL+WIN, 9 bytes
n∘.×n←⍳10

Try it online! Courtesy of Dyalog Classic
Outer product multiplication of a vector of integers 1 to 10

on Dyalog you can get 7 bytes

@dzaima Unfortunately I am running an ancient version of APL+WIN which does not have the ⍨ operator ;(

Batch, 177 bytes
@echo off
for /l %%i in (1,1,10)do call:r %%i
exit/b
:r
set s=
for /l %%j in (1,1,10)do set/an=%1*%%j&call:c
echo %s%
:c
set n= %n%
if "%n:~3%"=="" goto c
set s=%s%%n%

J, 9 bytes
*/~1+i.10

Try it online!

Red, 56 bytes
repeat n 10[repeat m 10[prin pad rejoin[n * m]4]print""]

Try it online!

CJam, 24 23 bytes
A,:)_m*{:*"%4d"e%}%A/:n

Try it online!
Alternative without pretty printing:
A,:)_m*{:*}%A/:p

JavaScript (Node.js), 79 bytes
(_=[...".........."])=>_.map((a,i)=>Array.from({length:10},(v,k)=>(k+1)*(i+1)))

Try it online!