text:
Counting from 1 to n without any consecutive numbers
Goal
You are given an integer n (n > 1). You must output how many permutations of the integers 1 to n there are which start at 1, end at n, and don't have two consecutive integers which differ by 1.
Alternatively, if you take the complete graph K_n and remove the edges of the path 1-2-3-...-n you must count the Hamiltonian paths from 1 to n in the remaining graph.
The examples will use f(n) for a function that takes in n and outputs the number of valid permutations, but your submission can be a function or a program.

Examples
For n = 6, a possible solution is 1-3-5-2-4-6
However, 1-3-5-2-6-4 is not a valid solution since it does not end with 6.
In fact, for n = 6, there are only 2 solutions (1-4-2-5-3-6 is the other one).
Hence f(6) = 2.

For n = 4 the only permutations which start in 1 and end in 4 are 1-2-3-4 and 1-3-2-4. In both of them the 2 is adjacent to the 3, giving consecutive integers which differ by 1. Therefore f(4) = 0.

Test cases
f(6) = 2
f(4) = 0
f(8) = 68
f(13) = 4462848

Winning criterion
This is code-golf, the shortest answer wins.

You see, kids, you can't just check how many permutations of [2..n-1] contain no deltas of 1 or -1, you have to also check that none of them start with 2 or end with n-1...

Does the list have to start with 1 and end with the number?

To fix ETH's comment, what you should be checking (to work for 1) is check the amount of permutations that 1. Start with 1, 2. End with n, 3. Do not contain consecutive numbers.

@Okx Then brute-force solutions would either be a few bytes longer to handle the special case of 1, or even slower than they are already... :P

I understand your point, thought I'd rather not add any rule that will eliminate existing answers. Plus I think the 1 rule is arbitrary and has no meaning in the problem.

It seems there is no entry for this sequence in OEIS. Perhaps it deserves to be, what do you think?

Haha yeah I looked for it. I don't know, I'm curious to see if it has other applications. I might turn that problem to a fastest-code later ahah!

I presume that "without any consecutive numbers" means "without any two-element sublists in which the second is one greater than the first" (because any list of two or more elements which only contains integers must contain consecutive elements which are numbers, so although that's the simpler interpretation in general the context rules it out). However, [0 2 1 3] would therefore be a valid permutation, which conflicts with the test cases. Cf A000757.

Maybe the OP means "adjacent" not "consecutive"?

Bizarly the sequence is here: http://algo.inria.fr/libraries/autocomb/graphs99.ps where on page 6 is written Q_ser:=z + 2 z^6 + 10 z^7 + 68 z^8 + 500 z^9 + 4174 z^10 + 38774 z^11 + 397584z^12 + 4462848 z^13 + 54455754 z^14 I spend some time now trying to use the formulas, but I can't compose one that generates the sequence. Amazing to see the the exponent of z is the input of the formula and the outcome is the multiplication factor. The one how can deduce the formula from there may be one with the shortest answer in bytes

@ChristiaanWesterbeek Amazing find! I could use a result from page 7, but I'm far from beating the size of the golfing language solutions.

@ChristiaanWesterbeek that's called the generating function for the sequence. There exist many sequences with a generating function that has a nicer closed form than the sequence itself, it's cool stuff!

I know generating function as I did some advanced maths, but never got to that level. It's a real blast ahah!

MATL, 16 bytes
qtq:Y@0&Yc!d|qAs

Try it online!
For inputs exceeding 12 it runs out of memory.
Explanation
q      % Implicitly input n. Push n-1
tq     % Duplicate and subtract 1: pushes n-2
:      % Range [1 2 ... n-2]
Y@     % Matrix with all permutations, each in a row
0      % Push 0
&Yc    % Append n-1 and predend 0 to each row
!      % Tranpose
d      % Consecutive differences along each column
|      % Absolute value
q      % Subtract 1
A      % All: true if all values in each column are non-zero
s      % Sum. Implicitly display

Working fine, well done :)

Although there were some really nice advancement into this problem, your solution is still the shortest. It is also faster than the Jelly one. Congratz!

Mathematica, 58 bytes, polynomial(n) time
Abs[Sum[(k-1)Hypergeometric2F1[k,k-#,2,2](#-k)!,{k,#}]-1]&

How it works
Rather than iterating over permutations with brute force, we use the inclusion–exclusion principle to count them combinatorially.
Let S be the set of all permutations of [1, …, n] with σ1 = 1, σn = n, and let Si be the set of permutations σ ∈ S such that |σi − σi + 1| = 1.  Then the count we are looking for is
|S| − |S1 ∪ ⋯ ∪ Sn − 1| = ∑2 ≤ k ≤ n + 1; 1 ≤ i2 < ⋯ < ik − 1 < n (−1)k − 2|Si2 ∩ ⋯ ∩ Sik − 1|.
Now, |Si2 ∩ ⋯ ∩ Sik − 1| only depends on k and on the number j of runs of consecutive indices in [i1, i2, …, ik − 1, ik] where for convenience we fix i1 = 0 and ik = n. Specifically,
|Si2 ∩ ⋯ ∩ Sik − 1| = 2j − 2(n − k)!, for 2 ≤ j ≤ k ≤ n,
|Si2 ∩ ⋯ ∩ Sik − 1| = 1, for j = 1, k = n + 1.
The number of such index sets [i1, i2, …, ik − 1, ik] with j runs is
(k − 1Cj − 1)(n − kCj − 2), for 2 ≤ j ≤ k ≤ n,
1, for j = 1, k = n + 1.
The result is then
(−1)n − 1 + ∑2 ≤ k ≤ n ∑2 ≤ j ≤ k  (−1)k − 2(k − 1Cj − 1)(n − kCj − 2)2j − 2(n − k)!
The inner sum over j can be written using the hypergeometric 2F1 function:
(−1)n − 1 + ∑2 ≤ k ≤ n (−1)k(k − 1)2F1(2 − k, k − n; 2; 2)(n − k)!
to which we apply a Pfaff transformation that lets us golf away the powers of −1 using an absolute value:
(−1)n − 1 + ∑2 ≤ k ≤ n (−1)n(k − 1)2F1(k, k − n; 2; 2)(n − k)!
= |−1 + ∑1 ≤ k ≤ n (k − 1)2F1(k, k − n; 2; 2)(n − k)!|.
Demo
In[1]:= Table[Abs[Sum[(k-1)Hypergeometric2F1[k,k-#,2,2](#-k)!,{k,#}]-1]&[n],{n,50}]

Out[1]= {1, 0, 0, 0, 0, 2, 10, 68, 500, 4174, 38774, 397584, 4462848,

>    54455754, 717909202, 10171232060, 154142811052, 2488421201446,

>    42636471916622, 772807552752712, 14774586965277816, 297138592463202402,

>    6271277634164008170, 138596853553771517492, 3200958202120445923684,

>    77114612783976599209598, 1934583996316791634828454,

>    50460687385591722097602304, 1366482059862153751146376304,

>    38366771565392871446940748410, 1115482364570332601576605376898,

>    33544252621178275692411892779180, 1042188051349139920383738392594332,

>    33419576037745472521641814354312790,

>    1105004411146009553865786545464526206,

>    37639281863619947475378460886135133496,

>    1319658179153254337635342434408766065896,

>    47585390139805782930448514259179162696722,

>    1763380871412273296449902785237054760438426,

>    67106516021125545469475040472412706780911268,

>    2620784212531087457316728120883870079549134420,

>    104969402113244439880057492782663678669089779118,

>    4309132147486627708154774750891684285077633835734,

>    181199144276064794296827392186304334716629346180848,

>    7800407552443042507640613928796820288452902805286368,

>    343589595090843265591418718266306051705639884996218154,

>    15477521503994968035062094274002250590013877419466108978,

>    712669883315580566495978374316773450341097231239406211100,

>    33527174671849317156037438120623503416356879769273672584588,

>    1610762789255012501855846297689494046193178343355755998487686}

My mind is blown, good job

Jelly, 17 16 bytes
ṖḊŒ!ð1;;⁹IỊṀðÐḟL

A monadic link.
Try it online!
How?
ṖḊŒ!ð1;;⁹IỊṀðÐḟL - Link: number n
Ṗ                - pop (implicit range build) -> [1,n-1]
 Ḋ               - dequeue -> [2,n-1]
  Œ!             - all permutations of [2,n-1]
    ð       ðÐḟ  - filter discard those entries for which this is truthy:
     1;          -   1 concatenated with the entry
       ;⁹        -   ...concatenated with right (n)
         I       -   incremental differences
          Ị      -   is insignificant (absolute value <=1)
           Ṁ     -   maximum
               L - length (the number of valid arrangements)

Sorry but it does not meet the test cases

Yeah, you made the same mistake Okx and I made at first. You have to account for the fact that the second number cannot be 2 and the second-to-last number cannot be n-1

@Philippe fixed it up.

I don't think using IỊṀ is valid. Specifically, what if -2 is one of the deltas in there for example? You can fix with IAỊṀ for +1.

@EriktheOutgolfer What is the issue with a -2? Ị needs no A because it is an atom which yields the result of if abs(x)<=1.

@JonathanAllan Ooh I thought it returned x <= 1.

05AB1E, 17 bytes
L¦¨œʒ¹1Š)˜¥Ä1å_}g

Try it online!

It's not providing the right results, sorry

@Philippe On which testcase?

@Philippe Fixed.

¹1Š)˜ saves a byte.

Japt, 19 18 bytes
o2 á è_pU äÉ m²e>1

Test it online! I would not recommend testing on anything larger than 10.
Explanation
o2 á è_  pU äÉ  m²  e>1
o2 á èZ{ZpU ä-1 mp2 e>1}
                          : Implicit: U = input integer
o2                        : Create the range [2..U-1].
   á                      : Generate all permutations of this range.
     èZ{               }  : Check how many permutations Z return a truthy value:
        ZpU               :   Push U to the end of Z.
            ä-1           :   Push 1 to the beginning of Z, then take the difference
                          :   of each pair of items.
                m         :   Map each item X to
                 p2       :     X ** 2. This gives a number greater than 1 unless the
                          :     item is 1 or -1.
                    e>1   :   Return whether every item in this list is greater than 1.
                          :   This returns `true` iff the permutation contains no
                          :   consecutive pairs of numbers.
                          : Implicit: output result of last expression

Good job! Funny how my brute-force code can't get over n = 13 neither ahah

@Philippe I wouldn't recommend accepting so fast, I'm sure this will be shorter in 05AB1E or Jelly ;-)

Fails on testcase 1.

@Okx OP has specified that we can assume n > 1.

Haskell, 76 65 bytes
Saved 11 bytes thanks to @xnor.
Using the result for Q_rec on page 7 of @ChristiaanWesterbeek's find, we get
f 1=1
f n|n<6=0
f n=sum$zipWith((*).f)[n-5..][n-4,1,10-2*n,4,n-2]

I don't understand how their next result ha relates to this, but after speeding up (first by memoization, see earlier versions, then as below) I get their numbers.
While the above is okay for n=20, it is essentialy an example how not to do recursion. Here is a faster version (only for n>=6) that also would only need constant memory - if only the numbers didn't keep increasing...
f n=last$foldl(#)[1,0,0,0,0][6..n]
l#n=tail l++[sum$zipWith(*)l[n-4,1,10-2*n,4,n-2]]

That gives
Prelude> f 50
1610762789255012501855846297689494046193178343355755998487686
Prelude> f 500
659178618863924802757920269977240274180092211041657762693634630044383805576666007245903670780603497370173231423527767109899936008034229541700392144282505597945561328426013937966521561345817045884498867592832897938083071843810602104434376305964577943025310184523643816782047883794585616331928324460394146825636085453532404319881264974005968087265587062691285454120911586459406436421191277596121471930913837355151842093002557978076653884610826296845041929616496533544124347765641367732716560025553179112645454078955409181466212732427071306363820080109636358537270466838558068527692374178581063316309789026101221004745226182671038004326069705775312654329754698423385241664984156235692539255677944294995403233446243315371404887473868003155621849544566385172835597260848972758443874423271017007843907015007416644383573987606586308556317833384896267539628278571497402655322562624217658332870157802254043614726316296058329670971054977099155788604175817828380564156329839201579006169173002756295957371639199917376529472990059986681882194726437566769717959443857298155265292535858523609764515938314672724480762724541633037484152303637096

It's no problem to also get f 5000 but I don't want to paste the result...

BTW, it's possible to not use fancy math and still not use (ultra) brute force. First, instead of looking at all permutations, look at partial permutations and only extend them when they are not already invalid. It's no use to look at all permutations starting with 1 6 5. Second, some partial permutations like 1 3 5 7 and 1 5 3 7 have exactly the same valid continuations, so handle them together. Using these ideas, I could compute the values up to n=16  in 0.3s.

You can write the recursive expression shorter like a dot by extracting out the coefficients: f n=sum$zipWith((*).f)[n-5..][n-4,1,10-2*n,4,n-2].

@xnor Right, thanks!

This is some good work, I'm astonished by the results this community came up with! Too bad it's a golf ^^

Python, 125 bytes
from itertools import*
lambda n:sum(p[-1]-p[0]==n-1and all(~-abs(x-y)for x,y in zip(p,p[1:]))for p in permutations(range(n)))

Looks pretty fast, good job!

117 bytes

Mathematica, 66 bytes
Count[Permutations@Range@#,x:{1,__,#}/;FreeQ[Differences@x,1|-1]]&

Explanation
Function with first argument #.
Count[                                                             (* Count the number of *)
      Permutations@                                                (* permutations of *)
                   Range@#,                                        (* the list {1, ..., #} *)
                           x:{1,__,#}                              (* of the form {1, __, #} *)
                                     /;                            (* such that *)
                                             Differences@x,        (* the list of differences of consecutive elements *)
                                       FreeQ[                      (* is free of elements of the form *)
                                                           1|-1    (* 1 or -1 *)
                                                               ]]&

Javascript (ES6), 100 74 72 60 bytes
f=n=>n--<6?!n|0:f(n)*--n+4*f(n--)-2*f(n--)*--n+f(n)*++n+f(n)

Below is the version before the golf-mastery of @PeterTaylor
f=n=>n<6?n==1|0:(n-4)*f(n-5)+f(n-4)-2*(n-5)*f(n-3)+4*f(n-2)+(n-2)*f(n-1)

Thanks to the answer from @ChristianSievers that managed to draft a Haskell solution from a paper that I found after googling '0, 2, 10, 68, 500, 4174, 38774, 397584', here's a Javascript version that does not permutate too.
Usage
for (i=1; i<=20; i++) {
  console.log(i, f(i))
}

1 1
2 0
3 0
4 0
5 0
6 2
7 10
8 68
9 500
10 4174
11 38774
12 397584
13 4462848
14 54455754
15 717909202
16 10171232060
17 154142811052
18 2488421201446
19 42636471916622
20 772807552752712

The task description only asks for f(n) when n>1, so it doesn't matter what you return for n=1. Also I think f(1)=1 is correct.

You can combine the special cases as n<6?n==1|0: for a further two-char saving.

Great. I adjusted for those 2 comments.

And by reordering terms and relying on order of evaluation it's possible to get down to 60: f=n=>n--<6?!n|0:f(n)*--n+4*f(n--)-2*f(n--)*--n+f(n)*++n+f(n)

Python 3, 109 107 102 bytes
q=lambda s,x,n:sum(q(s-{v},v,n)for v in s if(v-x)**2>1)if s else x<n;f=lambda n:q({*range(2,n)},1,n-1)

Try it online!
Removed four bytes by not trying to one-line the function (as suggested by @shooqie) and another byte by replacing abs with a square.
(Requires Python 3.5+)

103 bytes

Brachylog, 26 bytes
{⟦₁pLh1&~tLs₂ᶠ{-ȧ>1}ᵐ}ᶜ|∧0

Try it online!
Explanation
{                    }ᶜ       Output = count the number of outputs of:
 ⟦₁pL                           L is a permutation of [1, …, Input]
    Lh1                         The head of L is 1
       &~tL                     The tail of L is the Input
          Ls₂ᶠ                  Find all sublists of length 2 of L
              {    }ᵐ           Map on each sublist:
               -ȧ>1               The elements are separated by strictly more than 1
                       |      Else (no outputs to the count)
                        ∧0    Output = 0

Python 2, 136 bytes
-10 bytes thanks to @ovs.
lambda n,r=range:sum(x[0]<1and~-n==x[-1]and 2+~any(abs(x[i]-x[i+1])<2for i in r(n-1))for x in permutations(r(n)))
from itertools import*

Try it online!

136 bytes

Mathematica, 134 bytes
(s=Permutations@Range[2,#-1];g=Table[Join[Prepend[s[[i]],1],{#}],{i,Length@s}];Length@Select[Union@*Abs@*Differences/@g,FreeQ[#,1]&])&

test cases n: 2 to 12

{0, 0, 0, 0, 2, 10, 68, 500, 4174, 38774, 397584}

Python 2, 105 bytes
lambda n:reduce(lambda a,i:a+[i*a[-5]+a[-4]+2*(1-i)*a[-3]+4*a[-2]+(i+2)*a[-1]],range(2,n),[0,1]+4*[0])[n]

Try it online!
This is based on Philippe Flajolet's paper discovered by @Christiaan Westerbeek; it's much faster and two bytes shorter than my Python 3 solution which enumerates the possible permutations. (In Python 3, reduce has annoyingly been moved to functools.)
There is a much shorter version using numpy's dot product, but that overflows quite rapidly and requires numpy to have been imported. But for what it's worth:
lambda n:reduce(lambda a,i:a+[dot([i,1,2-2*i,4,i+2],a[-5:])],range(2,n),[0,1]+4*[0])[n]


text:
Regex, Paper, Scissors, Lizard, Spock
Warm up: Regex, Paper, Scissors
This is the challenge I originally wanted to post, before realising that some very short solution exist. Nevertheless, it can be an interesting problem to think about in preparation for the actual challenge below.
Write three regexes R, P and S such that they match each other in a cyclic Rock, Paper, Scissors fashion. In particular, R matches S, S matches P and P matches R, but R doesn't match P, S doesn't match R and P doesn't match S. Here's a handy table:
Regex   Matches   Doesn't match
R       S         P
P       R         S
S       P         R

It doesn't matter what R, P and S do on any other inputs, including themselves.
Here, match just means that some (possibly empty) substring of the input is matched. The match does not need to cover the entire input.
The challenge: Regex, Paper, Scissors, Lizard, Spock
For this challenge, you'll solve a tougher version of the above problem, based on the RPS variant Rock, Paper, Scissors, Lizard, Spock (as popularised by The Big Bang Theory). In RPSLV, there are five different symbols, that beat each other in two cycles:

Rock → Scissors → Lizard → Paper → Spock → Rock
Rock → Lizard → Spock → Scissors → Paper → Rock

You should write five regexes R, P, S, L and V which mimic this structure when given to each other as input. Here is the corresponding table:
Regex   Matches   Doesn't match
R       L, S      V, P
L       V, P      S, R
V       S, R      P, L
S       P, L      R, V
P       R, V      L, S

Just to be clear, you should not match the string R, P, etc, but the other regexes. E.g. if your regex R is ^\w$ for example, then P and V have to match the string ^\w$, whereas S and L shouldn't.
Again, match just means that at least one (possibly empty) substring of the input is matched. The match does not need to cover the entire input. For example \b (word boundary) matches hello (at the beginning and at the end), but it doesn't match (^,^).
You may use any regex flavour, but please state the choice in your answer and, if possible, provide a link to an online tester for the chosen flavour. You may not use any regex features that let you invoke code in the flavour's host language (like the Perl flavour's e modifier).
Delimiters (like /regex/) are not included in the regex when given as input to another, and you cannot use modifiers that are outside of the regex. Some flavours still let you use modifiers with inline syntax like (?s).
Your score is the sum of the lengths of the five regexes in bytes. Lower is better.
It turns out to be a lot simpler to find a working solution to this problem than it may seem at first, but I hope that finding an optimal solution is quite tricky.

Does, say, R have to match the entire regex of S or a substring of S, provided it does not match any substrings of P or V?

@Okx "match just means that at least one (possibly empty) substring of the input is matched. The match does not need to cover the entire input. For example \b (word boundary) matches hello (at the beginning and at the end), but it doesn't match (^,^)."

Presumably it doesn't matter if a regex matches itself?

@Brilliand Correct.

For making this more general, could one just write a set of programs which accept (or reject) each other?

@MartinEnder I didn't want to generalize the graph, but to generalize from regular expressions to any kind of programs which implement a string → boolean function, in order to allow more "programming languages".

Great puzzle. I've created an interactive version here, if anyone is interested: https://shark.fish/rock-paper-scissors/

@shark.dp Wow that's really cool, nice work!

PCRE, 15 14 bytes
Rock:
B
Paper:
\b$
Scissors:
b|B.
Lizard:
\B.
Spock:
^\w

Very impressive.

Unbeatable! I've been fiddling with Rock = Q (one 14b solution exists with Lizard = \Q\\, then the rest similar to yours) but to absolutely no avail.

PCRE .NET, 35 32 bytes
-3 bytes thanks to Martin Ender
Rock:
([*?]$)

Paper:
[)$]$+

Scissors:
[+?]$.*

Lizard:
[+$]$.?

Spock:
[*)]$

The idea here is to match characters at the end of other regexes which are reserved regex characters, but stop being treated as such when inside a character class.

Okay, you win :P

Sneaky use of putting things after the EOL "$" that become ignored when actively used and matchable when passively used

no fancy features, 35 30 bytes
5 bytes saved by Neil's idea which uses that ] needs no \.
This works for example with the python re module.
R='[SLR]]'
P='[RVP]]'
S='[PLS]]'
L='[PVL]]'
V='[SRV]]'

It searches for a ] preceded by a letter that indicates which rule it is.
Previous version used R='\[[RSL]' etc.
An earlier attempt with score 40 was using R='[SL]x|Rx' etc.

Save 5 bytes by reversing everything: R='[LSR]]' etc.

@Neil That's a great improvement, thanks!

This works with python's re well, Python should probably be the header then

@cat I also wrote "for example", the whole sentence is just to say something concrete that I actually tried. I guess I could say POSIX like some others did, but I think my header is quite correct.

PCRE, 20 19
Rock
W

Paper
^\w

Scissors
^\W

Spock
w?\x57$

Lizard
[w]W?

20 bytes
R = 'R|VP'
L = 'L|RS'
V = 'V|LP'
S = 'S|RV'
P = 'P|LS'

Oh wow, it can be so easy!

That's beautiful.

JavaScript, 45 bytes
Another trivial solution.
R:
^R|^.[SL]
P:
^P|^.[RV]
S:
^S|^.[PL]
L:
^L|^.[PV]
V:
^V|^.[SR]

Oh just realised my answer is a longer/similar version of yours, want me to delete it?

@TheLethalCoder All the answers currently are just longer/shorter versions of each other :p

I suppose haha...

POSIX, 50 45 bytes
Rock
.{5}RP?V?
Paper
.{5}PS?L?
Scissors
.{5}SR?V?
Lizard
.{5}LR?S?
Vulcan (Spock)
.{5}VP?L?

Could be done shorter but the (hide matches after $) trick got used, so I'm looking for another way
The first 5 chars of each string are ignored when matching. So the effective target string simplifies to just X?Y?. None of them have any double letters because "?" is an ordinary char, so the last 4 chars when used as a regex have to match (null string). So the patterns collapse down to "contains 5 chars followed by the target letter":  meaning  chars 6-9 of the target must contain the target letter (the 5th char in each string)
Update: 35 byte version below, now!

I always thought the V isn't actually for Vulcan but to represent the shape of the Vulcan salute (which is the hand gesture you use to represent Spock when playing RPSLV in person).

Anyway, welcome to PPCG! Nice first answer. I like that you've inverted the logic compared to all existing answers (matching only one letter and putting the letters beating the current regex into the regex).

Does POSIX automatically anchor the match to the beginning of the string? Otherwise, couldn't you drop those commas?

I think its POSIX. Could be perc. But yes, nicely spotted! 5 chars less!

And thanks for the welcome. Not that there's many golfs I know enough to tangle with or compete with jelly, but this one was nice!

There's no need to compete with Jelly. Just pick a language you like and enjoy yourself. :)

PCRE, 65 bytes
This is a really trivial solution - and not very clever at all - but I'll try to golf it.
V:
(?#V).+[SR]\)

L:
(?#L).+[PV]\)

S:
(?#S).+[PL]\)

P:
(?#P).+[RV]\)

R:
(?#R).+[SL]\)

Essentially, each regex has an 'identifier', in the form of a comment, which tells the other regexes whether it should be matched or not.

Vanilla RE, 40 characters
Not the most concise or elegant solution but has a pleasing quasi-semantic visual structure!
[^r][sl]
[^p][vr]
[^s][lp]
[^l][pv]
[^v][rs]

Rock beats Scissors or Lizard
Paper beats Vulcan or Rock
Scissors beats Lizard or Paper
Lizard beats Paper or Vulcan
Vulcan beats Rock or Scissors

I'm glad that someone posted the actual rules for Vulcan & Lizard.... I know Paper smothers a Rock, but how does a Paper defeat a Vulcan?  I suppose Wikipedia would yield the answer.  Yup: https://en.wikipedia.org/wiki/Rock_paper_scissors#Additional_weapons

.NET, 50 bytes
In order they are R, P, S, L, V.
[^R]\^[SL]
[^P]\^[RV]
[^S]\^[PL]
[^L]\^[PV]
[^V]\^[SR]

Works by looking for the identifier group (for example, [^R]) in each of the other expressions.
Changing the expressions to ^R|\^[SL], or similar, seems to work but then it's a bit too similar to @dzaima's answer although it would get it to 45 bytes.

POSIX, 35 bytes
Rock
R?^[LS]
Paper
P?^[RV]
Scissors
S?^[LP]
Lizard
L?^[PV]
Vulcan (Spock)
V?^[RS]

A completely different way to "hide" behind a start/end symbol, so I feel OK about it :)  I'm matching to start because "?" would always have to go between letter and end/$ if done the other way.
10 bytes less than my 1st solution, and conceptually simple which is a bonus I like.

source: Stack Exchange

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

sort: votes


text:
Reverse a Rubik's Cube Algorithm
Whenever you make a move on a Rubik's Cube, there is a reverse move which undoes the first move. Because of this, every algorithm (set of moves) has a reverse algorithm which undoes the first algorithm.
The goal of this challenge is to find the reverse of a given algorithm.
Specification:
The input consists of an array of individual moves. Each move is a string of length 1 or 2. Of course, you can use whatever input format makes the most sense in your language. Each move consists of the structure X or X' or X2, where X is an uppercase or lowercase letter.
To reverse X, simply replace it with X'. Likewise, X' becomes X. X2 on the other hand does not get changed.
To create the output, reverse each move, and then reverse the array.
Examples (strings separated by spaces):
R => R'
D U' => U D'
S T A C K => K' C' A' T' S'
A2 B2 => B2 A2
Scoring:
This is code-golf, so the fewest amount of bytes win. Standard loopholes are not allowed.

Is R2 -> R2' or B -> B3 allowed?

R2 has to become R2. Although B3 makes sense for actual algorithms, it is not within the scope of the challenge.

Having to handle X3 or X1 would have been a nice addition to the challenge.

"Because of this, every algorithm (set of moves) has a reverse algorithm which undoes the first algorithm" is this true for every algorithms?? Cause I think the hashing algorithms are one way. Means it doesn't have any reverse algorithms, right? please let me know

@AvishekSaha : For Rubik's Cube problems, "algorithm" is restricted to the meaning "a sequence of moves you can do on the Cube". In this sense, there is no such thing as a one-way hashing algorithm on the Cube.

oh! I was talking about algorithms in general, not the rubik's cube algorithms though.

@AvishekSaha It is not true for general algorithms. If an algorithm takes both A and B to C, then a reverse algorithm ran on C would on one hand have to return A, and on the other it would have to return B. The theory of reversibke computing is interesting, but quite different from your usual computer science.

Should have had D2R2 as a test case...

Can we assume that the input only contains valid Rubik's Cube moves? For example, if the input RL produced the output L'R', but the input RLK also produced the output L'R', would the answer be valid?

Python 2, 71 57 54 53 bytes
-15 bytes thanks to ovs! -3 bytes thanks to Rod.
lambda l:[i.strip("'")+" '"[len(i):]for i in l[::-1]]

Try it online!
String I/O, 70 bytes
lambda s:' '.join(i.strip("'")+"'"*(len(i)<2)for i in s.split()[::-1])

Try it online!

53 bytes

Retina 0.8.2, 27 26 bytes
\w
$&'
''

'2'
2
O$^`.'?2?

Try it online! Link includes test cases. Explanation: The first stage adds an apostrophe after every alphanumeric. This results in double apostrophes (with or without an inclusive 2) which need to be removed. The final stage reverses the moves.

Could this be improved with the release of Retina 1.0?

@MDXF It seems that O$^ is in fact still the best way of reversing a list of matches, so the byte count is actually unchanged in Retina 1.

V, 13 10 bytes
æGÇä/á'Ó''

Try it online!
3 bytes saved thanks to @nmjmcman pointing out my favorite feature. Explanation:
æG          " Revere the order of every line
  Ç         " On every line not containing...
   ä/       " a digit:
     á'     "   Append an '
       Ó    "   Remove every instance on this line
        ''  "     Of two single quotes

Does ä like represent a regex when compiled to vim?

@Downgoat Yes! It does. Translated into vim, this solution is :g!/\d/norm A'<CR>:%s/''//g<CR>gg:g/^/m0<CR> More information on how V compresses regular expressions can be found here

@DJMcMayhem Aren't implicit endings like your favorite feature? Try it online!

I know this is quite late, but this doesn't work for me. It turns an R2 into a 2R, which isn't valid

JavaScript (ES6), 45 bytes
s=>s.map(([a,b])=>b?+b?a+b:a:a+"'").reverse()

Shortest solution is to take Array IO. Simple and appropriate use of argument destruction.
String output is +8 bytes for .join` `.
String input, Array output: 69 bytes
(s,k=[])=>s.replace(/\S\S?/g,([a,b])=>k.unshift(b?+b?a+b:a:a+"'"))&&k

f=

(s,k=[])=>s.replace(/\S\S?/g,([a,b])=>k.unshift(b?+b?a+b:a:a+"'"))&&k

;

console.log(["R", "D U'", "S T A C K", "A2 B2"].map(e => `${e} => ${f(e)}`));
<textarea oninput="out.value=(f(this.value)||[]).join` `" placeholder="input here"></textarea>
<textarea id="out" readonly></textarea>

Nice one. Why do I never think to destructure function parameters?! :(

You should be able to replace .reverse() with ::reverse saving 1 byte but making ES7

@Downgoat Any place where I can test ES7?

@ConorO'Brien you can use babel online REPL (tick execute and all the preset boxes for all feature): https://babeljs.io/repl

JavaScript (ES6), 46 bytes
Takes input as an array of moves.
a=>a.map(m=>m[1]?+m[1]?m:m[0]:m+"'").reverse()

Test it
Enter a comma separated list of moves.

o.innerText=(f=
a=>a.map(m=>m[1]?+m[1]?m:m[0]:m+"'").reverse()
)((i.value="S,T,A,C,K").split`,`);oninput=_=>o.innerText=f(i.value.split`,`)
<input id=i><pre id=o>

Explanation
a=>

Anonymous function taking the array of moves as an argument via parameter a.
a.map(m=>                       )

Map over the array, passing each string through a function, where m is the current string.
 m[1]?

Check if the string contains a second second character ("'" or "2").
+m[1]?

If it does try to cast that character string to an integer. If the string is "2", it becomes 2, which is truthy. If the string is "'", it becomes NaN, which is falsey.
m

If the previous test is truthy, simply return m.
:m[0]

Otherwise, return the first character of m.
:m+"'"

If the string does not contain a second character then return m appended with a '.
.reverse()

Reverse the modified array.

Sorry, I just saw this. My own answer is similar to yours :P

Jelly, 10 bytes
ḟ;ċ?”'ḣ2)Ṛ

A monadic link taking an returning a list of lists of characters (an "array" of "strings").
Try it online! (The footer avoids smashing the output, displaying the list split with spaces.)
How?
ḟ;ċ?”'ḣ2)Ṛ - Link: list of lists of characters             e.g. ["F'", "D2" , "R"]
        )  - for each turn instruction:
    ”'     -   literal "'" character
   ?       -   if:
  ċ        -     count (number of "'" in the instruction) i.e.:  1   , 0    , 0
ḟ          -   then: filter out                                  "F"
 ;         -   else: concatenate                                       "D2'", "R'"
      ḣ2   -   head to index 2                                   "F" , "D2" , "R'"
         Ṛ - reverse                                            ["R'", "D2" , "F"]

10 bytes with new Jelly.

Python 3, 91 89 72 70 69 65 bytes
lambda s:[i[0]+(len(i)-2and"'"or"2"*("2"==i[1]))for i in s[::-1]]

Try it online! (With testcases)
Apparantly you don't need to take input and output as strings, so a 69 byte solution is possible

AFAIK you can delete the space after len(i)==1

@StepHen Huh, didn't know that was allowed (Knew that some interpreters allowed it, just didn't know it's allowed in codegolf)

Languages are defined by their interpreters here so, if it works in any one interpreter, it's valid.

If the interpreter allows it, you can do it. That's all code-golf cares about ;)

len(i)-2 is shorter than len(i)==1 (remember 0 is falsey)

Python,  51  48 bytes
lambda a:[(v+"'")[:2-("'"in v)]for v in a[::-1]]

An unnamed function taking and returning lists of strings.
Try it online!
Reverses the input list with a[::-1]; appends a ' to every entry with v+"'"; heads each one to 1 or 2 characters depending on whether the original had a ' in or not with [:2-("'"in v)].

PHP, 81 bytes
<?foreach(array_reverse($_GET)as$v)$r[]=$v[1]?$v[1]<2?$v[0]:$v:"$v'";print_r($r);

Try it online!

05AB1E, 13 bytes
RεÐ1èQ''si«ëK

Try it online!
Explanation
RεÐ1èQ''si«ëK
R             # Reverse input array
 ε            # Map over each element...
  Ð1èQ         # Is the second char in the element the first one? (Uses the fact that in python indexing loops)
      ''       # Push '
        s      # Swap top items of stack
         i     # If the question above is true...
          «     # Concatenate
           ë   # Else
            K   # Push element without '

J, 25 bytes
J handles this one well, other than the unfortunate escape sequence needed to represent a single quote:
|.,&''''`}:@.(''''={:)&.>

We need to represent the list using boxed data, since it's a mix of one and two character items, hence:

&.> - "under unbox", which means unbox each element, perform the operation that follows (ie, the symbols explained below) and then rebox when done
(''''={:) "if the 2nd character is a single quote"....
@. (J's agenda verb, a kind of generalized ternary statement, or a case statement) "then perform the 2nd item on the agenda list, otherwise perform the first"
}: (the 2nd item on the agenda list), "remove the last character", ie, the single quote
  ` (J's tie verb) You can think of this as the agenda item separator
,&'''' (first item on agenda list) "add a single quote to the end"
|. "reverse"

Try it online!

Haskell, 43 bytes
map f.reverse
f[x]=x:"'"
f[x,c]=x:[c|c>'1']

Try it online! Declares an anonymous function map f.reverse. Bind to g and use as g["S","T","A","C","K"].

05AB1E, 10 bytes
Rε''«¤ºK2£

I/O as a list of moves.
This is a subset of my answer for the Expand a Rubik's Cube Commutator challenge.
Try it online or verify all test cases.
Explanation:
R           # Reverse the (implicit) input-list
 ε          # Map over its strings:
  ''«       #  Append a "'" to each string
     ¤      #  Push the last character (the "'") without popping the string
      º     #  Mirror it to "''"
       K    #  Remove all "''" from the string
        2£  #  Only keep the first two characters of the string
            # (after which the result is output implicitly)

R, 51 bytes
function(u)sub("((2)|')'","\\2",paste0(rev(u),"'"))

Try it online!

Java 8, 141 128 126 115 bytes
a->(new StringBuffer(a).reverse()+"").replaceAll(".","'$0").replace("'''","").replaceAll("('(2)'|('))(.)","$4$2$3")

Takes input as single String without spaces (i.e. RUR'URU2R'U).
Try it online.
Explanation:
a->                      // Method with String as both parameter and return-type
  (new StringBuffer(a).reverse()+"")
                         //1  Reverse the input
  .replaceAll(".","'$0") //2  Prepend an apostrophe before each character
  .replace("'''","")     //3  Remove all occurrences of three adjacent apostrophes
  .replaceAll("('(2)'|('))(.)","$4$2$3")
                         //4  Replace '2'C with C2 OR 'C with C' (C is any character)

Example of the result after each step, with RUR'URU2R'U as given input:

U'R2URU'RUR
'U'''R'2'U'R'U'''R'U'R
'UR'2'U'R'UR'U'R
U'RU2R'U'RU'R'

Ruby, 44 bytes
->a{a.reverse.map{|i|i[1]?i.tr(?',''):i+?'}}

Try it online!

Scala, 47 bytes
Golfed version. Try it online!
_.reverse.map(i=>if(i.last=='\'')i else i+" '")

Ungolfed version. Try it online!
object Main {
  def f(l: List[String]): List[String] = {
    l.reverse.map(i => if (i.last == '\'') i else i + " '")
  }

  val tests: List[List[String]] = List(
    List("R"),
    List("D", "U'"),
    List("S", "T", "A", "C", "K"),
    List("A2", "B2")
  )

  def main(args: Array[String]): Unit = {
    tests.foreach(test => println(f(test)))
  }
}

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

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


text:
n * k = dd0d00d where d = ...?
Given a positive integer n ≤ 500:

Find the smallest positive integer k such that all digits in the decimal representation of n*k are either 0 or d, with 1 ≤ d ≤ 9.
Print or return d in less than 30 seconds (read more about that in the Clarifications and rules section).

Easy examples
Here are the first 30 values of d.
+----+-------+---------+---+    +----+-------+---------+---+
|  n |     k |   n * k | d |    |  n |     k |   n * k | d |
+----+-------+---------+---+    +----+-------+---------+---+
|  1 |     1 |       1 | 1 |    | 16 |     5 |      80 | 8 |
|  2 |     1 |       2 | 2 |    | 17 |   653 |   11101 | 1 |
|  3 |     1 |       3 | 3 |    | 18 |     5 |      90 | 9 |
|  4 |     1 |       4 | 4 |    | 19 |   579 |   11001 | 1 |
|  5 |     1 |       5 | 5 |    | 20 |     1 |      20 | 2 |
|  6 |     1 |       6 | 6 |    | 21 |    37 |     777 | 7 |
|  7 |     1 |       7 | 7 |    | 22 |     1 |      22 | 2 |
|  8 |     1 |       8 | 8 |    | 23 |  4787 |  110101 | 1 |
|  9 |     1 |       9 | 9 |    | 24 |    25 |     600 | 6 |
| 10 |     1 |      10 | 1 |    | 25 |     2 |      50 | 5 |
| 11 |     1 |      11 | 1 |    | 26 |    77 |    2002 | 2 |
| 12 |     5 |      60 | 6 |    | 27 |    37 |     999 | 9 |
| 13 |    77 |    1001 | 1 |    | 28 |    25 |     700 | 7 |
| 14 |     5 |      70 | 7 |    | 29 | 37969 | 1101101 | 1 |
| 15 |     2 |      30 | 3 |    | 30 |     1 |      30 | 3 |
+----+-------+---------+---+    +----+-------+---------+---+

Not-so-easy examples
One particularity of this challenge is that some values are much harder to find than others -- at least with a purely brute-force approach. Below are some examples of n that lead to a high value of k.
+-----+------------+---------------+---+    +-----+------------+---------------+---+
|   n |          k |         n * k | d |    |   n |          k |         n * k | d |
+-----+------------+---------------+---+    +-----+------------+---------------+---+
|  81 |   12345679 |     999999999 | 9 |    | 324 |   13717421 |    4444444404 | 4 |
| 157 |   64338223 |   10101101011 | 1 |    | 353 |   28615017 |   10101101001 | 1 |
| 162 |   13717421 |    2222222202 | 2 |    | 391 |  281613811 |  110111000101 | 1 |
| 229 |   43668559 |   10000100011 | 1 |    | 405 |   13717421 |    5555555505 | 5 |
| 243 |   13717421 |    3333333303 | 3 |    | 439 |   22781549 |   10001100011 | 1 |
| 283 |   35371417 |   10010111011 | 1 |    | 458 |   43668559 |   20000200022 | 2 |
| 299 |   33478599 |   10010101101 | 1 |    | 471 |   64338223 |   30303303033 | 3 |
| 307 |   32576873 |   10001100011 | 1 |    | 486 |   13717421 |    6666666606 | 6 |
| 314 |   64338223 |   20202202022 | 2 |    | 491 |  203871711 |  100101010101 | 1 |
| 317 | 3154574483 | 1000000111111 | 1 |    | 499 |   22244489 |   11100000011 | 1 |
+-----+------------+---------------+---+    +-----+------------+---------------+---+

Clarifications and rules

n*k will always contain at least one digit d, but it may contain no zero at all.
This is code-golf, so the shortest code in bytes wins. However, your program or function must be able to return the result for any 1 ≤ n ≤ 500 in less than 30 seconds on middle-range hardware.
Keep in mind that some values are harder to find than others. A program that would try to brute-force the value of k is unlikely to comply with the time-limit constraint (a good test case is n = 317). There are significantly faster methods to find d.

Reference table
All values of d for 1 ≤ n ≤ 500 are listed below.
n       | d
--------+--------------------------------------------------
001-025 | 1 2 3 4 5 6 7 8 9 1 1 6 1 7 3 8 1 9 1 2 7 2 1 6 5
026-050 | 2 9 7 1 3 1 8 3 2 7 9 1 2 3 4 1 6 1 4 9 2 1 6 7 5
051-075 | 3 4 1 9 5 7 1 2 1 6 1 2 9 8 5 6 1 4 3 7 1 9 1 2 3
076-100 | 4 7 6 1 8 9 2 1 4 5 2 3 8 1 9 1 4 3 2 5 6 1 7 9 1
101-125 | 1 6 1 8 7 2 1 9 1 1 1 7 1 2 5 4 9 2 7 6 1 2 3 4 5
126-150 | 6 1 8 3 1 1 6 7 2 9 8 1 6 1 7 1 2 1 9 5 2 7 4 1 3
151-175 | 1 8 9 7 5 4 1 2 1 8 7 2 1 4 3 2 1 8 1 1 3 4 1 6 7
176-200 | 8 3 2 1 9 1 2 1 8 5 6 1 4 9 1 1 6 1 2 3 7 1 9 1 2
201-225 | 3 2 7 4 5 2 9 8 1 7 1 4 1 2 5 9 7 2 3 2 1 2 1 7 9
226-250 | 2 1 4 1 1 3 8 1 6 5 4 3 7 1 6 1 2 3 4 7 6 1 8 3 5
251-275 | 1 6 1 2 3 8 1 6 7 2 9 2 1 6 5 7 3 4 1 9 1 8 3 2 5
276-300 | 6 1 2 9 7 1 2 1 4 5 2 7 9 1 1 3 4 1 7 5 8 9 2 1 3
301-325 | 7 2 3 8 5 6 1 4 3 1 1 8 1 2 9 4 1 2 1 8 1 7 1 4 5
326-350 | 2 1 8 7 3 1 4 3 2 5 8 1 2 3 2 1 6 1 8 3 2 1 4 1 7
351-375 | 9 8 1 6 5 4 7 2 1 9 1 2 3 4 5 2 1 8 9 1 7 6 1 2 3
376-400 | 8 1 9 1 2 3 2 1 6 7 2 9 4 1 3 1 7 1 2 5 9 1 2 7 4
401-425 | 1 6 1 4 5 2 1 8 1 1 3 4 7 9 5 8 1 2 1 6 1 2 3 8 5
426-450 | 2 7 4 3 1 1 9 1 7 3 4 1 6 1 4 3 2 1 4 5 2 3 7 1 9
451-475 | 1 4 3 2 5 8 1 2 9 2 1 6 1 8 3 2 1 6 7 1 3 8 1 6 5
476-500 | 7 3 2 1 6 1 2 3 4 5 6 1 8 3 7 1 6 1 2 9 8 7 6 1 5

Loosely inspired by (but quite different from) this recent challenge.

n=6669666 -> d=9

Interesting diagonals in that table.

@James Indeed. The patterns would appear a bit more clearly by formatting MOD 24. With MOD 25, we get some diagonals instead. :-)

Jelly, 16 15 14 bytes
²B€Ḍ9×þF%Þ¹ḢQS

Quadratic runtime (under 25 seconds on TIO).
Try it online!
Alternate version, 15 bytes
2ȷB€Ḍ9×þF%Þ¹ḢQS

Constant runtime (approx. 1 second on TIO).
Try it online!
How it works
²B€Ḍ9×þF%Þ¹ḢQS  Main link. Argument: n

²               Take the square of n.
                This bound is high enough for all integers up to 500.
                In fact, The highest value we need is 1387 for input 471, so
                2000 (2ȷ) is also enough (and a lot faster).

 B€             Binary; convert 1, ..., 4159 to base 2.
   Ḍ            Undecimal; convert each digit array from base 10 to integer.
                This generates the array A of all positive integers up to n²
                whose decimal representations consist entirely of 1's and 0's.
    9×þ         9 multiply table; for each x in A, yield [x, 2x, ..., 8x, 9x].
       F        Flatten; concatenate the resulting arrays, yielding the vector
                V. Note that V contains all numbers that match the regex ^d[0d]*$
                in base 10, in ascending order.
          ¹     Identity; yield n.
        %Þ      Sort the entries for V by their remainders modulo n. This places
                multiples of n at the beginning. The sorting algorithm in stable,
                so the first element of sorted V is the smallest multiple of n.
           Ḣ    Head; extract the first element.
            Q   Unique; deduplicate its digits in base 10. This yields [d, 0].
             S  Take the sum, yielding d.

JavaScript (ES6), 83 bytes
n=>{for(p=1;;p=k)for(d=0;d++<9;)for(k=p;k<p+p;k++)if(k.toString(2)*d%n<1)return d;}

Now returns 6 for n=252! I tried a recursive approach but it's also 83 bytes and crashes out for me for the harder numbers:
f=(n,p=1,d=1,k=p)=>k<p+p?k.toString(2)*d%n<1?d:f(n,p,d,k+1):d>8?f(n,p+p):f(n,p,d+1)

Mathematica, 103 100 97 bytes
#&@@IntegerDigits[Sort[Join@@Table[Cases[FromDigits/@{0,i}~Tuples~13/#,_Integer],{i,9}]][[10]]#]&

finds 317 in 0.39 sec
Try it online
copy/paste the code, add [317] at the end and press shift+enter to run
-3 bytes from @JungHwan Min
-3 bytes from @Keyu Gan

You can get rid of * in *#, and Tuples[{0,i},13] is {0,i}~Tuples~13

yes, of course.done!

Oh, and one more: [[1]] at the end is the same as putting #&@@ at the beginning

...and we made it to 100! thanks for -3 bytes

You may use Join@@ instead of Flatten@

and Cases[, _Integer] to replace Select[, IntegerQ]

all fixed and credited

Jelly, 21 bytes
9Rṭ€0ṗ€⁴ẎḌḍ@Ðf⁸ṢDFḟ0Ḣ

A monadic link returning the number OR a full program printing it.
A limited-range brute-forcer which takes less than 20 seconds for any 1 ≤ n ≤ 500 (less than 3 seconds for a 1 byte code cost - replace ⁴ with 13).
Try it online!
How?
9Rṭ€0ṗ€⁴ẎḌḍ@Ðf⁸ṢDFḟ0Ḣ - Link: number, n
9R                    - range of 9 = [1,2,3,4,5,6,7,8,9]
  ṭ€0                 - tack €ach to 0 -> [[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[0,9]]
       ⁴              - literal 16
     ṗ€               - Cartesian product for €ach
        Ẏ             - tighten (flatten by 1 level)
         Ḍ            - covert from decimal list to number (vectorises)
              ⁸       - chain's left argument (n)
            Ðf        - filter keep items for which this yields a truthy value:
          ḍ@          -   divisible? with swapped @rguments
               Ṣ      - sort
                D     - convert to decimal list (vectorises)
                 F    - flatten into a single list
                  ḟ0  - filter out zeros
                    Ḣ - head (get the first value)

Python 2/3, 129 128 127 bytes
from itertools import*
lambda n:next(d for p in count()for d in range(1,10)for k in range(2**p,2*2**p)if d*int(bin(k)[2:])%n<1)

-1 byte: count(0)→count()
-1 byte: ==0→<1 since it can't be negative

PHP, 87 bytes
for(;++$i<5e3;)for($n=10;$d=--$n*decbin($i);)($y&&$d>$y)|$d%$argn?:$x=$n.!$y=$d;echo$x;

Try it online!
PHP, 89 bytes
for(;++$i<5e3;)for($n=10;$d=--$n*decbin($i);)$d%$argn?:$r[$d]=$n;krsort($r);echo end($r);

Try it online!


text:
A Simple Patttern
Inputs:
Two single digits (let's call them m and n) and two chars (let's call them a and b) in your input format of choice.
Output:
For the walkthrough, pretend m=2, n=5, a='a', b='b'.
Your output will be a string built from your four inputs. Let's call the string result, with value "". First, concatenate a onto result m times, so concatenate a onto result 2 times. result now equals aa. Second, concatenate b onto result m times, so concatenate b onto result 2 times. result now equals aabb. Lastly, if result is already longer than n, truncate result so that it has length n. Otherwise, continue alternating with m length runs of a and b until result has length n. The final result is aabba, which has length 5.
Test Cases:
Input: m = 2, n = 4, a = A, b = B

Output: AABB

Input: m = 3, n = 8, a = A, b = B

Output: AAABBBAA

Input: m = 4, n = 3, a = A, b = B

Output: AAA

Input: m = 2, n = 10, a = A, b = B

Output: AABBAABBAA

As all knows, lesser one will rule the world, so the smallest programs, in bytes, win! :)

What do you mean by "total char in output will be 'n'" and "lesser one will rule the world"?

I basically rewrote the challenge, keeping what I believe was your original intent. You can rollback if you want, but in its original state it's not going to get reopened.

@StepHen you saved my day:p gracias :)

@Durga no problem :) I'm glad it still says what you wanted.

@Durga proposed test case : m=2,n=10,a=A,b=B

^ That test case is important.  Do you want it to be AABBAAAAAAA or AABBAABBAA?

@NathanMerrill agreed, my edit assumes the first, the second is more logical though.

@Rod output will be AABBAABBAA, as mentioned in case 2

@StepHen output will AABBAABBAA what Rod asked

are we guaranteed that m,n>0?

@Giuseppe yes :)

Python, 32 bytes
lambda m,n,a,b:((a*m+b*m)*n)[:n]

Try it online!

Anonymous functions are allowed last I checked so you can remove the f= for -2 bytes.

@ComradeSparklePony: Thanks for the heads up. That was leftover from the TiO; I'd actually already removed it from the byte count.

You can put the f= in the header section of TIO, so you don't need to remove it manually. TIO

Ah, I always forget about backslashes. Thanks.

To whoever suggested editing (a*m+b*m) -> (a+b)*m: this does not work.

MATL, 5 bytes
Y"i:)

Inputs are a string with the two characters, then m, then n.
Try it online!
Explanation
Y"   % Implicit inputs: string and number m. Apply run-length decoding.
     % The second input is reused for each char in the first. Gives a
     % string
i    % Input number n
:    % Push vector [1 2 ... n]
)    % Index the string with the numbers in that vector. Indexing is
     % modular, so the chars are reused if necessary. Implicit display

Haskell, 44 40 bytes
f=(.cycle).take
(n#m)a=f n.(f m a++).f m

Try it online!

Ruby, 29 characters
->m,n,a,b{((a*m+b*m)*n)[0,n]}

Sample run:
irb(main):001:0> ->m,n,a,b{((a*m+b*m)*n)[0,n]}[3, 8, 'A', 'B']
=> "AAABBBAA"

Try it online!

Japt, 10 bytes
VîUçW +UçX

First try using a golfing language. Try it online!
Explanation
Vî          // repeat the following until it reaches length V (second input)
  UçW       // third input repeated U (first input) times
      +UçX  // plus the fourth input, repeated U times

Thanks for using Japt, and well done :-) You could do VîWpU +XpU too, but both do the same thing. Vî is perfect for this challenge.

@ETHproductions Thanks, and thanks for making it! I really enjoy how everything transpiles nicely to JS code.

V, 13 bytes
ÀäjÀäêÍî
À|lD

Try it online!
a and b are taken on separate lines in the input, m and n are taken as argument, reversed (so n is the first argument and m is the second)
Explanation
Àäj      ' duplicate the inputs [arg 1] times
a -> a
b    b
     a
     b
     ...
   Àäê   ' duplicate everything straight down [arg 2] times - À cycles arguments
a -> aaa
b    bbb
a    aaa
b    bbb
...  ...
      Íî ' remove all newlines
-> aaabbbaaabbb...
À|lD     ' delete from the [arg 1] + 1 column onwards
-> aaabbbaa

Jelly, 6 4 bytes
xFṁ⁵

Try it online!
Thanks to Jonathan Allan for better input format (-2).

4 bytes as a full program with a different input format

@JonathanAllan Heh I usually try to avoid using the third argument but this time it makes my answer way shorter.

R, 41 39 bytes
function(d,m,n)cat(d[gl(2,m,n)],sep='')

An anonymous function; prints the result to stdout. Takes the characters as a vector d=c(a,b). gl generates factors (integers) of (in this case) 2 levels of run length m with total length n! cat concatenates and prints them as a string.
Try it online!

I think function(d,m,n)rep(d,e=m,l=n) would be a valid submission.

@ovs unfortunately rep will result in a vector of characters rather than a single string

05AB1E, 5 bytes
×J×I£

Try it online!
Explanation
×      # repeat a and b m times each
 J     # join to string
  ×    # repeat the string n times
   I£  # take the first n characters

Exactly what I got without checking first :P

Haskell, 36 35 29 bytes
Yet another Haskell solution (expects the characters given as a list):
(m#n)c=take n$cycle$c<*[1..m]

Try it online!
Thanks @Laikoni for -1 byte.

You can save a byte with (m#n)a b=.

Javascript, 55 bytes
(m,n,a,b)=>(a[r='repeat'](m)+b[r](m))[r](n).substr(0,n)

Example code snippet:

f=

(m,n,a,b)=>(a[r='repeat'](m)+b[r](m))[r](n).substr(0,n)

console.log(f(2, 4, 'A', 'B'))
console.log(f(3, 8, 'A', 'B'))
console.log(f(4, 3, 'A', 'B'))
console.log(f(2, 9, 'A', 'B'))

Javascript, 53 bytes
(m,n,a,b)=>a.repeat(n).replace(/./g,(i,j)=>j/m&1?b:i)

Husk, 3 bytes
Direct Port of my Haskell answer, except that the argument order is different:
↑¢Ṙ

Try it online!

Java (OpenJDK 8), 75 bytes
void f(int m,int n,char[]s){for(int i=0;i<n;)System.out.print(s[i++/m%2]);}

Try it online!

Haskell, 48 43 bytes
(m#n)a|r<-(<$[1..m])=take n.cycle.(r a++).r

Try it online!

QBIC, 37 27 bytes
[:|G=;+G+;][:|G=G+G]?_sG,d

Explanation
          This takes its arguments as frequency m, A, B, length n
          For example: 2, A, B, 8
 :        Read a cmd line arg as number 'b' ('a' is used by the FOR declaration as loop counter)
[ |       Start a FOR loop, from 1 to b
G=  G     Set G to hold itself
  ;+      prepended by a cmd line arg read as strig and assigned to A$
     +;   and followed by a cmd line arg read as strig and assigned to B$
]         At the end of the FOR loop, G has had A added to the front twice, and B t the end x2: G$ = AABB
[:|       FOR c = 1 to n
G=G+G]      Add G to itself          G$ = AABBAABBAABBAABBAABBAABBAABBAABB
?_sG,d    PRINT the first n chars of G$   AABBAABB

Previous attempt:
(37b)  {Z=Z+;┘_LZ|~a=:|_X]~a%:|\C=A┘A=;┘B=C
Takes its arguments as `A, length n, frequency m, B`.
Basically adds A to Z until length % freq = 0, then swaps A for B. Loops until lengtn = n

PHP>=7.1, 77 bytes
for([,$x,$l,$f,$s]=$argv;$l-=$z;)echo str_repeat(++$i&1?$f:$s,$z=min($l,$x));

PHP Sandbox Online

Cubix, 63 58 bytes
.rr.@u:s?.\.sw).i|>v:.\nB;?(q:Is...;rr/s.uw/....sIB/\/?(qo

Try it online!
watch the interpreter
Takes input like ab*m*n where the * can be any non-digit character.
Cube version:
        . r r .
        @ u : s
        ? . \ .
        s w ) .
i | > v : . \ n B ; ? ( q : I s
. . . ; r r / s . u w / . . . .
s I B / \ / ? ( q o . . . . . .
. . . . . . . . . . . . . . . .
        . . . .
        . . . .
        . . . .
        . . . .

i|is : read in the chars, and swap them (so a is on top)
I:q : read in m, dup, and push to bottom (stack is now m,b,a,m)
) : decrement
? : turn right if positive, go straight if zero (duplicates a)
positive branch (loop)

s:rur(/w : swap, dup, move m-i to the top of the stack, decrement m-i

zero branch

B : reverse stack (which now has m copies of a: a... b m)
n : negate m (so we can use ? to turn left)
) : increment
? : go straight if zero, turn left if negative

negative branch  (duplicates b)

s:r\/rw)\ basically the same as the positive branch but with increment and left turns.

zero branch (prints the output)

>v; : pop the 0 off the stack (looks like a...b...)
/B : reverse the stack
I : read n
s : swap
print loop:

oq : print and push to bottom of stack now looks like: ab...a...n
( decrement n
? : turn right if positive, go straight if zero
If right, : /su : swap top of stack and continue the loop
if zero, / reflects down and the code evaluated is Iru@; @ terminates the program.

APL (Dyalog), 5 bytes
⎕⍴⎕/⎕

Try it online!
Takes the two chars in a string as the first input, followed by m and then n.
Explanation
Let the example input be 'ab', 2, 10.
⎕/⎕                 Replicate the two-char string `m` times
                    2/'ab' => 'aabb'
⎕⍴                  Shape it so that its length is `n`
                    10⍴'aabb' => 'aabbaabbaa'

Pyth, 13 bytes
KE<*+*EQ*EQKK

Try it online!
Explanation
                 # Implicitly store m to Q
KE               # Store n to K
     *EQ         # Perform a * m
        *EQ      # Perform b * m
    +            # Concatenate the two strings
   *       K     # Multiply by n
  <         K    # Take the first n characters of the string

Charcoal, 10 bytes
…⁺×ζＩθ×εＮＮ

Try it online! Link is to verbose version of code and includes fourth example. (Annoyingly the deverbosifer won't remove the separator if I add one before the last InputNumber().)

What do you mean by the separator? (Can you give an example)

@ASCII-only With the comma before the last InputNumber(),  notice that the generated code has an unnecessary separator: Try it online!

Mathematica , 61 bytes
T=Table;StringTake[""<>Flatten@T[{#3~T~#,#4~T~#},⌈#2/#⌉],#2]&

input

[2,10,"A","B"]

Mathematica, 44 bytes
StringPadRight[x={##3}~Table~#<>"",#2,x]&

Explanation
 is the three byte private use character U+F3C7, representing the postfix \[Transpose] operator in Mathematica. No TIO link because Mathics does not support , \[Transpose] has the wrong operator precedence, the second argument to Table is required to be a list, and most importantly, StringPadRight is not implemented.
                                         & (* Function *)
                 {##3}                     (* which takes the third and fourth arguments *)
                      ~Table~#             (* repeats them a number of times equal to the first argument *)
                                          (* takes the tranpose *)
                               <>""        (* then joins the strings with the empty string *)
               x=                          (* sets x equal to that string *)
StringPadRight[                            (* then pads x *)
                                   ,#2     (* to a length equal to the second argument *)
                                      ,x]  (* with x. *)

k, 10 bytes
{y#,/x#'z}

Try it online!

Chip, 588 bytes
*Z~vZ.*ZZZs  z. z. z. z. z. z. z. z.
  ,'|`-. ZZ--#<,#<,#<,#<,#<,#<,#<,#<
a/mAM/a| `~S `x'`x'`x'`x'`x'`x'`x'`x.
b/mBM/b|  *.)/')/')/')/')/')/')/')/'|
c/mCM/cZv--x^x-^x-^x-^x-^x-^x-^x-^x-'
d/mDM/d||A~#M',-',-',-',-',-',-',-'
e/mEM/e||B~#M-',-',-',-',-',-',-'
f/mFM/f||C~#M--',-',-',-',-',-'
g/mGM/g||D~#M---',-',-',-',-'
h/mHM/h||E~#M----',-',-',-'
 `v~v' ||F~#M-----',-',-'
* `mz  ||G~#M------',-'
Z  `---x'H~#M-------'
Z,--z--^----'
Z|z. z. z. z. z. z. z. z.
Zx#<,#<,#<,#<,#<,#<,#<,#<
 |`x'`x'`x'`x'`x'`x'`x'`xT
 |A| B| C| D| E| F| G| H|
 )\')\')\')\')\')\')\')\'
 `--^--^--^--^--^--^--'

Try it online!
Takes input as a 4-character string. The first two are the characters a and b, followed by the byte value m, and then the byte value n. For example, the TIO includes input ab<tab>2, this corresponds to 'a', 'b', 9, 50. (Since the codes for <tab> and 2 are 9 and 50.
How?
This answer is a bit of a behemoth, but here's the highlights:
The upper left block, with the lowercase a-h, is the storage mechanism for the characters a and b, one line per bit. At its bottom, with the v~v and mz is the switching mechanism, to swap between the two.
In the middle is a column with a bunch of ~#M's. This reads in m and stores its negative. The big triangle to the right is just wires to bring this value into the upper accumulator.
The upper right block is the accumulator for m. It increments every cycle (starting from -m) until it reaches zero. When this happens, the output character is swapped, and counting restarts from -m.
Meanwhile, there is the lower block, which is the n accumulator. Since n is only read once, we don't need a bank of memory (M and m) to store this value. We simply negate it and start counting. When this value reaches zero, the whole shebang is simply terminated.
All the other guff is delays (Z and z), wiring (-, |, ...), and other miscellany.


text:
The sum of consecutive odd numbers
Although related challenges have been asked, this one is different to warrant its own question.

Challenge
Given a positive integer, return the longest sequence of consecutive positive odd integers whose sum is the given integer. If no such sequence exists, you may report an error in whatever way makes sense for your language, including returning a falsy value or throwing an exception.
Test Cases

  1 -> [1]
  2 -> []
  3 -> [3]
  4 -> [1, 3]
  5 -> [5]
  6 -> []
  9 -> [1, 3, 5] (note that [9] is not a valid answer)
 15 -> [3, 5, 7]
104 -> [23, 25, 27, 29] (note that [51, 53] is not a valid answer)

Scoring
This is code-golf, so the shortest answer in each language wins.

Can my program just run forever if there's no solution?

Very related. The fact that some even numbers cannot be represented in this one might save it from being a dupe though.

Can't 15 give [-1, 1, 3, 5, 7]? If only positive values are allowed, you should say so.

@Dennis Yes that is fine

@xnor Good point. When I made the challenge I intended the answers to be only positive odd integers. I'll update the challenge spec to reflect that

For 104 longest is 1+3+5+7+9+11+13+15+19+21 , not 23+25+27+29

@ЕвгенийНовиков you skipped 17

@kalsowerus yes. I misunderstand word "consecutive"

Sorry about that - my wording may be a little complex. Feel free to edit my post if you can think of an easier way to describe the challenge!

Haskell, 67 65 63 62 58 bytes
Saved 4 bytes thanks to Julian Wolf
f x=[[2*n+1,2*n+3..2*m]|n<-[0..x],m<-[n..x],m^2-n^2==x]!!0

Try it online!
I check if the number can be expressed as he difference of two squares: m^2-n^2. I can then construct the list of consecutive odd numbers: [2n+1,2n+3...2m-1]. Note that because the minimum n is chosen, the longest list will be output

Down-voter: It would be both friendlier and more constructive to add a comment giving your reason, especially when down-voting a new user.

Unless I'm missing something, you can save 4 bytes by only going up to x for both n and m

Just so you know, the downvote was cast automatically by the Community user when you edited your answer. I consider this a bug. (CC @JonathanAllan)

Ahh, it was one of those.

Jelly,  11  10 bytes
-1 byte thanks to Dennis (use the implicit range building of Ẇ - replace Rm2Ẇ with ẆḤ’)
ẆḤ’S_¥Ðḟ⁸Ṫ

A monadic link returning a list of the summands if possible, or 0 if not.
Try it online!
How?
ẆḤ’S_¥Ðḟ⁸Ṫ - Link: number, n
Ẇ          - all sublists (implicit range of input) note: ordered by increasing length
           -                i.e. [[1], [2], [3], ..., [1,2], [2,3], ..., [1,2,3], ...]]
 Ḥ         - double              [[2], [4], [6], ..., [2,4], [4,6], ..., [2,4,6], ...]]
  ’        - decrement           [[1], [3], [5], ..., [1,3], [3,5], ..., [1,2,5], ...]]
        ⁸  - link's left argument, n
      Ðḟ   - filter out items for which the following yields a truthy value:
     ¥     -   last two links as a dyad:
   S       -     sum
    _      -     subtract the right from the left = sum - n
         Ṫ - tail (last and hence longest such run)

ẆḤ’ saves a byte.

Python 2, 66 62 bytes
f=lambda n,k=0,*r:n-sum(r)and f(n,k+1,*range(k%n|1,k/n,2))or r

Exits with a RuntimeError (maximum recursion depth exceeded) if there's no solution.
Try it online!

If the input values are high enough, but there is a solution, will this result in a RuntimeError?

If the recursion limit isn't high enough and/or the stack isn't big enough, yes. However, it's common to ignore physical limitations (e.g., a C answer only has to work for 32-bit ints), and the OP explicitly said that running forever is acceptable if there's no solution.

JavaScript (ES7), 87 86 85 81 bytes
Returns a comma-delimited list of integers, or 0 if no solution exists.
n=>(g=(s,k,x=n+s)=>(x**.5|0)**2-x?k>n?0:g(s+k,k+2):(n-=k)?k+','+g(-n,k+2):k)(0,1)

How?
We first look for the smallest perfect square s such that x = n + s is another perfect square.
If s exists, n is the difference x - s of 2 perfect squares, which can be written as the difference of 2 sequences of consecutive odd numbers. We then build the resulting list.
Example:
For n = 104:
We find s = 11² = 121 which satisfies x = n + s = 225 = 15²
Then:
15² = 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 + 21 + 23 + 25 + 27 + 29
11² = 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 + 21
104 = 15² - 11² = 23 + 25 + 27 + 29

let f =

n=>(g=(s,k,x=n+s)=>(x**.5|0)**2-x?k>n?0:g(s+k,k+2):(n-=k)?k+','+g(-n,k+2):k)(0,1)

console.log(f(1))   // -> 1
console.log(f(2))   // -> 0
console.log(f(3))   // -> 3
console.log(f(4))   // -> 1,3
console.log(f(5))   // -> 5
console.log(f(6))   // -> 0
console.log(f(9))   // -> 1,3,5
console.log(f(15))  // -> 3,5,7
console.log(f(104)) // -> 23,25,27,29

Wait are you telling me that n^2 is always equal to the sum of the first n odd numbers? Huh, interesting

@Mayube Indeed!

https://math.stackexchange.com/questions/639068/sum-of-odd-numbers-always-gives-a-perfect-square

05AB1E, 9 8 bytes
-1 byte thanks to Emigna
ÅÉŒʒOQ}н

Explanation:
ÅÉ           Generate a list of odd numbers up to, and including, the input
  Œ          Substrings
   ʒ         Only keep values
    O          where the sum
     Q         equals the input
       }     End
             For 9, the result would look like this:
             [[1, 3, 5], [9]]
        н    Get the first value

On invalid input, outputs nothing.
Try it online!

ʒOQ} instead of DO¹QÏ saves a byte.

@JonathanAllan Docs say "uneven" so that might've been confused...

@JonathanAllan Small mistake. Fixed.

Haskell, 61 60 bytes
Thanks to @maple_shaft for shaving off 1 byte
f n=[k|r<-[1,3..],s<-[r,r+2..n],k<-[[r,r+2..s]],sum k==n]!!0

Try it online!
Uses the fact that the longest run will always be the run that starts with the lowest number.
I wanted to do something with arithmetic in stead of brute-forcing k, but fromInteger seems to kill it.

You can save yourself one byte by changing [1,3..n] to [1,3..]

You can save 7 bytes with a helper function r?n=[r,r+2..n]. Try it online!

Python, 67 bytes
f=lambda n,R=[1]:n-sum(R)and f(n,[R+[R[-1]+2],R[1:]][sum(R)>n])or R

Try it online!
I copied my answer from the previous consecutive sum challenge and changed the +1 to +2. Who knew that golfed code could be so modular?
An oddly straightforward strategy: search for the interval R with the desired sum.

If the sum is too small, shift the right endpoint of the interval up
2 by appending the next number 2 above it.
If the sum is too large, shift up the left endpoint by removing the smallest element
If the sum is correct, output R.

Since the bottom end of the interval only increases, longer intervals are found before shorter ones. If no possible interval can be found, terminates with IndexError.

JavaScript (ES6), 65 64 bytes
f=(a,i=1)=>a>i?(c=f(a-i,i+=2))[0]==i?[i-2,...c]:f(a,i):a
  a > i ?
    (c = f(a - i, i += 2))[0] == i ?
      [i-2, ...c] :
      f(a, i) :
  a a>i?(c=f(a-i,i+=2))[0]==i?[i-2,...c]:f(a,i):a<i?0:[i]

console.log(JSON.stringify(f(1)));   //[1]
console.log(JSON.stringify(f(3)));   //[3]
console.log(JSON.stringify(f(4)));   //[1, 3]
console.log(JSON.stringify(f(5)));   //[5]
console.log(JSON.stringify(f(6)));   //[0]
console.log(JSON.stringify(f(9)));   //[1, 3, 5]
console.log(JSON.stringify(f(15)));  //[3, 5, 7]
console.log(JSON.stringify(f(104))); //[23, 25, 27, 29]

For an idea of how inefficient this is, the solution to f(104) requires 69,535 recursive calls.  The stack is never more than 51 levels deep, so no problem with stack overflow.
The solution to f(200) requires 8.6 million recursive calls, with a stack 99 levels deep.  (Its solution is [11,13,15,17,19,21,23,25,27,29].)
Here's a visual representation of the program running:

r=0;
output=o=>setTimeout(_=>O.textContent += o + '\n', r++ * 20);

f=(a,i=1,s='',o = s + 'a=' + a + '; i=' + i + ';')=>
(
  output(o),
  a > i ?
    (c = f(a - i, i += 2, s + '  '))[0] == i ? (
      output(o + ' a > i; [i-2, ...c] = [' + [i-2, ...c] + '];'),
      [i-2, ...c]
    ) : (
      output(o + ' a > i; c=[' + c + ']; ' + 'c[0]+2 != i ... dead end\n' + s + 'trying a, i+2:'),
      f(a, i, s)
    ) :
  a < i ? (
    output(o + ' a < i ... dead end'),
    0
  ) : (
    output(o + ' a == i;'),
    [i]
  )
)

f(21);  //[5, 7, 9]

Python 2.7, 109 108 97 bytes
11 bytes down, Thanks to Erik the Outgolfer.
This is my first code golf!
def f(N):
 for n in range(N):
    x=(n*n+N)**.5-n
    if x%1==0:return[2*(k+n)+1for k in range(int(x))]

How it works
I used the well known identity that 1 + 3 + 5 + ... + (2n - 1) = n²
Take the case of 15
15 = 3 + 5 + 7 = (1 + 2) + (3 + 2) + (5 + 2) = (1 + 3 + 5) + 3×2 = 3² + 3×2

In general, if there are x terms starting from 2n + 1, like
(2n + 1) + (2n + 3) + (2n + 5) ... (2n + (2x-1))

 It is equal to 2nx + x²

If N is the input integer, the problem reduces to finding maximum x such that
x² + 2nx - N = 0

It is a quadratic equation with solution
x = sqrt(n² + N) - n

The longest sequence is one with largest x. The program iterates n from 0 to N and when it find that x is an integer, it creates a list of (2n + 1) + (2n + 3) + (2n + 5) ... (2n + (2x-1)) and returns it.

You can trivially golf 11 bytes off.

@EriktheOutgolfer, Thanks, I forgot about using tabs (=

Python 3, 190 81 Bytes
def c(q,l,i):
    if sum(l)0:
        l.append(i)
        return c(q,l,i+2)
    elif sum(l)>q:
        l.pop(0)
        return c(q,l,i)
    else:
        print(l)
c(q,[1],1)
c=lambda q,l=[1]:c(q,l+[l[-1]+2])if(sum(l)<q)*l else c(q,l[1:])if sum(l)>q else l

Thanks to @ovs and @musicman523

You can get this down to 122 bytes just by removing some indentation. If you want to shorten your code further, have a look at Tips for golfing in Python.

This doesn't run in Python 3, because the call to print is missing parentheses

You can remove l.append(i) by simply using l+[i] in the recursive call. You can remove l.pop(0) by using l[1:] in the recursive call. You can remove the call to c at the very bottom by using keyword arguments instead. You can remove >0 on line 2. Finally, you can change your if and else statements into expressions, using the ternary form, which gets you down to 92 bytes as a lambda expression. Try it online!

Based on @musicman523 suggestions we can still shorten the conditions and drop i to get to a total of 81 bytes.

I think you could change sum(l)>q else to q<sum(l)else to save 1 byte.

QBIC, 47 bytes
{_Cg=q┘q=q+2~g>:|_Xp\?g,[q,a,2|?b,┘g=g+b~g=a|_X

This tries to count all the odd numbers from one until its sum is n. If it passes n, reset the loop, increase 1 to 3 and try again. Quit, printing 0, if at the start of the loop our number > n.
Explanation
{       Do infinitely
_C      Clear the screen (we basically print every run of odd numbers, but clear out everything that doesn't sum up to n)
g=q     Set g to the first num of this cycle (q starts as 1 in QBIC)
┘       (Syntatcic linebreak)
q=q+2   Raise q to the next odd number, this sets up both the next outer loop as well as a coming FOR loop
~g>:|   If we start out with a number > n (read as 'a' from the cmd line)
_Xp     THEN quit, printing 0 (the value of the number var 'p')
\       ELSE
[q,a,2| FOR b = q, b <= n, b+=2
?b,┘    PRINT b followed by a tab
g=g+b   Add 'b' to running total 'g'
~g=a|   and if that lands us on 'n'
_X      QUIT (printing nothing: everything is already printed)

Pyth, 11 bytes
efqsTQ.:%2S

Try it here.

Python 2, 91 90 bytes
-1 byte thanks to  @CMcAvoy
lambda n,r=range:[r(i,j+1,2)for i in r(1,n+1,2)for j in r(i,n+1,2)if(i+j)*(2+j-i)==4*n][0]

Try it online!

PHP, 73 bytes

no solution is a infinite loop
for($e=-1;$s-$i=$argn;)$s+=$s<$i?$n[]=$e+=2:-array_shift($n);print_r($n);

Try it online!
PHP, 83 bytes
prints nothing for no solution
every input mod 4 == 2 has no solution

for($e=-1;($i=$argn)%4-2&&$s-$i;)$s+=$s<$i?$n[]=$e+=2:-array_shift($n);print_r($n);

Try it online!

fails to detect unsolvable input

@Titus fixed...

R, 90 bytes
f=function(x,y=1)'if'(length(w<-which(cumsum(r<-y:x*2-1)==x)),r[1:w],'if'(y>x,0,f(x,y+1)))

Try it online!
Uses a recursive function that test sequence cumulative sum of y:x converted to an odd number sequence. y is incremented on each recursion until it exceeds x.  The first sequence which sums to the target will be returned.

Python 2, 89 bytes
lambda n,r=range:[v for v in[r(1,n+1,2)[i:j]for i in r(n)for j in r(n+1)]if sum(v)==n][0]

An unnamed function taking a positive integer, n, and returning the result if it exists and raising an IndexError otherwise.
Try it online!
Creates a list of all the relevant odd numbers with r(1,n+1,2) which is range(start=1, stop=n+1, step=2); creates all the relevant sub-slices (plus some empty ones) by slicing that from i inclusive to j exclusive with [i:j] across i in [0,n)  using r(n) and j in [0,n] using r(n+1) (the empty ones when i>=j or i is out of bounds); filters for those with the correct sum with if sum(v)==n; returns the first (and hence longest) such slice using [0].

PHP, 78 bytes
for($b=-1;$s-$argn;)for($n=[$s=$x=$b+=2];$s<$argn;)$s+=$n[]=$x+=2;print_r($n);

infinite loop if no solution. insert ?$b>$argn+2?$n=[]:1:0 after $s-$argn to print empty array instead.
Run with -nR or try it online.

Excel VBA, 139 Bytes
Subroutine that takes input n of expected type integer and reports the longest sequence of consecutive odd numbers to cell [A1]
Sub a(n)
For i=1To n Step 2
s=0
For j=i To n Step 2
s=s+j
If s=n Then:For k=i To j-1 Step 2:r=r &k &"+":Next:[A1]=r &j:End
Next j,i
End Sub

C# (.NET Core), 129 bytes
(i)=>{int s,j,b=1,e=3;for(;;){var o="";s=0;for(j=b;j<e;j+=2){s+=j;o+=j+" ";}if(s==i)return o;s=s<i?e+=2:b+=2;if(b==e)return"";}};

Outputs numbers in a string, space delimited (any other character would just require changing the " "). Input with no solution returns an empty string (though if running forever without error is a valid way to indicate no solution then 17 bytes could be saved by removing if(b==e)return"";).
Algorithm is:

Start with [1]
If the sum is equal to the target, return the list
If the sum is less than the target, add the next odd number
If the sum is greater than the target, remove the first item
If the list is empty, return it
Repeat from 2

You can write (i)=> as i=>

C++, 157 -> 147 Bytes

-10 Bytes thanks to DJMcMayhem
will return 0 if there's no answer, 1 otherwise
the last line it prints is the answer
int f(int n){for(int i=1;;i+=2){int v=0;for(int k=i;;k+=2){v+=k;std::cout<<k<<" ";if(v==n)return 1;if(v>n)break;}if(i>n)return 0;std::cout<<"\n";}}

ungolfed:
int f(int n)
{
    for (int i = 1;; i += 2)
    {
        int v = 0;
        for (int k = i;; k += 2)
        {
            v += k;
            std::cout << k << " ";
            if (v == n)
                return 1;
            if (v > n)
                break;

        }
        if (i > n)
            return 0;
        std::cout << "\n";
    }
}

this is my first code golf ^^

You could save some bytes if you made it an int function and returned 0 or 1. Also, you could do int v=0; instead of int v;....v=0; and if you made your output Newline delimited, you could do std::cout<<k<<"\n"; and then remove the second Newline altogether

the if i did the last recomendation then it would print a new line on every single number but i want to seperate number groups, but thanks anyways for -10 Bytes

Kotlin, 152 bytes
fun f(a:Double){var n=Math.sqrt(a).toInt()+1;var x=0;while(n-->0){if(((a/n)-n)%2==0.0){x=((a/n)-n).toInt()+1;while(n-->0){println(x.toString());x+=2}}}}

Try it online (Wait 4-5 seconds, compiler is slow)
Ungolfed
fun f(a: Double){
    var n=Math.sqrt(a).toInt()+1;
    var x=0;

    while(n-->0){
        if(((a/n)-n)%2==0.0){
            x=((a/n)-n).toInt()+1;

            while(n-->0){
                println(x.toString());
                x+=2;
            }

        }
    }
}

Python 2, 122 121 119 115 bytes
-1 byte thanks to musicman523. -4 bytes thanks to Step Hen. haha
def f(n,R=range):r=R(1,n,2);print[i for w in R(1,len(r)+1)for i in[r[j:j+w]for j in R(len(r)-w+1)]if sum(i)==n][-1]

Try it online!

This is one byte shorter as a function. Try it online!

Save bytes if you redefine range, Try it online!

This fails for 1.

Python 3, 93 bytes
lambda n,r=range:[[*r(s,e+1,2)]for s in r(1,n+1,2)for e in r(s,n+1,2)if(s+e)*(2+e-s)==4*n][0]

Try it online!
Only thing special I did was noting that (s+e)*(2+e-s)==4*n is equivalent to sum(range(s,e+1,2))==n, and though they're the same size when r=range, the former can be placed closer to the if statement.

Python 3, 185 bytes
def f(s):
  d={k:v for k,v in{a:(1-a+((a-1)**2+4*s)**(.5))/2 for a in range(1,s,2)}.items()if int(v)==v};m=max(d.keys(), key=(lambda k: d[k]));return list(range(int(m),int(m+2*d[m]),2))

Try it online!

As for how this works, I tried to go for a bit more elegant solution than a simple brute force search. I rearranged the formula for the sum of an arithmetic sequence and applied the quadratic formula to get the expression (1-a+((a-1)**2+4*s)**(.5))/2, which appears in the code. What the expression calculates is, given a desired sum s and a first term for of arithmetic sequence a, the length of the sequence. These lengths are stored in a dictionary as values to the first terms as keys.
Next, all non-integer values are removed from the dictionary, as those represent invalid sequences. From there, the largest value is identified with max(d.keys(), key=(lambda k: d[k])) and the sequence of odd numbers at that position and at that length is made with list(range(int(m),int(m+2*d[m]),2)).

I'm looking for help golfing this if you see anything. I was more interested in seeing how well I could do with a non-trivial algorithm; my answer is nearly twice as long as the best Python solution.

Would this work? https://repl.it/JTt7 (177 bytes)

Mathematica, 56 bytes
Last@Cases[Subsequences@Table[n,{n,1,#,2}],x_/;Tr@x==#]&

Function with first argument #. Table[n,{n,1,#,2}] computes the list of positive odd numbers less than or equal to #. Subsequences returns all subsequences of that list ordered by increasing length. We then take the Cases which match x_/;Tr@x==#, that is, sequences x such that their sum Tr@x is equal to the input #. We then take the Last such sequence.

JavaScript (ES6), 72 bytes
n=>(g=s=>s?s>0?g(s-(u+=2)):g(s+l,l+=2):u-l?l+' '+g(s,l+=2):u)(n-1,l=u=1)

Returns a space-separated string of odd numbers or throws on invalid input. 84 byte version that returns an (empty when appropriate) array:
n=>n%4-2?(g=s=>s?s>0?g(s-(u+=2)):g(s+l,l+=2):u-l?[l,...g(s,l+=2)]:[u])(n-1,l=u=1):[]

Explanation: Loosely based on @Cabbie407's awk solution to Sums of Consecutive Integers except I was able to save some bytes by using recursion.

authors: Евгений Новиков


text:
Reduce the list to a final number
Inputs
A list (array) of numbers, or numerical strings if that makes it easier. You can assume there will always be at least two elements in the list and every element will be a natural number (integer larger than zero).
Outputs
A single number, or again, a numerical string.
Problem
The idea is to reduce the list of numbers by removing the last digit of the largest number at that current stage of the list, eventually ending with one number (only one number should be returned, even if there are multiple instances)
Example
[123,343,121,76,465,786] -- The last digit in 786 is dropped, so it becomes 78
[123,343,121,76,465,78]  -- New largest number is 465, so the 5 is dropped, making it 46
[123,343,121,76,46,78]   -- Repeat until left with one number
[123,34,121,76,46,78]
[12,34,121,76,46,78]
[12,34,12,76,46,78]
[12,34,12,76,46,7]
[12,34,12,7,46,7]
[12,34,12,7,4,7]
[12,3,12,7,4,7]
[1,3,1,7,4,7]            -- If there are multiple max numbers, you **must** remove the last digit from all of them
[1,3,1,4]
[1,3,1]
[1,1]                    -- You have your answer when there is one number, or multiple numbers that are equal
1                        -- Result

Loopholes
Standard loopholes apply
Other constraints
Your program must work for any list of random numbers (within reason of course)
Test Cases
[24,72,4]
[24,7,4]
[2,7,4]
[2,4]
[2]
2

[14, 7]
[1, 7]
[1]
1

[1278,232,98273,2334]
[1278,232,9827,2334]
[1278,232,982,2334]
[1278,232,982,233]
[127,232,982,233]
[127,232,98,233]
[127,232,98,23]
[127,23,98,23]
[12,23,98,23]
[12,23,9,23]
[12,2,9,2]
[1,2,9,2]
[1,2,2]
[1]
1

Scoring
This is code-golf, so shortest answer in every language wins!

Please let me know if I missed anything. First question.

@DJMcMayhem I should note that you do not have to output each stage. But rather just return or print the final result.

I know. Is it OK to print the final result with trailing newlines?

@DJMcMayhem Sure. I do not see any reason why not.

Dunno if it's too late to change, but the question might be better if we did have to output each stage. I think the answers will be quite straightforward otherwise.

@DLosc I didn't think about this too much, and it turned out to be far more trivial than I had expected. Bummer, but I learned from it. Thanks!

Since no one else has mentioned it, this is the kind of thing that would frequently be caught in the sandbox.

@DJMcMayhem, didn't know that existed, thank you.

Can you add testcases where the answer is not the first digit of the first entry in the list?

Nearly all the answers fail for [12,23,12]. The expected answer to that test case is 2. All print 1.

@OlivierGrégoire No it isn't? [12, 23, 12] -> [12, 2, 12] -> [1, 2, 1] -> [1, 1] -> 1?

You said we have to remove the values... So it's [12,23,12] -> [12,2,12] -> [2] -> 2. Am I wrong?

@OlivierGrégoire "If there are multiple max numbers, you **must** remove the last digit from all of them"

My bad, the formatting actually hid the text right after remove and I then understood remove [the value]. Sorry everyone! ^_^'

@OlivierGrégoire No, thank you! I wish I had implemented that, the problem was far more trivial than I had hoped.

Nothing forbids you to create another challenge with my misunderstanding as a replacement rule. It would be indeed more challenging.

The way I read this question the answer for [12, 123, 124] is 12, which makes every single posted answer wrong.

Haskell, 16 bytes
minimum.map head

Try it online!

Python 2, 24 bytes
-4 bytes thanks to notjagan.
lambda l:min(zip(*l)[0])

Try it online!

This can be shortened 4 bytes while keeping the same idea using min(zip(*l)[0]).

Python 3, 24, 21, 18 bytes
lambda l:min(l)[0]

Try it online!
Three Six bytes saved thanks to @totallyhuman!

Mathematica, 29 bytes
Min[First@*IntegerDigits/@#]&

Japt, 8 6 5 bytes
-1 byte thanks to @Shaggy
n g g

Takes input as an array of numeric strings. Try it online!
Explanation
        // implicit input: array of strings
n       // sort the array
  g     // get the first element
    g   // get the first character
        // implicit output

5 bytes: Sort the array, get the first element, get the first character.

@Shaggy Oh duh, I totally over complicated this one. Thanks!

No problem :) n v g would also work for 5 bytes. Welcome to Japt, by the way.

JavaScript (ES6), 17 bytes
Takes input as an array of strings.
a=>a.sort()[0][0]

Try it
Input a comma separated list of numbers.

o.innerText=(f=
a=>a.sort()[0][0]
)((i.value="1278,232,98273,2334").split`,`);oninput=_=>o.innerText=f(i.value.split`,`)
<input id=i><pre id=o>

V, 11, 5 bytes
ÚxV}p

Try it online!
I was making this waaay more complicated than it actually is. This answer simply sorts every line by ASCII values, and then returns the very first character. Since this is kind or a boring answer, here is a more interesting answer that actually implements the algorithm originally described:
V, 11 bytes
òún
/äîä
Lx

Try it online!

I was too when I posed the question. Your original answer was what I expected most to look like. Bummer.

05AB1E, 3 bytes
€нW

Try it online!

Fails for [12,23,12].

@OlivierGrégoire: How? Removing the digits in the order 3,2,2,2,1 results in 1 as expected.

My bad, I misread. See previous comment.

PHP, 45 bytes
<?foreach($_GET as$v)$r[]=$v[0];echo min($r);

Try it online!

Fails for [12,23,12].

@OlivierGrégoire [12,23,12]->[12,2,12]->[1,2,12]->[1,2,1]->[1,1]->[1]->1 is in my opinion correct

My bad, I misread. See previous comment.

Jelly,  3  2 bytes
ṂḢ

A full program which takes a list of lists of characters (strings) and prints the result.
Try it online!
How?
We just need to return the smallest leading digit...
ṂḢ - Main link: list of lists of characters
Ṃ  - minimum (lexicographical ordering ensures this will start with the minimal digit)
 Ḣ - head (get that first digit character)

No problem, it happens.

Braingolf, 17 bytes
VVR{Mvd<M&$_R}vvx

Try it online!
Explanation
VVR{Mvd<M&$_R}vvx  Implicit input from commandline args
VVR                Create stack2 and stack3, return to stack1
   {.........}     Foreach item in stack..
    M              ..Move item to next stack
     v             ..Switch to next stack
      d            ..Split item into digits
       <M          ..Move first item to next stack
         &$_       ..Clear stack
            R      ..Return to stack1
              vv   Switch to stack3
                x  Reduce to lowest value
                   Implicit output of last item on stack

In other words, it constructs a stack consisting of only the first digit of each item, then outputs the lowest.
This challenge gave me a bunch of useful ideas for builtins to add to Braingolf, and now thanks to the addition of the "special" foreach loop, Braingolf can do it in 5 bytes:
Braingolf, 5 bytes [non-competing]
(d<)x

Explanation
(d<)x  Implicit input from commandline args
(..)   Special foreach loop, iterates over the stack, moving each item to a special
       Sandboxed stack environment, and prepends the last item of the sandboxed
       stack to the real stack at the end of each iteration
 d<    Split into digits, move first digit to end of stack
    x  Reduce to lowest value
       Implicit output of last item on stack

Try it online!
I'm normally against adding builtins just to complete one challenge, but I can see a plethora of uses for the new (...) foreach loop, so I don't really consider it adding a feature just for this challenge.

Fails for [12,23,12]. Expected output is 2, you returned 1.

@OlivierGrégoire The expected output of that is 1: [12,23,12] > [12,2,12] > [1,2,1] > [1,1]

My bad, I misread. See previous comment.

,,,, 3 bytes
⫰1⊣

Explanation
⫰1⊣

⫰    pop the whole stack and push the minimum element
 1   push 1
  ⊣  pop the minimum and 1 and push the first character of it

Funky, 18 bytes
x=>x::sort()[0][0]

Takes input as a list of strings.
Try it online!

Python 3, 33 bytes
lambda l:min(str(x)[0]for x in l)

Try it online!
@DJMcMayhem and @totallyhuman have a better solutions but mine assumes numerical input instead of string.

Pyth, 3 bytes
hhS

Input is list of string representations of numbers.
Try It Online
Explanation:
hhS
    # Q=input
  S # Sort Q
 h  # First Element of sorted list
h   # First element of string
    # Implicitly print result

Pyth, 9 7 bytes
hSmsh`d

Try it online!
Explanation
This basically return the smallest leading digit.
       Q    # Implicit input
  msh`d     # For each number in Q, convert to string, take the first character, convert to integer
hS          # Return the minimum

Pip, 5 bytes
Takes the list of input numbers as command-line arguments.
@@SSg

Try it online!
Alternately:
MN@Zg

Try it online!
Explanations
In both programs, g is the list of command-line args.
@@SSg

SS sorts using string comparison, thus putting the numbers with smallest first digits first, regardless of their magnitudes. Unary @ gives the first element of a list or scalar. We apply it twice to get the first digit of the first number after sorting.
    g  [24 72 491]
  SS   [24 491 72]
 @     24
@      2

Alternately:
MN@Zg

Z is zip; its unary version can be used to transpose a list. The first element of the transposed list is a list of the first digits of all the numbers. @ gets that list of digits; MN takes its minimum.
    g  [24 72 491]
   Z   [[2 7 4] [4 2 9]]
  @    [2 7 4]
MN     2


text:
Tri-interquine - Three programs that output each other in a loop
Related: Interquine
Program A outputs program B's code when run, and B outputs C's source, and C outputs A's source.
This time you can't exchange two characters and exchange again :)
Requirements:

Only one language across all programs
Standard loopholes restrictions apply
All programs are different. One program that outputs itself does not qualify. Two that output each other does not qualify, too.
All programs are non-empty, or at least 1 byte in length.
There's nothing to read because stdin is connected to /dev/null (You can abuse this rule if you can). Output goes to stdout.
Do not use functions that generate random results.

Additional:

Give explanations if possible

Score is length of the shortest one (can you generate a long program from a short one?). Please write the length of all programs and highlight the smallest number. Trailing newline does not count. Lowest score wins.

Related. (Same thing, different languages.)

Python 3, 50 bytes
s='s=%r;print(s%%(s,%i*2%%7))';print(s%(s,1*2%7))

Try it online!
The last expression goes from 1*2%7 to 2*2%7 to 4*2%7 then back to 1*2%7.

Looks like a universal solution to n-interquine. You only need to replace 7 with (2^n)-1.

In Python 2, the mapping 1-2/_ forms a 3-cycle with (1,-1,3), which saves a byte by not needing escaping for %.

@iBug or even shorter for large n, s='s=%r;print(s%%(s,-~%i%%3))';print(s%(s,-~1%3)) replacing 3 with n

RProgN 2, 12 8 bytes
1
«\2*7%

Explained
1   # Push the digit to the stack.

«\2*7%
«       # Define a function from here to the matching ». As there is no matching », define it from here to the end of the program, and continue running.
 \      # Flip the function under the constant number.
  2*    # Multiply by 2.
    7%  # Modulo 7.

Due to the convenient nature of how RProgN defaultly outputs, this leaves the number, which loops between 1, 2, and 4, on the first line, and the stringified version of the function on the second. Inspired by @LeakyNun's Python Answer
Try it online!

CJam, 17 bytes
{sZZe\6Ye\"_~"}_~

{s6Ze\ZYe\"_~"}_~

{sZ6e\ZYe\"_~"}_~

Try it online!
Probably not optimal, but this is a modification of my approach to the previous challenge.
The basic idea is the same, but we perform two swaps, one of which is always a no-op. The affected indices are 2, 3 and 6:
1:     {sZZe\6Ye\"_~"}_~
ZZe\             does nothing
       {sZZe\6Ye\"_~"}_~
6Ye\     \   /
          \ /
           X
          / \
         /   \
2:     {s6Ze\ZYe\"_~"}_~
6Ze\      \  /
           \/    doesn't really do anything
           /\
          /  \
       {s6Ze\ZYe\"_~"}_~
ZYe\     \/
         /\
3:     {sZ6e\ZYe\"_~"}_~
Z6e\      \  /
           \/
           /\
          /  \
       {sZZe\6Ye\"_~"}_~
ZYe\     \/      doesn't really do anything
         /\
1:     {sZZe\6Ye\"_~"}_~

CJam, 14 bytes
{_]3/W="_~"}_~

{_]3/W="_~"}{_]3/W="_~"}_~

{_]3/W="_~"}{_]3/W="_~"}{_]3/W="_~"}_~

Try it online!
The other programs are 26 and 38 bytes long, respectively.
Explanation
Yet another approach!
{       e# Again, the usual quine framework. In this case, there might
        e# be one or two additional copies of the block on the stack.
  _     e#   Duplicate the top copy of the block.
  ]     e#   Wrap all copies in an array.
  3/    e#   Split into chunks of 3. For the first two programs, this will
        e#   just wrap all of them in an array. For the third program, this
        e#   splits the fourth copy off from the first three.
  W=    e#   Select the last chunk. So `3/W=` does nothing for the first
        e#   two programs, but discards three copies once we get to four.
  "_~"  e#   Push the remainder of the program.
}_~

Jelly, 11 bytes
“Ḥ%7Øv;”Ṙv1

This generated the same program with 1 replaced by 2, which replaced 2 by 4, which generates the original program.
Try it online!

Python 3, 127, 127 and 127 bytes
a='a=%r;b=%r;c=%r;print(b%%(b,a,c))';b='b=%r;a=%r;c=%r;print(c%%(c,a,b))';c='c=%r;a=%r;b=%r;print(a%%(a,b,c))';print(b%(b,a,c))

prints
b='b=%r;a=%r;c=%r;print(c%%(c,a,b))';a='a=%r;b=%r;c=%r;print(b%%(b,a,c))';c='c=%r;a=%r;b=%r;print(a%%(a,b,c))';print(c%(c,a,b))

prints
c='c=%r;a=%r;b=%r;print(a%%(a,b,c))';a='a=%r;b=%r;c=%r;print(b%%(b,a,c))';b='b=%r;a=%r;c=%r;print(c%%(c,a,b))';print(a%(a,b,c))

This is based on my answer to the Interquine question, which is based on a normal Python quine.
And I know exactly what to do when we get a quad-interquine question ;)

CJam, 14 bytes
0{\)3%\"_~"}_~

1{\)3%\"_~"}_~

2{\)3%\"_~"}_~

Try it online!
Explanation
0{      e# Again, the standard CJam quine framework, but this time we have a zero
        e# at the bottom of the stack.
  \     e#   Bring the 0 to the top.
  )     e#   Increment.
  3%    e#   Mod 3 to loop from 2 back to 0.
  \     e#   Put the result underneath the block again.
  "_~"  e#   Push the remainder of the source.
}_~

Javascript (ES6), 63 55 bytes
eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=0)

eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=1)

eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=2)

o1.innerText = eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=0)
o2.innerText = eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=1)
o3.innerText = eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=2)

Alternative solution using Function.prototype.toString (cheaty, 30 bytes)
(f=n=>`(f=${f})(${++n%3})`)(1)

Lambda Calculus, 38 characters, 44 bytes
A simple solution based on the mother of all quines: the y-combinator:
(λx.(λy.y)(λz.z)xx)(λx.(λy.y)(λz.z)xx)

Using beta reductions we see that this indeed a tri-interquine:
(λx.(λy.y)(λz.z)xx)(λx.(λy.y)(λz.z)xx)
(λy.y)(λz.z)(λx.(λy.y)(λz.z)xx)(λx.(λy.y)(λz.z)xx)
(λz.z)(λx.(λy.y)(λz.z)xx)(λx.(λy.y)(λz.z)xx)
(λx.(λy.y)(λz.z)xx)(λx.(λy.y)(λz.z)xx)
etc.

Java 8, 118 bytes
v->{int i=0;String s="v->{int i=%d;String s=%c%s%2$c;return s.format(s,++i%%3,34,s);}";return s.format(s,++i%3,34,s);}

Only int i=0; is difference between the functions/outputs (it's either 0, 1 or 2).
Explanation:
Try it online.
v->{                       // Method with empty unused parameter and String return-type
  int i=0;                 //  Integer, starting at 0, 1 or 2 depending on the version
                           //  (this is the only variation between the functions/outputs)
  String s="v->{int i=%d;String s=%c%s%2$c;return s.format(s,++i%%3,34,s);}";
                           //  String containing the unformatted source code
  return s.format(s,++i%3,s);}
                           //  Quine to get the source code, which we return as result
                           //  ++i%3 is used to cycle 0→1→2→0

Additional explanation:
quine-part:

String s contains the unformatted source code
%s is used to put this String into itself with s.format(...)
%c, %2$c and 34 are used to format the double-quotes (")
%% is used to format the modulo-sign (%)
s.format(s,...,34,s) puts it all together

Difference of the outputs/functions:
Same approach as most other answers:

int i starts at either 0, 1 or 2
++i%3 transforms this to the next (0→1; 1→2; 2→0)

><>, 15 bytes
1'~r2*7%nd3*>o<

Try it online!
Uses the same general form as other ><> quines, but has an extra character in front that is cycled through 1, 2 and 4.