text:
A factorization game
Input
A single integer \$1 \leq x \leq 10^{15}\$.
Output
The maximum number of distinct positive integers that have the product \$x\$.
Examples
Input: 1099511627776. Output: 9.  One possible optimal list of factors is: (1, 2, 4, 8, 16, 32, 64, 128, 4096).
Input: 127381. Output 4. One possible optimal list of factors is: (1, 17, 59, 127).
Related to this old question.

Could you add a few more test cases? (Preferably of reasonable size.)

Given your comments on most answers: if you're looking for efficient code instead, this should definitely not be tagged as code-golf. You may consider either fastest-code or fastest-algorithm for an upcoming challenge. If you really wanted all answers to work in a limited time within the specified range, it should have been explicitly mentioned. (And I would have recommended a smaller range so that it does not conflict with code-golf entirely.)

@Arnauld No  I am careful to make it code-golf and no one is judged for that. It would just be cool if the code could run for the input ranges specfied.

Quoting xnor: If it's not mandatory, answers won't do it.

This challenge amounts to factoring integers into distinct elements of OEIS A050376 I believe.

@HaraldKorneliussen I do not think that works for n=225 (as far as I see, it is 925, but the output is 4 as 13515 works as well), but I might be (and likely am)  completely wrong.

For x=1, 2, ... I get f(x)=1, 2, 2, 2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 3, 3, 2, 3, 2, 3, 3, 3, 2, 4, 2, 3, 3, 3, 2, 4, 2, 3, 3, 3, 3, 4, 2, 3 which I do not find in OEIS. It is clear enough that records will appear for factorial numbers x. For example the smallest x such that f(x)=13 will be 13!. I guess f depends only on the exponents of the prime factorization. So to find f(13^4*19^7*29^2) we might simplify to f(2^7*3^4*5^2).

Wolfram Language (Mathematica), 52 bytes
Max[Length/@Cases[Subsets@Divisors@#,{a__}/;1a==#]]&

Try it online!
4-bytes saved thanks to @attinat
Here is also a 153 bytes version that calculates 1099511627776 and 10^15
Max[Length/@Table[s=RandomSample@Flatten[Table@@@FactorInteger[#]];Last@Select[Times@@@TakeList[s,#]&/@IntegerPartitions@Length@s,DuplicateFreeQ],5!]]+1&

Try it online!
The result for 10^15 is 12

{1, 2, 4, 5, 10, 16, 25, 40, 50, 100, 125, 250}

Crashes with 1099511627776

@Anush It doesn't crash. Just needs memory. You didn't say anything about memory limitations. This is code golf

Yes I realise. It just would be nice if you could actually run the code the input ranges specified in the question.

@Anush This is code-golf. Not nice answers. Please specify your criteria. An answer is either valid or not. I think the problem here is the question... Maybe you should change it to "most sufficient algorithm"

@Anush I made an edit in my answer and added one more version which is really fast and efficient in case you want to check it

52 bytes using Cases

and 49 bytes with Range instead of Divisors, though it's almost unusable

How does the 153 byte version work?

@Anush it is easy to make it work very fast for numbers like 1099511627776 which have only one prime factor (2^40). The case of 10^15 which has 2 prime factors is more difficult and that is why this algorithm works on a statistical sample of the permutations

@J42161217 How do you know the answer is optimal when you take a sample?

Wolfram Language (Mathematica), 38 bytes
(c=n=#;If[i∣n,n/=i,--c]~Do~{i,n};c)&

Try it online!
Greedy algorithm. Times out on TIO on larger inputs such as 1099511627776.

05AB1E, 9 bytes
Very inefficient. Will time out on TIO for numbers with a large amount of divisors.
ÑæʒPQ}€gZ

Try it online!
Explanation
Ñ          # push a list of divisors of the input
 æ         # push the powerset of that list
  ʒPQ}     # filter, keep only the lists whose product is the input
      €g   # get the length of each
        Z  # take the maximum

Your TIO code seems to output 3 instead of 9.

@Anush: It is a different number than your example (since that one times out due to to many factors). I probably should use a more distinct example.

€gZ is a bit more efficient than éθg for the same bytecount.

@Grimy: True. It won't do much difference as it's the filter that is the big bad guy here, but it doesn't hurt being a bit more efficient :)

Jelly, 9 bytes
ŒPP=³ƊƇẈṀ

Try it online!
-1 byte thanks to someone
-2 bytes thanks to ErikTheOutgolfer

While preparing a input for the OEIS superseeker, I created a 11-byte likely golfable Jelly program (that uses a different approach), and am unlikely to post a Jelly answer so I'll pretend I golfed a byte from your solution: ÆE×8‘½’:2S‘ (it works with the power of the OEIS "formula" section for A003056). Disclaimer: it might be wrong, but it works on the test cases.

It doesn't seem to terminate with 1099511627776

@someone doesn't work for 36 but thanks

@Anush yeah, it's really slow because i code-golfed it, not optimized for efficiency

I think you can replace L€ by Ẉ. I guess I have a advantage over all other Jelly programmers as I have no idea how to type all of these characters and copy and paste them from the "Atoms" and "Quicks" pages on the wiki like a very odd person and get to automatically read all of the documentation every time.

@someone I copy paste too, I just suck at reading :D thanks!

You can remove ÆD, it's not like there are more partitions that are going to be created like this, it's just going to take a lot more time (times out for $x\ge21$).

@EriktheOutgolfer oh true, thanks!

Perl 6, 38 bytes
{$!=$_;+grep {$!%%$_&&($!/=$_)},1..$_}

Try it online!
Takes the greedy approach to selecting divisors.

Doesn't terminate with 1099511627776

@Anush Well, it terminates eventually. Generally, the answer is valid if the program's algorithm would work with any input, if it were given as much memory and time as it wanted. Since this is [tag:code-golf], I optimised it for code length, not algorithmic complexity

Javascript (ES6), 39 bytes
f=(n,i=0)=>n%++i?n>i&&f(n,i):1+f(n/i,i)

There's probably a few bytes that can be saved here and there. Just uses the greedy algorithm for the factors.

Japt -h, 13 bytes
â à f_×¶UÃmÊn

Try it

Brachylog, 8 bytes
f;?⟨⊇×⟩l

Try it online!
(The naive approach, {~×≠l}ᶠ⌉, generates an infinite number of solutions with extra 1s before eliminating them with ≠, and thus fails to actually terminate. It's not a problem, though, since it's for the same byte count!)
Takes input through the input variable and output through the output variable. The header on TIO contains a copy of most of the code for the sake of showing you what the factor list is, but this works perfectly fine without it. Since ⊇ gives larger sublists first, this predicate essentially does the same thing as most other answers, but without explicitly generating and filtering the complete powerset of the factors, thanks to backtracking.
            The output
       l    is the length of
    ⊇       a sublist (the largest satisfying these constraints)
f           of the factors of
            the input
 ; ⟨  ⟩     which
     ×      with its elements multiplied together
  ?         is the input.

Gaia, 10 9 bytes
Π=
dz↑⁇(l

Try it online!
Follows the same "algorithm" as seen elsewhere -- filter the divisor powerset for the longest with product equal to the number and return its length.
	| helper function
Π=	| is prod(list)==n (implicit)?
	|
	| main function; implicitly takes n
dz	| divisor powerset (in decreasing order of size)
  ↑⁇	| filter by helper function
    (l	| take the first element and take the length (implicitly output)

Scala, 77 bytes
def f(n:Long)={var(m,c,i)=(n,1,2L);while(i<=m){if(m%i==0){m/=i;c+=1};i+=1};c}

Try it online!

Clam, 15 bytes
p}_`nq#:;qQ@s~Q

TIO link coming soon (when dennis pulls)
Basically a port of @Emigna's 05AB1E solution.
Explanation
                - Implicit Q = first input
p               - Print...
 }              - The last element of...
  _             - Sorted...
   `nq          - Lengths of... (map q => q.len)
           @s   - Items in powerset of
             ~Q - Proper divisors of Q
      #         - Where... (filter)
        ;q      - Product of subset
       :        - Equals...
          Q     - Q

C# (Visual C# Interactive Compiler), 54 bytes
int f(int n,int i=0)=>n%++i<1?1+f(n/i,i):n>i?f(n,i):0;

Uses the same approach as @vrugtehagel's and @JoKing's answers.
Try it online!

Assuming I implemented your logic correctly, a 53-byte solution (that I couldn't rid of the "return" keyword): Try it online!

@someone Thanks, but according to meta, functions have to be reusable. Also, I'm don't know if it is acceptable to have declarations outside of the function leave out a trailing semicolon, may make a meta post on that.

Ruby, 34 bytes
Obviously times out on that massive number, but will eventually time out if given enough time on another machine.
->n{(1..n).count{|e|n%e<1?n/=e:p}}

Try it online!

Husk, 10 bytes
▲mLfo=¹ΠṖḊ

Try it online! A port of Emigna's answer.


text:
Hostile Divisor Numbers
Some divisors of positive integers really hate each other and they don't like to share one or more common digits.
Those integers are called Hostile Divisor Numbers (HDN)
Examples
Number 9566 has 4 divisors: 1, 2, 4783 and 9566
(as you can see, no two of them share the same digit).
Thus, 9566 is a Hostile Divisor Number
Number 9567 is NOT HDN because its divisors (1, 3, 9, 1063, 3189, 9567) share some common digits.
Here are the first few HDN
1,2,3,4,5,6,7,8,9,23,27,29,37,43,47,49,53,59,67,73,79,83,86,87,89,97,223,227,229,233,239,257,263,267,269,277,283,293,307,337...

Task
The above list goes on and your task is to find the nth HDN
Input
A positive integer n from 1 to 4000
Output
The nth HDN
Test Cases
here are some 1-indexed test cases.
Please state which indexing system you use in your answer to avoid confusion.
input -> output
 1        1
 10       23
 101      853
 1012     26053
 3098     66686
 4000     85009

This is code-golf, so the lowest score in bytes wins.
EDIT
Good news!
I submitted my sequence to OEIS and...
Hostile Divisor Numbers are now OEIS A307636

I think square numbers would be the least hostile of numbers.

@JoeFrambach That I do not understand. There are perfect-square HDN. For a somewhat large example, 94699599289, the square of 307733, has divisors [1, 307733, 94699599289] which shows it is a HDN. Seems hostile to me.

@JeppeStigNielsen For a much smaller example, why not just 49?  Factors [1, 7, 49] qualifies as hostile...  Or, well, 4: [1, 2, 4]...

@DarrelHoffman Not to mention, the square number 1 with divisor list [1]. (Maybe large HDN are more interesting?)

I interpreted 49 as having divisors [7, 7], which not only share digits but are the same digits. 49 has factors [1, 7, 49]

this would be pretty tough in binary.

05AB1E, 12 10 bytes
µNNÑ€ÙSDÙQ

-2 bytes thanks to @Emigna.
1-indexed
Try it online or verify most test cases (last two test cases are omitted, since they time out).
Explanation:
µ           # Loop while the counter_variable is not equal to the (implicit) input yet:
 N          #  Push the 0-based index of the loop to the stack
  NÑ        #  Get the divisors of the 0-based index as well
            #   i.e. N=9566 → [1,2,4783,9566]
            #   i.e. N=9567 → [1,3,9,1063,3189,9567]
    €Ù      #  Uniquify the digits of each divisor
            #   → ["1","2","4783","956"]
            #   → ["1","3","9","1063","3189","9567"]
      S     #  Convert it to a flattened list of digits
            #   → ["1","2","4","7","8","3","9","5","6"]
            #   → ["1","3","9","1","0","6","3","3","1","8","9","9","5","6","7"]
       D    #  Duplicate this list
        Ù   #  Unique the digits
            #   → ["1","2","4","7","8","3","9","5","6"]
            #   → ["1","3","9","0","6","8","5","7"]
         Q  #  And check if it is still equal to the duplicated list
            #   → 1 (truthy)
            #   → 0 (falsey)
            #  And if it's truthy: implicitly increase the counter_variable by 1
            # (After the loop: implicitly output the top of the stack,
            #  which is the pushed index)

You beat me to it this time. I had µNNÑ€ÙSDÙQ for 10.

@Emigna Ah, I was just working on an alternative with µ, so you save me the trouble. ;)

this is poetically eloquent

Python 2, 104 bytes
n=input()
x=1
while n:
 x=i=x+1;d={0};c=1
 while i:m=set(`i`*(x%i<1));c*=d-m==d;d|=m;i-=1
 n-=c
print x

Try it online!
0-indexed.

Jelly, 10 bytes
ÆDQ€FQƑµ#Ṫ

Try it online!
-1 byte thanks to ErikTheOutgolfer
Takes input from STDIN, which is unusual for Jelly but normal where nfind is used.
ÆDQ€FQƑµ#Ṫ  Main link
         Ṫ  Get the last element of
        #   The first <input> elements that pass the filter:
ÆD          Get the divisors
  Q€        Uniquify each (implicitly converts a number to its digits)
    F       Flatten the list
     QƑ     Does that list equal itself when deduplicated?

2-indexed

is this 2-indexed? It's ok with me but please state it for others

It's whatever your test cases were, so 1

No it isn't. 101 returns 839. and 102 ->  853. It works fine but it is 2-indexed

@J42161217 wait what? i guess when i moved the nfind it changed the indexing lol

⁼Q$ is the same as QƑ.

@EriktheOutgolfer Thanks. I was looking for that since that's exactly what i wanted but I'm like blind or something lol

JavaScript (ES6), 78 bytes
1-indexed.
n=>eval("for(k=0;n;n-=!d)for(s=d=++k+'';k%--d||d*!s.match(`[${s+=d,d}]`););k")

Try it online!
Faster version, 79 bytes
n=>{for(k=0;n;n-=!d)for(s=d=++k+'';k%--d||d*!s.match(`[${s+=d,d}]`););return k}

Try it online!
How?
Given an integer \$k>0\$, we build the string \$s\$ as the concatenation of all divisors of \$k\$.
Because \$k\$ is always a divisor of itself, \$s\$ is initialized to \$k\$ (coerced to a string) and the first divisor that we try is \$d=k-1\$.
For each divisor \$d\$ of \$k\$, we test whether any digit of \$d\$ can be found in \$s\$ by turning \$d\$ into a character set in a regular expression.
Examples

\$s=\text{"}956647832\text{"}\$, \$d=1\$ → "956647832".match(/[1]/) is falsy
\$s=\text{"}9567\text{"}\$, \$d=3189\$ → "9567".match(/[3189]/) is truthy

Commented
This is the version without eval(), for readability
n => {                   // n = input
  for(                   // for() loop:
    k = 0;               //   start with k = 0
    n;                   //   go on until n = 0
    n -= !d              //   decrement n if the last iteration resulted in d = 0
  )                      //
    for(                 //   for() loop:
      s =                //     start by incrementing k and
      d = ++k + '';      //     setting both s and d to k, coerced to a string
      k % --d ||         //     decrement d; always go on if d is not a divisor of k
      d *                //     stop if d = 0
      !s.match(          //     stop if any digit of d can be found in s
        `[${s += d, d}]` //     append d to s
      );                 //
    );                   //   implicit end of inner for() loop
                         // implicit end of outer for() loop
  return k               // return k
}                        //

Python 2 (PyPy), 117 114 bytes
Uses 1-indexing
k=input();n=0;r=range
while k:n+=1;k-=1-any(set(`a`)&set(`b`)for a in r(1,n+1)for b in r(1,a)if n%a<1>n%b)
print n

Try it online!

Perl 6, 53 bytes
{(grep {/(.).*$0/R!~~[~] grep $_%%*,1..$_},^∞)[$_]}

Try it online!
1-indexed.
/(.).*$0/ matches any number with a repeated digit.
grep $_ %% *, 1 .. $_ returns a list of all divisors of the number $_ currently being checked for membership in the list.
[~] concatenates all of those digits together, and then R!~~ matches the string on the right against the pattern on the left.  (~~ is the usual match operator, !~~ is the negation of that operator, and R is a metaoperator that swaps the arguments of !~~.)

50 bytes

Ah wait, this checks for digits within the same divisor. The regex should be /(\d).*\s.*$0/, where you don't concatenate the divisors

Wolfram Language 103 bytes
Uses 1-indexing.
I'm surprised it required so much code.
(k=1;u=Union;n=2;l=Length;While[k<#,If[l[a=Join@@u/@IntegerDigits@Divisors@#]==l@u@a&@n,k++];n++];n-1)&

Can you please add a TIO link so that everybody can check your answer?

95 bytes: (n=t=1;While[t<=#,If[!Or@@IntersectingQ@@@Subsets[IntegerDigits@Divisors@n,{2}],t++];n++];n-1)& I am not planning to post an answer so I will leave this here

@J42161217, I've been trying to get the code to work in TIO without success.  There must be some trick I'm missing.

@J42161217, Your code seems to work but takes 3 times the runtime.  You can submit it as your own.  (Maybe I'll learn how to implement TIO from your example.)

Very fast indeed! here is your link  Try it online!

72 bytes using For instead of While, E!=##& to test for repeated digits

@J42161217, Thanks for the TIO code.  There are some tricks in it I would not have figured out on my own.

@attinat. I do not understand how E!=## works.  Kindly explain.

@DavidC E!=## is equivalent to Unequal[E,##]. This is True if all of its arguments are different and unequal to E; E is chosen here because it is a one-byte number which is not a digit. Try it online!

Python 3, 115 bytes
1-indexed
f=lambda n,x=1,s="",l="",d=1:n and(d>x+1and f(n-1,x+1)or{*s}&{*l}and f(n,x+1)or f(n,x,s+l,(1-x%d)*str(d),d+1))or~-x

Try it online!
This uses a lot of recursion; even with increased recursion limit, it can't do f(30). I think it might be golfable further, and I tried finding something to replace the (1-x%d) with, but couldn't come up with anything (-~-x%d has the wrong precedence). Any bytes that can be shaved off are greatly appreciated.
How it works
# n: HDNs to go
# x: Currently tested number
# s: String of currently seen divisor digits
# l: String of digits of last tried divisor if it was a divisor, empty string otherwise
# d: Currently tested divisor

f=lambda n,x=1,s="",l="",d=1:n and(                    # If there are still numbers to go
                             d>x+1and f(n-1,x+1)or     # If the divisors have been
                                                       #  exhausted, a HDN has been found
                             {*s}&{*l}and f(n,x+1)or   # If there were illegal digits in
                                                       #  the last divisor, x isn't a HDN
                             f(n,x,s+l,(1-x%d)*str(d),d+1)
                                                       # Else, try the next divisor, and
                                                       #  check this divisor's digits (if
                                                       #  if is one) in the next call
                             )or~-x                    # Else, return the answer

PowerShell, 112 bytes
for($a=$args[0];$a-gt0){$z=,0*10;1..++$n|?{!($n%$_)}|%{"$_"|% t*y|sort -u|%{$z[+"$_"]++}};$a-=!($z|?{$_-ge2})}$n

Try it online!
Takes 1-indexed input $args[0], stores that into $a, loops until that hits 0. Each iteration, we zero-out a ten-element array $z (used to hold our digit counts). Then we construct our list of divisors with 1..++$n|?{!($n%$_)}. For each divisor, we cast it to a string "$_", cast it toCharArray, and sort those digits with the -unique flag (because we don't care if a divisor itself has duplicate digits). We then increment the appropriate digit count in $z. Then, we decrement $a only if $z contains 0s and 1s (i.e., we've found an HDN). If we've finished our for loop, that means we found the appropriate number of HDNs, so we leave $n on the pipeline and output is implicit.

you could save some bytes: $a-=!($z-ge2) instead $a-=!($z|?{$_-ge2})

a bit golfed

Java 10, 149 139 138 126 125 120 119 bytes
n->{int r=0,i,d;for(;n>0;n-=d){var s="1";for(r+=d=i=1;i++<r;)if(r%i<1){d=s.matches(".*["+i+"].*")?0:d;s+=i;}}return r;}

-10 bytes by using .matches instead of .contains per digit, inspired by @Arnauld's JavaScript answer.
-5 bytes thanks to @ValueInk
-1 byte thanks to @ceilingcat
1-indexed
Try it online.
Explanation:
n->{                 // Method with integer as both parameter and return-type
  int r=0,           //  Result-integer, starting at 0
      i,             //  Index integer
      d;             //  Decrement integer
  for(;n>0;          //  Loop until the input `n` is 0:
      n-=d){         //    After every iteration: decrease `n` by the decrement integer `d`
    var s="1";       //   Create a String `s`, starting at "1"
    for(r+=d=i=1;    //   (Re)set the decrement and index integers to 1,
                     //   and increase the result by 1 as well
        i++<r;)      //   Inner loop `i` in the range [2, r]:
      if(r%i<1){     //    If `r` is divisible by `i`:
        d=s.matches(".*["+i+"].*")?
                     //     If string `s` contains any digits also found in integer `i`:
           0         //      Set the decrement integer `d` to 0
          :d;        //     Else: leave `d` unchanged
        s+=i;}}      //     And then append `i` to the String `s`
  return r;}         //  After the loops, return the result `r`

If you switch the i and s in your regex search, you don't need the extra string conversion, and the result is the same.

@ValueInk Thanks! :)

Wolfram Language (Mathematica), 74 bytes
Nest[1+#//.a_/;!Unequal@@Join@@Union/@IntegerDigits@Divisors@a:>a+1&,0,#]&

Try it online!

Brachylog (v2), 14 bytes
;A{ℕfdᵐc≠&}ᶠ⁽t

Try it online!
Function submission; input from the left, output to the right. (The TIO link contains a command-line argument to run a function as though it were a full program.)
Explanation
"Is this a hostile divisor number?" decision-problem code:
ℕfdᵐc≠
ℕ       number is ≥0 (required to match the question's definition of "nth solution")
 f      list of all factors of the number
   ᵐ    for each factor
  d       deduplicate its digits
    c   concatenate all the deduplications with each other
     ≠  the resulting number has no repeated digits

This turned out basically the same as @UnrelatedString's, although I wrote it independently.
"nth solution to a decision-problem" wrapper:
;A{…&}ᶠ⁽t
    &      output the successful input to
  {  }ᶠ    the first n solutions of the problem
       ⁽   taking <n, input> as a pair
;A         form a pair of user input and a "no constraints" value
        t  take the last solution (of those first n)

This is one of those cases where the wrapper required to produce the nth output is significantly longer than the code required to test each output in turn :-)
I came up with this wrapper independently of @UnrelatedString's. It's the same length and works on the same principle, but somehow ends up being written rather differently. It does have more potential scope for improvement, as we could add constraints on what values we were looking at for free via replacing the A with some constraint variable, but none of the possible constraint variables save bytes. (If there were a "nonnegative integer" constraint variable, you could replace the A with it, and then save a byte via making the the ℕ unnecessary.)

It’s 2-indexed?

Japt v2.0a0, 17 bytes
_=â ®sâÃ¬UµZ¶â}f1

Try it
Port of this Brachylog answer.
Credit: 4 bytes savings total thanks to Shaggy who also suggested there was a better solution leading to many more bytes :)

Original answer 28 byte approach:
Èâ¬rÈ«è"[{Y}]" ©X+Y}Xs)«U´Ãa

Try it
Port of this JavaScript answer.

28 bytes

Nice - I hadn't used the « shortcut before :) I figure if Shaggy is only improving on my score by a handful of bytes, I must be getting (somewhat) decent at this?

It can be done in 20 (maybe less) b7 employing a slightly different method.

Hah - I guess I spoke too soon :) yeah, some of the other golfing lang's have much shorter solutions.

@Shaggy - alright, currently down to 20 :)

Yup, that's the approach I was using, too. I got mine down to 17 eventually, if you want to try for it.

17 bytes

Perl 5 -p, 66 bytes
map{1while(join$",map{$\%$_==0&&$_}1..++$\)=~/(\d).* .*\1/}1..$_}{

Try it online!
1 indexed

Brachylog, 16 bytes
g{∧0<.fdᵐc≠∧}ᵘ⁾t

Try it online!
Very slow, and twice as long as it would be if this was a decision-problem. 1-indexed.
                    The output
               t    is the last
             ᵘ⁾     of a number of unique outputs,
g                   where that number is the input,
 {          }       from the predicate declaring that:
     .              the output
    <               which is greater than
   0                zero
  ∧                 (which is not the empty list)
      f             factorized
        ᵐ           with each factor individually
       d            having duplicate digits removed
          ≠         has no duplicate digits in
         c          the concatenation of the factors
           ∧        (which is not the output).

If you just read that explanation as a sentence though...

I try to write my explanations like plain English, which typically ends up just making them harder to read

Husk, 10 bytes
!fȯS=uṁdḊN

Try it online!
Same method as Jelly.
Husk, 19 bytes
!f(Λo¬Fnfo¬Eπ2mdḊ)N

Try it online!
The more manual cehcker.

Vyxal, 10 bytes
λKvUfÞu;ȯt

Try it Online!

Perl 6, 74 bytes
{(grep {!grep *>1,values [(+)] map *.comb.Set,grep $_%%*,1..$_},1..*)[$_]}

0-indexed. Only the first three cases are listed on TIO since it's too slow to test the rest.
Try it online!

57 bytes

Ruby, 110 97 92 84 bytes
-13 bytes by leveraging @Arnauld's JavaScript regex check.
-5 bytes for swapping out the times loop for a decrementer and a while.
-8 bytes by ditching combination for something more like the other answers.
->n{x=0;n-=1if(s='';1..x+=1).all?{|a|x%a>0||(e=/[#{a}]/!~s;s+=a.to_s;e)}while n>0;x}

Try it online!

Icon, 123 bytes
procedure f(n)
k:=m:=0
while m<n do{
k+:=1
r:=0
s:=""
every k%(i:=1 to k)=0&(upto(i,s)&r:=1)|s++:=i
r=0&m+:=1}
return k
end

Try it online!
1-indexed. Really slow for big inputs.

J, 87 59 bytes
-28 bytes thanks to FrownFrog
0{(+1,1(-:~.)@;@(~.@":&.>@,i.#~0=i.|])@+{.)@]^:(>{:)^:_&0 0

Try it online!
original
J, 87 bytes
[:{:({.@](>:@[,],([:(-:~.)[:-.&' '@,/~.@":"0)@((]#~0=|~)1+i.)@[#[)}.@])^:(#@]<1+[)^:_&1

Try it online!
Yikes.
This is atrociously long for J, but I'm not seeing great ways to bring it down.
explanation
It helps to introduce a couple helper verbs to see what's happening:
d=.(]#~0=|~)1+i.
h=. [: (-:~.) [: -.&' '@,/ ~.@":"0

d returns a list of all divisors of its argument
h tells you such a list is hostile.  It stringifies and deduplicates each number ~.@":"0, which returns a square matrix where shorter numbers are padded with spaces. -.&' '@,/ flattens the matrix and removes spaces, and finally (-:~.) tells you if that number has repeats or not.

With those two helpers our overall, ungolfed verb becomes:
[: {: ({.@] (>:@[ , ] , h@d@[ # [) }.@])^:(#@] < 1 + [)^:_&1

Here we maintain a list whose head is our "current candidate" (which starts at 1), and whose tail is all hostile numbers found so far.
We increment the head of the list >:@[ on each iteration, and only append the "current candidate" if it is hostile h@d@[ # [.  We keep doing this until our list length reaches 1 + n: ^:(#@] < 1 + [)^:_.
Finally, when we're done, we return the last number of this list [: {: which is the nth hostile number.

66

62

This is great, many thanks.  Will go over it and update tonight

59

source: Stack Exchange

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

sort: votes


text:
Dihedral group D4 composition with custom labels
The dihedral group \$D_4\$ is the symmetry group of the square, that is the moves that transform a square to itself via rotations and reflections. It consists of 8 elements: rotations by 0, 90, 180, and 270 degrees, and reflections across the horizontal, vertical, and two diagonal axes.

The images are all from this lovely page by Larry Riddle.
This challenge is about composing these moves: given two moves, output the move that's equivalent to doing them one after another. For instance, doing move 7 followed by move 4 is the same as doing move 5.

Note that switching the order to move 4 then move 7 produces move 6 instead.
The results are tabulated below; this is the Cayley table of the group \$D_4\$. So for example, inputs \$7, 4\$ should produce output \$5\$.
\begin{array}{*{20}{c}}
   {} & {\begin{array}{*{20}{c}}
   1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\
\end{array} }  \\
   {\begin{array}{*{20}{c}}
   1  \\
   2  \\
   3  \\
   4  \\
   5  \\
   6  \\
   7   \\
   8   \\
\end{array} } & {\boxed{\begin{array}{*{20}{c}}
   1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\
   2 & 3 & 4 & 1 & 8 & 7 & 5 & 6\\
   3 & 4 & 1 & 2 & 6 & 5 & 8 & 7\\
   4 & 1 & 2 & 3 & 7 & 8 & 6 & 5\\
   5 & 7 & 6 & 8 & 1 & 3 & 2 & 4\\
   6 & 8 & 5 & 7 & 3 & 1 & 4 & 2\\
   7 & 6 & 8 & 5 & 4 & 2 & 1 & 3\\
   8 & 5 & 7 & 6 & 2 & 4 & 3 & 1\\
\end{array} }}  \\
\end{array}
Challenge
Your goal is to implement this operation in as few bytes as possible, but in addition to the code, you also choose the labels that represent the moves 1 through 8. The labels must be 8 distinct numbers from 0 to 255, or the 8 one-byte characters their code points represent.
Your code will be given two of the labels from the 8 you've chosen, and must output the label that corresponds to their composition in the dihedral group \$D_4\$.
Example
Say you've chosen the characters C, O, M, P, U, T, E, R for moves 1 through 8 respectively. Then, your code should implement this table.
\begin{array}{*{20}{c}}
   {} & {\begin{array}{*{20}{c}}
   \, C  \, & \, O \, & M \, & P \, & U \, & \, T \, &  \, E \,  &  R \, \\
\end{array} }  \\
   {\begin{array}{*{20}{c}}
   C  \\
   O  \\
   M  \\
   P  \\
   U  \\
   T  \\
   E   \\
   R   \\
\end{array} } & {\boxed{\begin{array}{*{20}{c}}
   C & O & M & P & U & T & E & R \\
   O & M & P & C & R & E & U & T\\
   M & P & C & O & T & U & R & E\\
   P & C & O & M & E & R & T & U\\
   U & E & T & R & C & M & O & P\\
   T & R & U & E & M & C & P & O\\
   E & T & R & U & P & O & C & M\\
   R & U & E & T & O & P & M & C\\
\end{array} }}  \\
\end{array}
Given inputs E and P, you should output U. Your inputs will always be two of the letters C, O, M, P, U, T, E, R, and your output should always be one of these letters.
Text table for copying
1 2 3 4 5 6 7 8
2 3 4 1 8 7 5 6
3 4 1 2 6 5 8 7
4 1 2 3 7 8 6 5
5 7 6 8 1 3 2 4
6 8 5 7 3 1 4 2
7 6 8 5 4 2 1 3
8 5 7 6 2 4 3 1

Your choice of labels doesn't count against your code length. mind elaborating? As it stands, I can hardcode the matrix into my code and claim it doesn't count against my score.

@BenjaminUrquhart I was trying to say the length of your code is just the length of your code, and say, choosing multidigit labels doesn't cost anything extra. Looks like that line is more confusing that helpful, so I'll remove it.

Ruby, 18 bytes
->a,b{a+b*~0**a&7}

Ungolfed
->a,b{ (a+b*(-1)**a) % 8}
# for operator precedence reasons,
#-1 is represented as ~0 in the golfed version

Try it online!
Uses the following coding numbers 0 to 7
In order native to the code:
Native     Effect                    Codes per
Code                                 Question
0          rotate 0 anticlockwise    1C
1 /        flip in y=x               7E
2 /|       rotate 90 anticlockwise   2O
3 /|/      flip in x axis            5U
4 /|/|     rotate 180 anticlockwise  3M
5 /|/|/    flip in y=-x              8R
6 /|/|/|   rotate 270 anticlockwise  4P
7 /|/|/|/  flip in y axis            6T

In order per the question
Native     Effect                    Codes per
Code                                 Question
0          rotate 0 anticlockwise    1C
2 /|       rotate 90 anticlockwise   2O
4 /|/|     rotate 180 anticlockwise  3M
6 /|/|/|   rotate 270 anticlockwise  4P
3 /|/      flip in x axis            5U
7 /|/|/|/  flip in y axis            6T
1 /        flip in y=x               7E
5 /|/|/    flip in y=-x              8R

Explanation
/ represents a flip in the line y=x and | represents a flip in the y axis.
It is possible to generate any of the symmetries of the group D4 by alternately flipping in these two lines For example / followed by | gives /| which is a rotation of 90 degrees anticlockwise.
The total number of consecutive flips gives a very convenient representation for arithmetic manipulation.
If the first move is a rotation, we can simply add the number of flips:
Rotate 90 degrees   +  Rotate 180 degrees = Rotate 270 degrees
/|                     /|/|                 /|/|/|

Rotate 90 degress   +  Flip in y=x        = Flip in x axis
/|                    /                     /|/

If the first move is a reflection, we find we have some identical reflections / and | symbols next to each other. As reflection is self inverse we can cancel out these flips one by one. So we need to subtract one move from the other
Flip in x axis     +  Flip in y=x        = Rotate 90 degrees
/|/                   /                    /|/ / (cancels to) /|

Flip in x axis     +  Rotate 90 degrees  = Flip in y=x
/|/                   /|                   /|/ /| (cancels to ) /

You can replace the ~0 with 7 because of modular arithmetic.

Great method and explanation! The way the flips cancel makes it really clear why the labels either add or subtract.

Wolfram Language (Mathematica), 31 bytes
Using integers \$0, 5, 2, 7, 1, 3, 6, 4\$ as labels.
BitXor[##,2Mod[#,2]⌊#2/4⌋]&

Try it online!
Explanation:
The Dihedral group \$D_4\$ is isomorphic to the unitriangular matrix group of degree three over the field \$\mathbb{F}_2\$:
$$D_4 \cong U(3,2) := \left\{\begin{pmatrix} 1 & a & b \\ 0 & 1 & c \\ 0 & 0 & 1 \end{pmatrix} \mid a,b,c \in \mathbb{F}_2\right\}.$$
And we have
$$\begin{pmatrix} 1 & a_1 & b_1 \\ 0 & 1 & c_1 \\ 0 & 0 & 1 \end{pmatrix} \cdot \begin{pmatrix} 1 & a_2 & b_2 \\ 0 & 1 & c_2 \\ 0 & 0 & 1 \end{pmatrix} = \begin{pmatrix} 1 & a_1+a_2 & b_1+b_2+a_1c_2 \\ 0 & 1 & c_1+c_2 \\ 0 & 0 & 1 \end{pmatrix},$$
which can easily be written in bitwise operations.

A pretty derivation -- I had not known about this isomorphism.

Wolfram Language (Mathematica), 51 bytes
⌊#/4^IntegerDigits[#2,4,4]⌋~Mod~4~FromDigits~4&

Try it online!
Using labels {228, 57, 78, 147, 27, 177, 198, 108}.
These are {3210, 0321, 1032, 2103, 0123, 2301, 3012, 1230} in base 4. Fortunately, 256=4^4.

Lower-level implementation, also 51 bytes
Sum[4^i⌊#/4^⌊#2/4^i⌋~Mod~4⌋~Mod~4,{i,0,3}]&

Try it online!

Python 2, 22 bytes
A port of my Mathematica answer. Using integers \$0, 6, 1, 7, 2, 3, 5, 4\$ as labels.
lambda a,b:a^b^a/2&b/4

Try it online!

Python 2, 26 23 21 bytes
lambda x,y:y+x*7**y&7

Try it online! Port of my answer to Cayley Table of the Dihedral Group \$D_3\$. Edit: Saved 3 bytes thanks to @NieDzejkob. Saved 2 bytes thanks to @xnor for suggesting the and (rather than xnor) operator. Uses the following mapping:
 id | r1 | r2 | r3 | s0 | s1 | s2 | s3
----+----+----+----+----+----+----+----
 0  | 2  | 4  | 6  | 1  | 3  | 5  | 7

You can replace (-1) with 7 because of modular arithmetic for -3 bytes.

@NieDzejkob Thanks! Shame that alephalpha golfed his answer down from 28 to 22 bytes though...

Nice solution! You can cut the parens by changing the operator precedence: y+x*7**y&7

@xnor Thanks, I'm ahead of alephalpha again!

TI-BASIC, 165 bytes
Ans→L₁:{.12345678,.23417865,.34126587,.41238756,.58671342,.67583124,.75862413,.86754231→L₂:For(I,1,8:10fPart(.1int(L₂(I)₁₀^(seq(X,X,1,8:List▶matr(Ans,[B]:If I=1:[B]→[A]:If I-1:augment([A],[B]→[A]:End:[A](L₁(1),L₁(2

Input is a list of length two in Ans.
Output is the number at the (row, column) index in the table.
There could be a better compression method which would save bytes, but I'll have to look into that.
Examples:
{1,2
           {1 2}
prgmCDGF1B
               2
{7,4
           {7 4}
prgmCDGF1B
               5

Explanation:
(Newlines have been added for readability.)
Ans→L₁                              ;store the input list into L₁
{.123456 ... →L₂                    ;store the compressed matrix into L₂
                                    ; (line shortened for brevity)
For(I,1,8                           ;loop 8 times
10fPart(.1int(L₂(I)₁₀^(seq(X,X,1,8  ;decompress the "I"-th column of the matrix
List▶matr(Ans,[B]                   ;convert the resulting list into a matrix column and
                                    ; then store it into the "[B]" matrix variable
If I=1                              ;if the loop has just started...
[B]→[A]                             ;then store this column into "[A]", another matrix
                                    ; variable
If I-1                              ;otherwise...
augment([A],[B]→[A]                 ;append this column onto "[A]"
End
[A](L₁(1),L₁(2                      ;get the index and keep it in "Ans"
                                    ;implicit print of "Ans"

Here's a 155 byte solution, but it just hardcodes the matrix and gets the index.
I found it to be more boring, so I didn't make it my official submission:
Ans→L₁:[[1,2,3,4,5,6,7,8][2,3,4,1,8,7,5,6][3,4,1,2,6,5,8,7][4,1,2,3,7,8,6,5][5,7,6,8,1,3,2,4][6,8,5,7,3,1,4,2][7,6,8,5,4,2,1,3][8,5,7,6,2,4,3,1:Ans(L₁(1),L₁(2

Note:  TI-BASIC is a tokenized language.  Character count does not equal byte count.

Couldn't you shave like one byte by using 0-7 to 1-8

I could, but then I'd have to use two more to add one to each of the matrix's elements.  Good thought, however!

wrong, you can use any set of characters lol, so you don't havev to use two more

that may be true, but TI-BASIC's matrices are 1-indexed.  this submission relies on that to get the wanted value (if that's what you're implying.  correct me if i'm wrong)

ah, forgot about that

You can store the big list in list A, so the second line is {.123456 ... →A (saving 1 byte). Elsewhere, you can just refer to it as ʟA (which is also 2 bytes).

JavaScript (Node.js), 22 17 bytes
(x,y)=>y+x*7**y&7

Try it online! Port of my answer to Cayley Table of the Dihedral Group \$D_3\$ but golfed down using the suggestions on my Python answer. Uses the following mapping:
 id | r1 | r2 | r3 | s0 | s1 | s2 | s3
----+----+----+----+----+----+----+----
 0  | 2  | 4  | 6  | 1  | 3  | 5  | 7

Older versions of JavaScript can be supported in a number of ways for 22 bytes:
(x,y)=>(y&1?y-x:y+x)&7
(x,y)=>y-x*(y&1||-1)&7
(x,y)=>y+x*(y<<31|1)&7

Small improvement - save a byte by currying input x=>y=>(y&1?y-x:y+x)&7 then call your function using f(x)(y).

Jelly, 6 bytes
N⁹¡+%8

A dyadic Link accepting the first transform on the right and the second transform on the left which yields the composite transform.
Where the transforms are:
as in question:  1    2    3    4    5    6    7    8
transformation: id  90a  180  90c  hor  ver  +ve  -ve
  code's label:  0    2    4    6    1    5    7    3

Try it online! ...Or see the table mapped back onto the labels in the question.
(The arguments could be taken in the other order using the 6 byter, _+Ḃ?%8)
How?
Each label is the length of a sequence of alternating hor and +ve transforms which is equivalent to the transform (e.g. 180 is equivalent to hor, +ve, hor, +ve).
The composition A,B is equivalent to the concatenation of the two equivalent sequences, and allows simplification to subtraction or addition modulo eight...
Using the question's 7, 4 example we have +ve, 90c which is:
hor, +ve, hor, +ve, hor, +ve, hor  ,  hor, +ve, hor, +ve, hor, +ve
...but since hor, hor is id we have:
hor, +ve, hor, +ve, hor, +ve  ,  +ve, hor, +ve, hor, +ve
...and since +ve, +ve is id we have:
hor, +ve, hor, +ve, hor  ,  hor, +ve, hor, +ve
...and we can repeat these cancellations to:
hor
..equivalent to subtraction of the lengths (7-6=1).
When no cancellations are possible we are just adding the lengths (like 90a, 180 \$\rightarrow\$ 2+4=6 \$\rightarrow\$ 90c).
Lastly, note that a sequence of length eight is id so we can take the resulting sequence length modulo eight.
N⁹¡+%8 - Link: B, A
  ¡    - repeat (applied to chain's left argument, B)...
 ⁹     - ...times: chain's right argument, A
N      - ...action: negate  ...i.e. B if A is even, otherwise -B
   +   - add (A)
    %8 - modulo eight

It's also 1 byte shorter than this implementation using lexicographical permutation indexes:
œ?@ƒ4Œ¿

...a monadic Link accepting [first, second], with labels:
as in question:  1    2    3    4    5    6    7    8
transformation: id  90a  180  90c  hor  ver  +ve  -ve
  code's label:  1   10   17   19   24    8   15    6

Rust, 16 bytes
|a,b|a^b^a/2&b/4

Try it online!
Port of alephalpha's Python answer. But shorter.

Elm, 42 bytes 19 bytes
\a b->and 7<|b+a*7^b

Port of the Neil's Node.js version
Try it online
Previous version:
\a b->and 7<|if and 1 a>0 then a-b else a+b

Nice first answer! I don't know how to program in Elm, but is it possible to remove spaces?

@MilkyWay90 nope, it's one of the main differences of ML-based languages that
f x is a function call, just like what f(x) means in C-like languages. And you can't help it. But it can be really nice and less cluttered in many non-golf scenarios. Elm doesn't have bitwise operators (like &) so and x y is just a plain function call here.

I see, thanks for explaining!

@MilkyWay90 actually, I managed to cut off one space (and a byte) using pipe operator <| instead of parenthesis. Thanks for questioning that!

You're welcome! If you are interested in making a new solution, you could ask over on The Nineteenth Byte (our SE chatroom) for help. If you are creating a coding challenge, you could post it to The Sandbox (on meta) and post the link to the question on The Nineteenth Byte every day.

Python, 82 71 bytes
0-7
-11 bytes thanks to ASCII-only
lambda a,b:int("27pwpxvfcobhkyqu1wrun3nu1fih0x8svriq0",36)>>3*(a*8+b)&7

TIO

80, python 2, 76, python 2

also 76, and -2 because f= can be removed since it isn't recursive

wait rip, it doesn't work

here we go, 71

seems like you could do better with int.from_bytes and non-UTF encoding, but... not sure how to do that on TIO

@ASCII-only updated. Thanks! (Python is not my main language)

Perl 6, 19 bytes
{($^x*7**$^y+$y)%8}

Port of Neil's Python solution.
Try it online!

C# (Visual C# Interactive Compiler), 17 bytes
a=>b=>a^b^a/2&b/4

Port of alpehalpha's Python answer.
Try it online!

Scala, 161 bytes
Choosing COMPUTER as labels.
val m="0123456712307645230154763012675446570213574620316574310274651320"
val s="COMPUTER"
val l=s.zipWithIndex.toMap
def f(a: Char, b: Char)=s(m(l(a)*8+l(b))-48)

Try it online!

this is code golf :| you're supposed to make it as short as possible

88

Yeah, I challenged myself to go with scala and real labels, not just native 0-7. Try to beat it.

133

118 :P

No bad, how about compressing the matrix somehow?

finally got it... 140 for now (EDIT: or not :/)

148 (EDIT: wait it's not even symmetrical)

115

Good job! I got 131 with matrix compressed into 32B ASCII string

123?

Haha ".zipWithIndex.toMap" is way too long, any chance to shorten indexOf?

:/ even def l(c:Int)=s.indexOf(c) is shorter

Scala, 70 bytes
Choosing 0-7 native integers as labels.
Compressed the matrix into 32 byte ASCII string, each pair of numbers n0, n1 into 1 character c = n0 + 8*n1 + 49. Starting from 49 to that we don't have \ in the encoded string.
(a:Int,b:Int)=>"9K]oB4h]K9Vh4BoVenAJne3<_X<AX_J3"(a*4+b/2)-49>>b%2*3&7

Try it online!

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


text:
Make me a minimum magic sum
Keeping this challenge short.
You are given 4 numbers: p1, p2, p3 and p4.
The magic sum of the numbers are defined as follows:
magic_sum = |p1 - p2| + |p2 - p3| + |p3 - p4| + |p4 - p1|

You are only allowed to change one of the above integer values (p1, p2, p3 or p4). You need to change the value such that the magic sum of the values attains its minimum value.
For example:
p1, p2, p3, p4 = 17, -6, 15, 33. The value of the magic sum is 78 in this case.
You can change the -6 here to 16, and the value of the magic sum will become 36, which is the minimum attainable value.
Do keep in mind that numbers can be positive or negative integers.
This is code-golf, so least bytes in code wins. Brownie points for using a Practical Language over a Recreational language. May the 4th be with you.
To reiterate:
Sample 1
Input 1
17 -6 15 33

Output 1
36

Explanation 1

The -6 can be replaced with 16 and that gives us the minimum attainable
  magic sum possible.

Sample 2
Input 2
10 10 10 10

Output 2
0 or 2

either is acceptable
Explanation 2

The minimum attainable magic sum is 0 since the minimum sum of 4 positive
  integers is 0. If a number has to be changed, then one of the 10's can be
  changed to a 9 and thus yielding the output 2.

Sample 3
Input 3
1 2 3 4

Output 3
4

Explanation 3

The input by itself yields 6 as its magic sum. Changing the 4 to 1 and the minimum magic sum is attained, which is 4.

+1, but could do with more examples.

A fully worked example and a couple more test cases and it's a +1 from me.

@Shaggy done. where is my +1? :P

@KoishoreRoy Wouldn't test case 3 be 6 without the change?

@wizzwizz4 |1 - 2 | + |2 - 3| + |3 - 4| + |4 - 1| = 1+1+1+3 =6. You are correct. Made the edit.

Also, should the explanations be in blockquotes and not pres?

@wizzwizz4 kinda new to formatting. can you help make the necessary changes?

Jelly, 6 bytes
ṢŒœIṂḤ

Try it online!
A port of my Python answer.
     (input)        [17, -6, 15, 33]
Ṣ    sort           [-6, 15, 17, 33]
Œœ   odd-even elts  [[-6, 17], [15, 33]]
I    increments     [23, 18]
M    minimum        18
Ḥ    double         36

Python 2, 44 bytes
a,b,c,d=sorted(input())
print min(c-a,d-b)*2

Try it online!
Sorts the input as a,b,c,d, in ascending order, takes the smaller of c-a and d-b, and doubles it. Why does this work?
First, note that when we change an element to maximize to total cyclic sum of distances, it's optimal (or tied for optimal) to change it to equal a neighbor, such as 17, -6, 15, 33 -> 17, 17, 15, 33. That's because its new total distance to its left and right cyclic neighbors is at least the distance between those neighbors, so making these be equal is the best we can do.
Now, deleting one of two adjacent copies of a number gives the same cyclic sum of distances. In the example, this is 17, 15, 33, giving distances 2 + 18 + 16. So instead of replacing one of the four numbers, it's equivalent to just delete it leaving three numbers, and using the sum of their cyclic distances.
Notice that with 3 numbers, the largest distance is the sum of the two smaller ones. This is because if we sort the numbers to have a ≤ b ≤ c, then |a - c| = |a - b| + |b - c|. In other words, we travel between the largest and smallest number twice, using the medium number as a pit stop one of the times. So, the sum of the three distances is just twice the distance between the minimum and maximum, so (c-a)*2.
So, the question is which number we delete to get the smallest distance between the minimum and maximum of the three numbers that remains. Clearly we delete either the smallest or the largest of the numbers. Calling them a, b, c, d in sorted order, deleting a leaves d - b, and deleting d leaves c - a, and the final result is double whichever is smaller.

help me out with a test case here. what if the magic sum is already 0, which the lowest attainable number. in that case, should the answer be 0? or the next lowest number possible.
Incase the input is [10,10,10,10], the magic sum is 0. the second lowest possible is 2.
Let me know what you think.

What I hear you say, is that you can just ignore the order of the four numbers given (your first step is to sort them). But what if we had asked for five numbers p1 through p5, and still only allowed changing one number? The four-number case seems too easy (only after seeing your answer).

@KoishoreRoy I like your solution of allowing either one.

@JeppeStigNielsen Yes, the fact that order doesn't matter is special to 4 numbers, and it happens because after deleting one to make three numbers, all pairs of numbers are cyclically adjacent. With five numbers this wouldn't work (you can surely find an example), and the challenge would be very different.

Wish I could upvote twice.  Beautiful observation, well explained.

R, 66 33 bytes
function(x)2*min(diff(sort(x),2))

Try it online!
Much shorter with xnor's algorithm (go read their explanation and upvote their post!).
Old version:
R, 66 bytes
function(x,m=matrix(x,3,4))min(colSums(abs(diff(rbind(m,m[1,])))))

Try it online!
Takes input as a vector of 4 integers.
This works because the minimum can be attained by setting one of the numbers as equal to one of its neighbours (it is not the only way of attaining the minimum). To see why this is true, find a configuration which achieves the minimum; say we have changed \$p_2\$. Any value of \$p_2\$ such that \$p_1\leq p_2\leq p_3\$ will give the same sum (\$|p_1-p_2|+|p_2-p_3|\$ remains constant), so we can choose \$p_2=p_1\$.
There are 4 ways of choosing which number we change; for each of these, we only have to compute the sum of 3 absolute differences.
The code sets the values in a \$3\times4\$ matrix, where each column represents a subset of size 3 of the 4 numbers. Copy the first row to a 4th row with rbind and compute the absolute differences, then take the minimum of the column sums.

Jelly, 11 10 bytes
I;SASƲ$-ƤṂ

Try it online!
A monadic link that takes a list if integers as input. Should work for arbitrary list size. Works on the basis that the minimum sum can be obtained by testing removing each number from the list, calculating the magic sum and taking the minimum.

Japt -Q, 11 bytes
ñÍó ®r- ÑÃn

Uses @xnor's algorithm, which saved me 4 bytes.
Saved 5 bytes thanks to @Shaggy
Try it

seems to be working fine, but would you explain why this works?

@KoishoreRoy Added an explanation

29 bytes (I think)

@Shaggy when I updated my answer, I accidentally replaced sum with map, making some golfs invalid, but others are good

Nicely (further) golfed :) You can save 1 more byte by replacing ÃÃ with a newline.

Although, any Japt solution over ~5 bytes without a single whitespace character is always an accomplishment!

ñn<space> can be replaced with ñÍ and r!- is the same as rn.

Jelly, 8 bytes
ṁ-Ƥ⁸IA§Ṃ

A monadic Link accepting a list of integers* which yields an integer
* can be any number so long as there are more than 1; using same style magic formula summing the neighbours differences wrapping around.
Try it online!
How?
ṁ-Ƥ⁸IA§Ṃ - Link: list of integers, X       e.g. [17,-6,15,33]
 -Ƥ      - for overlapping "outfixes" of length length(X)-1:
         -                                      [[-6,15,33],[17,15,33],[17,-6,33],[17,-6,15]]
ṁ  ⁸     -   mould like X                       [[-6,15,33,-6],[17,15,33,17],[17,-6,33,17],[17,-6,15,17]]
    I    - incremental differences              [[21,18,-39],[-2,18,-16],[-23,39,-16],[-23,21,2]]
     A   - absolute (vectorises)                [[21,18,39],[2,18,16],[23,39,16],[23,21,2]]
      §  - sums                                 [78,36,78,46]
       Ṃ - minimum                              36

J, 24 20 18 17 bytes
alternative version using xnor algorithm:
2*[:<./2 2-/@$\:~

how
Two times 2 * the min of [:<./ the 2nd row subtracted from the first row [:-/ of the 2x2 matrix formed by shaping 2 2$ the input sorted down \:~
Try it online!
original answer: J, 24 bytes
[:<./1(1#.2|@-/\],{.)\.]

Try it online!
Using Nick Kennedy's idea.

1(...)\.] apply the verb in parens to all outfixes of length 1 (an outfix of length n is a list with n contiguous elements removed, so this produces every possible list with 1 elm removed)
(1 #. 2 |@-/\ ] , {.) this calculates the magic sum by appending the first elm to the input ] , {. and applying the abs difference |@-/ to infixes of length 2 2 ...\, and summing the result 1 #..
[:<./ returns the min

05AB1E, 11 7 bytes
Port of @xnor's Jelly answer.
-4 bytes thanks to @Emigna and @Grimy.
{2ô`αß·

Try it online.
7 bytes alternative which only works in the legacy version of 05AB1E (would require a € before the ¥ in the new version):
{2ôø¥W·

Try it online.
Explanation:
{        # Sort the (implicit) input-list
         #  i.e. [17,-6,15,33] → [-6,15,17,33]
 2ô      # Split this list into parts of size 2
         #  → [[-6,15],[17,33]]
   `     # Push both separated to the stack
    α    # And take their absolute differences
         #  → [23,18]
     ß   # Pop and push the minimum
         #  → 18
      ·  # Double it (and output implicitly as result)
         #  → 36

{        # Sort the (implicit) input-list
         #  i.e. [17,-6,15,33] → [-6,15,17,33]
 2ô      # Split this list into parts of size 2
         #  → [[-6,15],[17,33]]
   ø     # Zip/transpose, swapping rows/columns
         #  → [[-6,17],[15,33]]
    ¥    # Get the deltas/forward differences of the inner lists
         #  → [[23],[18]]
     W   # Get the flattened minimum (without popping)
         #  → 18
      ·  # Double it (and output implicitly as result)
         #  → 36

7 bytes in legacy: {2ôø¥W· or 8 with € in the rewrite.

7 bytes in non-legacy: {2ô`αW·

@Emigna Smart, thanks!

@Grimy Thanks as well!

C++ (gcc)
full program: 138 bytes
#include<iostream>
#include<regex>
using namespace std;int main(){int a[4];for(int&b:a)cin>>b;sort(a,a+4);cout<<min(a[2]-*a,a[3]-a[1])*2;}

Try it online!
core function: 84 bytes
#include<regex>
int m(int*a){std::sort(a,a+4);return std::min(a[2]-*a,a[3]-a[1])*2;}

Try it online!
Also using the algorithm xnor explained in his Python 2 post.

Java 8, 235 bytes
A port of @xnor's Python answer and algorithm
import java.util.*;interface M{static void main(String[]A){Scanner I=new Scanner(System.in);int a[]={0,0,0,0};for(int i=0;i<4;a[i++]=I.nextInt());java.util.Arrays.sort(a);System.out.print(2*(a[2]-a[0]>a[3]-a[1]?a[3]-a[1]:a[2]-a[0]));}}

Try it online!
Java 10, unproven, 222 bytes
With Java 10, I should be able to replace left side of Scanner declaration with var, although I could not compile it online and thus I can only add it as a trivia. Sorry.
interface M{static void main(String[]A){var I=new java.util.Scanner(System.in);int a[]={0,0,0,0};for(int i=3;i<4;a[i++]=I.nextInt());java.util.Arrays.sort(a);System.out.print(2*(a[2]-a[0]>a[3]-a[1]?a[3]-a[1]:a[2]-a[0]));}}

AFAIK you can just have a function as your submission, like how the other answers have done.  No need to include the surrounding class, interface, etc.

JavaScript (ES6), 51 bytes
Using xnor's much more clever method:
a=>([a,b,c,d]=a.sort((a,b)=>a-b),b+c<a+d?c-a:d-b)*2

Try it online!

Original answer, 96 bytes
Takes input as an array of 4 integers. Probably Definitely not the shortest approach.
a=>a.map(m=x=>a.map((y,i)=>a[m=a.map(v=>s+=Math.abs(p-(p=v)),a[i]=x,p=a[3],s=0)|m<s?m:s,i]=y))|m

Try it online!

Wolfram Language (Mathematica), 29 bytes
A port of @xnor's algorithm
2{#3-#}~Min~{#4-#2}&@@Sort@#&

Try it online!

Charcoal, 20 bytes
Ｉ⌊ＥＥθΦθ⁻κμΣＥι↔⁻λ§ι⊕μ

Try it online! Link is to verbose version of code. Turns out I'm using @NickKennedy's idea. Explanation:
   Ｅθ                   Map over input array
     Φθ                 Filter over input array where
       ⁻κμ              Outer and inner indices differ
  Ｅ                     Map over resulting list of lists
           Ｅι           Map over remaining values in list
                §ι⊕μ    Get the next value in the list
             ↔⁻λ        Compute the absolute difference with the current value
          Σ             Take the sum of absolute differences
 ⌊                      Take the minimum sum
Ｉ                       Cast to string and implicitly print


text:
Determine if a grid contains another grid
Challenge
Create a function takes in two 2-dimensional arrays of characters (or strings if the programming language does not have characters as a datatype) as inputs: a and b. If your language does not support these inputs, you may use any other standard one-byte variable.
Your task is to determine if b contains a. If this is so, return true. Otherwise, return false.
Sample Test Cases
a:

123
456
789

b:

123
456
789

should return true.
a:

code
golf

b:

thisis
code!!
golf!!
ohyeah

should return true.
a:

abcd
efgh
ijkl

b:

abcdef
ghijkl
mnopqr

should return false.
a:

abc
def

b:

1abc2
3def4
5ghi6

should return true
a:

ab
cd

b:

#ab##
##cd#

should return false
This is code-golf so least bytes wins.

Hi and welcome to codegolf! I edited your test cases to (hopefully) make them a bit more clear. Note that we have a sandbox for working on challenges before posting them to main. Good luck!

Also, may I take the first array as an array of strings and the second as a string separated by newlines, even though my language(C#) has a character type built in?

@Neil Test cases 2 and 3 are not square.

Could you add a truthy test case where a isn't on b's left edge and a falsey test case where each line of a appears in consecutive lines of b but with their left edges staggered?

@EmbodimentofIgnorance yes

Please add test cases: ['abc','def'], ['1abc2abc7','3abc4xxx8','5ghi6'] -> false and ['abc','def'],['1abc2abc7','3abc4def8','5ghi6'] -> true

What's the minimum grid size? If it's 1x1, I recommend test cases involving a 1xY and Yx1 grid.

Brachylog (v2), 4 bytes
s\s\

Try it online!
Most easily run as a full program, as usual for a decision-problem, with a specified as a command-line argument, b on standard input. The question asks for a function, and the program also works as a function, with b on the left, a on the right, and output via producing an exception if and only if the decision is  false.
Explanation
s\s\
s     a substring of rows of {the left input}
 \…\  assert rectangular; swap row and column operations
  s   a substring of <s>rows</s> columns of {the above matrix}
      {implicit} assert that the result can be {the right input}

The "assert rectangular" is, obviously, pointless, as the question guarantees that already. The rest of the program does the grid-finding for us by identifying a substring of the rows and of the columns, i.e. a submatrix.
Meta-discussion
We've had a very similar question before; I'd expect most answers to one question to be modifiable into answers to the other. I think this is the neater version of it, though.

Shortest answer here, so I'll accept it.

Python 2, 67 bytes
f=lambda a,b,r=4:b*r and f(a,b[1:],r)|f(a,zip(*b)[::-1],r-1)or a==b

Try it online!
Takes input as lists of tuples of characters.
Tries all sub-grids of b and checks if a is among them. The sub-grids are generated by recursively branching on either removing the first row of b or rotating it 90 degrees. After exactly four rotations, checks if the trimmed down b is equal to a.

@mazzy I think the input grids are supposed to be rectangles.

J, 21 15 8 7 bytes
1#.,@E.

Try it online!
-7 bytes thanks to Bolce Bussiere
original answer
J, 21 15 bytes
<@[e.&,$@[<;.3]

Try it online!
-6 bytes thanks to FrownyFrog
how

<@[ boxed left arg
$@[<;.3] all rectangles in the right arg with the same shape as the left arg
now pass those as the left and right arg to...
is the left arg an elm of the right arg, after flattening both e.&,

I think this can be <@[e.&,$@[<;.3]

Ah ofc, ty!  If you want a challenge, have a look at this monstrosity I defiled the site with

-7 Bytes: +/@:,@E.. E. is pretty much made for this challenge.

tyvm @BolceBussiere.  i will update this tonight.

Charcoal, 26 bytes
⌈⭆η⭆ι⁼θＥ✂ηκ⁺Ｌθκ¹✂νμ⁺Ｌ§θ⁰μ¹

Try it online! Link is to verbose version of code. Heavily based on my answer to Count the contiguous submatrices, the only difference being that instead of taking the sum of the matches I take the maximum, and because of the implicit string conversion due to the use of ⭆ the result is already a string which saves a byte.

Wolfram Language (Mathematica), 46 37 bytes
Partition[#2,Dimensions@#,1]~FreeQ~#&

Try it online!
Returns True if b does not contain a, and False if it does.

05AB1E, 10 bytes
øŒεøŒI.å}à

Takes b as first input, a as second. Both inputs as character-matrices.
Port of @Mr.Xcoder's 05AB1E answer for this related challenge, so make sure to upvote him!
Try it online or verify all test cases.
Explanation:
øŒ          # Get the sublists of every column of the (implicit) input `b`
  ε         # Map each list of sublists to:
   øŒ       #  Get the sublists of every column again
            #  (now we have all sub-matrices of `b`)
     I.å    #  Check if the second input `a` is in this list of sub-matrices
        }à  # After the map: check if any are truthy by taking the maximum
            # (which is output implicitly as result)

JavaScript (ES6), 131 112 105 bytes
105 bytes:
f=(m,n)=>m.some((x,i)=>i<=m.length-n.length&x.some((c,j)=>n.every((l,z)=>(m[i+z]+'').indexOf(l,j)==2*j)))

Try it online!
Changes:

m[i] into x and n[z] into l: Totally forgot that these variables were already instanciated
&& into &: Both sides of the operator are already booleans so a bitwise operator will work

112 bytes:
f=(m,n)=>m.some((x,i)=>i<=m.length-n.length&&m[i].some((c,j)=>n.every((l,z)=>(m[i+z]+'').indexOf(n[z],j)==2*j)))

Try it online!
Changes:

map((c,j)=>{...}).some(s=>s) into some((c,j)=>{...}): Redundancy
m[i+z].join() into m[i+z]+'': A shorter way to convert the array into a string
indexOf(n[z].join(),j) into indexOf(n[z],j): The indexOf method already converts n[z] into a string

131 bytes:
f=(m,n)=>m.some((x,i)=>i<=m.length-n.length&&m[i].map((c,j)=>n.every((l,z)=>m[i+z].join().indexOf(n[z].join(),j)==2*j)).some(s=>s))

Try it online!
Readable:
function f (m, n) {
  return m.some((x, i) => {
    return i <= m.length - n.length
      && m[i].map((c, j) => {
        return n.every((l, z) => {
          return m[i + z].join().indexOf(n[z].join(), j) == 2 * j
        })
      })
        .some(s => s)
  })
}

Instead of compairing individual values, I checked if the lines from grid N were included in the lines of grid M, and if so, at which indexes. If all of the lines are included starting from the same index then the grid N is contained in the grid M.

APL (Dyalog Unicode), 3 bytes
1∊⍷

Try it online!
It's like this question was made for APL!
Explanation
  ⍷   ⍝ 'find', returns a matrix with '1' in all positions where the first matrix is contained in the second
1∊    ⍝ checks if '1' is a member of this matrix

Python 2, 106 118 113 bytes
lambda a,b,L=len:any(sum(A==B[j:j+L(A)]for A,B in zip(a,b[i:]))==L(a)for i in range(L(b))for j in range(L(b[0])))

Try it online!

@Neil: Fixed now.

PowerShell, 71 102 85 98 bytes
thanks @Jo King; test cases added.
param($a,$b)!!($a|%{$p=[regex]::Escape($_)
$b|sls $p -a -ca|% m*}|group index|?{"$a"-ceq$_.Group})

Try it online!
Less golfed:
param($a,$b)

$matches = $a|%{
    $pattern = [regex]::Escape($_)
    $b|Select-String $pattern -AllMatches -CaseSensitive|% Matches
}

$relevantGroupsByMatchPosition = $matches|group index|?{
    "$a"-ceq$_.Group  # the '$_.Group' contains matches in source order
                      # -ceq is case sensitivity equation operator
                      # -ceq performs an implicit conversion to the left operand type
}

!!($relevantGroupsByMatchPosition)  # true if the variable is not $null

Javascript, 150 bytes
f=(a,b)=>{_='length';for(r=i=0;i<=b[_]-a[_];i++)for(j=0;j<=b[0][_]-a[0][_];j++){u=0;a.map((l,y)=>l.map((c,x)=>u=u||b[i+y][j+x]!=c));r=r||!u;}return r}

Try it online

JavaScript (V8), 81 bytes
(m,n)=>m[s='some']((a,i)=>a[s]((b,j)=>!n[s]((c,k)=>c[s]((d,l)=>m[i+k][j+l]!=d))))

Try it online!

Octave/Matlab, 47 45 44 40/38 bytes

-2 Default output to ans
-1 Trace of inner product is the sum of the squares of the elements. Therefore use trace(a*a') instead of sum(a(:).^2)
-4 Use find instead of any(any(...)) since any non-zero output of find is considered as a logical truth, and Matlab/Octave is 1-indexed.
-2 but only in Matlab, since the second argument to xcorr2 does not need to be made numeric and is implicitly converted to whatever is the first argument's type.

Octave
@(a,b)find(xcorr2(a*1,b*1)==trace(a*a'))

Try it online!
Matlab
@(a,b)find(xcorr2(a*1,b)==trace(a*a'))

This works by computing the 2D cross-correlation function of matrices a and b (in a numeric from), and then checking whether an entry corresponding to a perfect overlap exists.


text:
Rock, Paper, Scissors, Lizard, Spock Tournament
Giving a challenge involving a Star Trek reference just after May the 4th may be frowned upon, but here goes.
You, Luke, Anakin, Palpatine, Yoda and Han Solo are involved in an insane tournament of Rock, Paper, Scissor, Lizard, Spock.
The catch here is that you are only allowed to use a fixed order of moves. If your order is "R", Then you have to use Rock, until you lose or win against everyone. If your order is RRV, then you have to use 2 Rocks followed by a Spock and keep repeating until you have won or lost.
Luke, Anakin, Palpatine, Yoda and Han Solo have submitted their respective orderings and you being an expert hacker got your hands on each of their orderings!
With this knowledge, you are to design your ordering for the tournament. Since everyone wants to win, you want to create an ordering such that you win the tournament by beating everyone.
But this may not be possible under all circumstances.
Incase there is a possible winning order, print that out. If there is no possible way for you to win, print out -1 (or 0 or False or "impossible")
Input: a list of 5 orders
Output: a single order or -1
Sample Input 1
R
P
S
L
V

Sample Output 1
-1

Explanation 1

No matter what you play in your first move, there will be at least one
  person who beats you, hence it is not possible for you to win.

Sample Input 2
RPS
RPP
R
SRR
L

Sample Output 2
RPSP

Explanation 2

Once you play Rock in your first move, you end up beating "L" and "SRR" and
  tie against the rest. This is because Lizard and Scissors lose to Rock.
  When you play Paper next, you will beat "R" and tie against the remaining
  2. This is because Rock loses to Paper.
  When you play Scissors next, you will win against "RPP" as Scissor beats
  Paper.
Finally, you will beat "RPS" with your Paper as Paper beats Rock.

Here are a list of notations (you may use any 5 literals, but please specify in your answer):
R : Rock
P : Paper
S : Scissor
L : Lizard
V : Spock

Here is a list of all possible outcomes:
winner('S', 'P') -> 'S'
winner('S', 'R') -> 'R'
winner('S', 'V') -> 'V'
winner('S', 'L') -> 'S'
winner('S', 'S') -> Tie
winner('P', 'R') -> 'P'
winner('P', 'V') -> 'P'
winner('P', 'L') -> 'L'
winner('P', 'S') -> 'S'
winner('P', 'P') -> Tie
winner('R', 'V') -> 'V'
winner('R', 'L') -> 'R'
winner('R', 'S') -> 'R'
winner('R', 'P') -> 'P'
winner('R', 'R') -> Tie
winner('L', 'R') -> 'R'
winner('L', 'V') -> 'L'
winner('L', 'S') -> 'S'
winner('L', 'P') -> 'L'
winner('L', 'L') -> Tie
winner('V', 'R') -> 'V'
winner('V', 'L') -> 'L'
winner('V', 'S') -> 'V'
winner('V', 'P') -> 'P'
winner('V', 'V') -> Tie

This is code-golf, so fewest bytes win.
P.S: Let me know if you need more test cases.

Please change "Star Trek" to "Star Wars" in your intro ;)

This is a pretty difficult problem. Well, or I am bad at this kind of programming.

@CrabMan This is a bit of a difficult problem to golf. especially in practical languages.

I think prolog would be very suitable for this problem

Does the solution need to be the shortest one?

No. It can be whatever. The solution just needs to win against all 5 inputs.
I just put in the shortest one in the example because it seemed easier after writing such a long question.

Is it acceptable to output several winning strategies, or do we have to output only one?

several works, but there are in theory infinite winning strategies, so keep that in mind

Not really a problem, but the title somewhat suggests that this is a king-of-the-hill challenge. (At least that's what I thought at first glance.)

Can I have different labels for the input and the output?

Related, and also a KOTH (cc: @Arnauld)

Jelly, 29 bytes
_%5ḟ0ḢḂ¬
ṁ€ZLḤƊçþ`Ạ€Tị;‘%5Ɗ$€

A monadic Link that accepts a list of lists of integers (each of which is an opponent's strategy) which yields a list of lists of integers - each of which is a winning strategy (so an empty list if none are possible).
(Just add Ḣ to only yield a single strategy list or 0 if impossible.)
Try it online! (the footer formats to always show the lists)
Rock  Paper  Scissors  Spock  Lizard
0     1      2         3      4

Or try a letter mapped version (where strategies are taken and shown on their own lines using RPSVL notation).
How?
The numbers are chosen such that any which are an odd number greater than another modulo five win (i.e. they are numbered going around the edge of an inscribed pentagon of the throws).
The code plays each strategy off against every strategy (including themselves) for twice as many throws as the longest strategy so as to ensure finding any losers keeping those which are not defeated. The resulting list of strategies will contain a single strategy if there is an outright winner; no strategies if there was no winner; or multiple strategies if there are drawing players. After this a winning set of moves is appended to each of these strategies.
_%5ḟ0ḢḂ¬ - Link 1, does B survive?: list A, list B (A & B of equal lengths)
                              e.g. RPSR vs RPVL ->  [0,1,2,0], [0,1,3,4]
_        - subtract (vectorises)                    [0,0,-1,-4]
 %5      - modulo five (vectorises)                 [0,0,4,1]   ...if all zeros:
   ḟ0    - filter discard zeros (ties)              [4,1]                       []
     Ḣ   - head (zero if an empty list)             4                           0
      Ḃ  - modulo two                               0                           0
       ¬ - logical NOT                              1                           1

ṁ€ZLḤƊçþ`Ạ€Tị;‘%5Ɗ$€ - Main Link: list of lists of integers
ṁ€                   - mould each list like:
     Ɗ               -   last three links as a monad
  Z                  -     transpose
   L                 -     length
    Ḥ                -     double  (i.e. 2 * throws in longest strategy)
        `            - use left as both arguments of:
       þ             -   table using:
      ç              -     last Link (1) as a dyad
         Ạ€          - all for each (1 if survives against all others, else 0)
           T         - truthy indices
            ị        - index into the input strategies
                  $€ - last two links as a monad for each:
             ;       -   concatenate with:
                 Ɗ   -     last three links as a monad:
              ‘      -       increment (vectorises)
               %5    -       modulo five (vectorises)

I am completely new to Jelly, but it seems that you can gain a byte by replacing ZLḤ by LÄ.

@RobinRyder That won't work - it's only working with the example data because there are enough opponents and few enough throws - this is an example of one that wouldn't work. We need to analyse twice as many throws as the longest opponent strategy. (Your code is actually equivalent to this)

...actually due to the action of Ɗ in your code it's not even doing what you may have thought - it's moulding each like it's own length then getting the cumulative sums of those results, so will also compare incorrect values too. Try this for example - it takes in [[1,2,3,4,5],[6,7],[8]], moulds each by the length of the entire list (3) to get [[1,2,3],[6,7,6],[8,8,8]] then performs accumulation to get [[1,1+2,1+2+3],[6,6+7,6+7+8],[8,8+8,8+8+8]] = [[1,3,6],[6,13,19],[8,16,24]].

Ah yes, I knew I was misunderstanding something!

JavaScript (ES6),  122 115  112 bytes
Takes input as an array of strings of digits, with:

\$0\$ = Scissors (S)
\$1\$ = Paper (P)
\$2\$ = Rock (R)
\$3\$ = Lizard (L)
\$4\$ = Spock (V)

Returns either a string in the same format or \$false\$ if there's no solution.
f=(a,m='',x=0,o,b=a.filter(a=>(y=a[m.length%a.length])-x?o|=y-x&1^x<y:1))=>b+b?x<4&&f(a,m,x+1)||!o&&f(b,m+x):m+x

Try it online!
How?
This is a breadth-first search: we first try all moves at a given step to see if we can win the game. If we can't win right now, we try to add another move to each non-losing move.
The move identifiers were chosen in such a way that a move \$A\$ wins against a move \$B\$ if and only if \$(B-A)\bmod 5\$ is odd.
With \$A\$ on the left and \$B\$ on the top:
$$
\begin{array}{cc|ccccc}
& & \text{(S)} & \text{(P)} & \text{(R)} & \text{(L)} & \text{(V)}\\
& & 0 & 1 & 2 & 3 & 4\\
\hline
\text{(S) }&0 & - & \color{green}1 & \color{red}2 & \color{green}3 & \color{red}4\\
\text{(P) }&1 & \color{red}4 & - & \color{green}1 & \color{red}2 & \color{green}3\\
\text{(R) }&2 & \color{green}3 & \color{red}4 & - & \color{green}1 & \color{red}2\\
\text{(L) }&3 & \color{red}2 & \color{green}3 & \color{red}4 & - & \color{green}1\\
\text{(V) }&4 & \color{green}1 & \color{red}2 & \color{green}3 & \color{red}4 & -
\end{array}
$$
From there, we can deduce another way of testing if \$A\$ wins against \$B\$ for \$A\neq B\$:
((A - B) and 1) xor (B < A)

where and and xor are bitwise operators.
Commented
f = (                        // f is a recursive function taking:
  a,                         //   a[] = input
  m = '',                    //   m   = string representing the list of moves
  x = 0,                     //   x   = next move to try (0 to 4)
  o,                         //   o   = flag set if we lose, initially undefined
  b =                        //   b[] = array of remaining opponents after the move x
    a.filter(s =>            //     for each entry s in a[]:
    ( y =                    //       define y as ...
      s[m.length % s.length] //         ... the next move of the current opponent
    ) - x                    //       subtract x from y
    ?                        //       if the difference is not equal to 0:
      o |=                   //         update o using the formula described above:
        y - x & 1 ^ x < y    //           set it to 1 if we lose; opponents are removed
                             //           while o = 0, and kept as soon as o = 1
    :                        //       else (this is a draw):
      1                      //         keep this opponent, but leave o unchanged
  )                          //     end of filter()
) =>                         //
  b + b ?                    // if b[] is not empty:
    x < 4 &&                 //   if x is less than 4:
      f(a, m, x + 1)         //     do a recursive call with x + 1 (going breadth-first)
    ||                       //   if this fails:
      !o &&                  //     if o is not set:
        f(b, m + x)          //       keep this move and do a recursive call with b[]
  :                          // else (success):
    m + x                    //   return m + x

your code fails for the test case: test(['P','P','S','P','P'])
The answer should be "SR" or "SV".

@KoishoreRoy Now fixed.

This is actually a brilliant approach. I didn't even think of considering it as a graph. I was using dictionaries and reverse look-ups in my ungolfed original approach (without Spock or Lizards i.e.)

R, 213 190 bytes
-23 bytes thanks to Giuseppe.
function(L){m=matrix(rep(0:2,1:3),5,5)
m[1,4]=m[2,5]=1
v=combn(rep(1:5,n),n<-sum(lengths(L)))
v[,which(apply(v,2,function(z)all(sapply(L,function(x,y,r=m[cbind(x,y)])r[r>0][1]<2,z)))>0)[1]]}

Try it online!
If a solution exists, it outputs one. If there is no solution, it outputs a row of NA. If this output format is not acceptable, I can change it at a cost of a few bytes.
Moves are coded as 1=R, 2=S, 3=P, 4=L, 5=V, so that the matrix of outcomes is
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    2    2    1    1
[2,]    1    0    2    2    1
[3,]    1    1    0    2    2
[4,]    2    1    1    0    2
[5,]    2    2    1    1    0

(0=no winner; 1=player 1 wins; 2=player 2 wins)
An upper bound on the length of the solution if it exists is n=sum(lengths(L)) where L is the list of opponents' moves. The code creates all possible strategies of length n (stored in matrix v), tries all of them, and displays all winning strategies.
Note that this value of n makes the code very slow on TIO, so I have hardcoded in the TIO n=4 which is enough for the test cases.
For the first test case, the output is
     1 4 2 4

corresponding to the solution RLSL.
For the second test case, the output is
 NA NA NA NA

meaning that there is no solution.
Explanation of a previous version (will update when I can):
function(L){
  m = matrix(rep(0:2,1:3),5,5);
  m[1,4]=m[2,5]=1                      # create matrix of outcomes
  v=as.matrix(expand.grid(replicate(   # all possible strategies of length n
    n<-sum(lengths(L))                 # where n is the upper bound on solution length
    ,1:5,F)))
  v[which(
    apply(v,1,                         # for each strategy
          function(z)                  # check whether it wins
            all(                       # against all opponents
              sapply(L,function(x,y){  # function to simulate one game
                r=m[cbind(x,y)];       # vector of pair-wise outcomes
                r[r>0][1]<2            # keep the first non-draw outcome, and verify that it is a win
              }
              ,z)))
    >0),]                              # keep only winning strategies
}

The which is necessary to get rid of NAs which occur when the two players draw forever.
I am not convinced this is the most efficient strategy. Even if it is, I am sure that the code for m could be golfed quite a bit.

why is lengths() aliased to always return 4?

Anyway, while I'm waiting for your response, I golfed it down to 197, mostly by focusing on v...

@Giuseppe I have aliased lengths to force n=4 on TIO, because otherwise it takes too long to go over all $5^n$ ($n=11$) strategies.

ah, makes sense, should have known. 187 bytes

@Giuseppe Thanks, impressive golfing! I added 3 bytes to make the output more readable (otherwise we end up with the same solution(s) printed many times).

Might be able to get away with using a Map or mapply rather than nested apply() and sapply() calls you we do v=combn(...,,F) to return a list, but the logic is a bit more complex and I don't have time to golf that right now.

Emacs Lisp, 730 bytes
(require 'cl-extra)
(require 'seq)
(defun N (g) (length (nth 1 g)))
(defun M (g) (mapcar (lambda (o) (nth (% (N g) (length o)) o)) (car g)))
(defun B (x y) (or (eq (% (1+ x) 5) y) (eq (% (+ y 2) 5) x)))
(defun S (g) (seq-filter (lambda (m) (not (seq-some (lambda (v) (B v m)) (M g)))) '(0 1 2 3 4)))
(defun F (g) (cond ((null (car g)) (reverse (nth 1 g))) ((null (S g)) nil) ((>= (nth 3 g) (seq-reduce (lambda (x y) (calc-eval "lcm($,$$)" 'raw x y)) (mapcar 'length (car g)) 1)) nil) (t (cl-some (lambda (m) (F   (let ((r (seq-filter 'identity (mapcar* (lambda (v o) (and (not (B m v)) o)) (M g) (car g))))) (list r (cons m (nth 1 g)) (1+ (N g)) (if (eq (car g) r) (1+ (nth 3 g)) 0))))) (S g)))))
(defun Z (s) (F (list s () 0 0)))

I didn't find an online interpreter of Emacs Lisp :( If you have Emacs installed, you can copy code into a .el file, copy some testing lines below
;; 0 = rock, 1 = lizard; 2 = spock;
;; 3 = scissors; 4 = paper
(print (Z '((0) (1) (2) (3) (4))))
; output: nil
(print (Z '((0) (4) (3) (1))))
; output: nil
(print (Z '((0 4 3) (0 4 4) (0) (3 0 0) (1))))
; output: (0 4 3 0 1)
(print (Z '((4) (4) (3) (4) (4))))
; output: (3 0)
(print (Z '((4 3 2 1 0) (2 1 0 4 3))))
; output: (1)
(print (Z '((2) (2) (3) (0) (2) (3) (0) (0))))
; output: (2 1)
(print (Z '((2) (2 0) (3) (0) (2 1) (3) (0) (0))))
; output: nil

and run it $ emacs --script filename.el.
How it works
My program does depth first search with sometimes figuring out that it's impossible to win and terminating the branch it's on.
You can see full explanation in the unshortened version of the code:
(require 'seq)
(require 'cl-extra)

;; This program does depth first search with sometimes figuring out
;; that it's impossible to win and terminating the branch it's on.
;;

;; A move is a number from 0 to 4.
;; https://d3qdvvkm3r2z1i.cloudfront.net/media/catalog/product/cache/1/image/1800x/6b9ffbf72458f4fd2d3cb995d92e8889/r/o/rockpaperscissorslizardspock_newthumb.png
;; this is a nice visualization of what beats what.
;; Rock = 0, lizard = 1, spock = 2, scissors = 3, paper = 4.

(defun beats (x y) "Calculates whether move x beats move y"
  (or (eq (% (1+ x) 5) y)
      (eq (% (+ y 2) 5) x)))

;; A gamestate is a list with the following elements:
(defun get-orders (gamestate)
  "A list of orders of players who haven't lost yet. Each order is a list of moves.
For example, ((2) (2 0) (3) (0) (2 1) (3) (0) (0)) is a valid orders list.
This function gets orders from the gamestate."
  (car gamestate))

;; At index 1 of the gamestate lies a list of all moves we have made so far in reverse order
;; (because lists are singly linked, we can't push back quickly)
(defun get-num-moves-done (gamestate)
  "Returns the number of moves the player has done so far"
  (length (nth 1 gamestate)))

(defun get-rounds-since-last-elim (gamestate)
  "The last element of a gamestate is the number of rounds passed since an opponent
was eliminated. We use this to determine if it's possible to win from current
gamestate (more about it later)."
  (nth 2 gamestate))

;; next go some utility functions
;; you can skip their descriptions, they are not very interesting
;; I suggest you skip until the next ;; comment

(defun get-next-move (order num-rounds-done)
  "Arguments: an order (e.g. (1 0 1)); how many rounds have passed total.
Returns the move this opponent will make next"
  (nth (% num-rounds-done (length order)) order))

(defun moves-of-opponents-this-round (gamestate)
  "Returns a list of moves the opponents will make next"
  (mapcar (lambda (order) (get-next-move order (get-num-moves-done gamestate)))
          (get-orders gamestate)))

(defun is-non-losing (move opponents-moves)
  "Calculates if we lose right away by playing move against opponents-moves"
  (not (seq-some (lambda (opponent-move) (beats opponent-move move))
                 opponents-moves)))

(defun non-losing-moves (gamestate)
  "Returns a list of moves which we can play without losing right away."
  (seq-filter
   (lambda (move) (is-non-losing move (moves-of-opponents-this-round gamestate)))
   '(0 1 2 3 4)))

(defun advance-gamestate (gamestate move)
  "If this move in this gamestate is non-losing, returns the next game state"
  (let ((new-orders (seq-filter
                    'identity (mapcar* (lambda (opp-move order)
                                         (and (not (beats move opp-move)) order))
                                       (moves-of-opponents-this-round gamestate)
                                       (get-orders gamestate)))))
  (list new-orders
        (cons move (nth 1 gamestate))
        (if (eq (get-orders gamestate) new-orders) (1+ (get-rounds-since-last-elim gamestate)) 0))))

;; How do we prevent our depth first search from continuing without halting?
;; Suppose 3 players (except us) are still in the game and they have orders of lengths a, b, c
;; In this situation, if least_common_multiple(a, b, c) rounds pass without an elimination
;; we will be in the same situation (because they will be playing the same moves they played
;; lcm(a, b, c) rounds ago)
;; Therefore, if it's possible to win from this gamestate,
;; then it's possible to win from that earlier game state,
;; hence we can stop exploring this branch

(defun get-cycle-len (gamestate)
  "Returns a number of rounds which is enough for the situation to become the same
if the game goes this long without an elimination."
  (seq-reduce (lambda (x y) (calc-eval "lcm($,$$)" 'raw x y))
              (mapcar 'length (get-orders gamestate)) 1))

(defun unwinnable-cycle (gamestate)
  "Using the aforementioned information, returns t if we are in such a
suboptimal course of play."
  (>= (get-rounds-since-last-elim gamestate) (get-cycle-len gamestate)))

(defun find-good-moves (gamestate)
  "Given gamestate, if it's possible to win
returns a list of moves, containing all moves already done + additional moves which lead to win.
Otherwise returns nil"
  (cond ((null (get-orders gamestate)) ; if no opponents left, we won, return the list of moves
         (reverse (nth 1 gamestate)))
        ((null (non-losing-moves gamestate)) ; if no non-losing moves available, this gamestate
         nil) ; doesn't lead to a win, return nil
        ((unwinnable-cycle gamestate) ; either it's impossible to win, or
         nil) ; it's possible to win from an earlier position, return nil
        (t (cl-some (lambda (move) ; otherwise return the first non-losing move which leads
                      (find-good-moves (advance-gamestate gamestate move))) ; to a non-nil result
                    (non-losing-moves gamestate)))))

(defun make-initial-gamestate (orders)
  "Given an orders list, create initial gamestate"
  (list orders () 0))

https://tio.run/##S81NTC7WzcksLvgPBAA
can you insert your code here and try running it?

@KoishoreRoy I had tried tio.run and I couldn't figure out why it doesn't run. It says "Trailing garbage following expression" and I have no idea what that is and 5 minutes of googling didn't help me to fix it.


text:
Convert Numbers To Emoji Math
In Emoji Math, a user created module for the video game Keep Talking And Nobody Explodes, numbers are written as strings of emoticons, where each emoticon represents a base 10 digit.
Below is the conversion table between digits and emoticons.
Digit | Emoticon
  0   |    :)
  1   |    =(
  2   |    (:
  3   |    )=
  4   |    :(
  5   |    ):
  6   |    =)
  7   |    (=
  8   |    :|
  9   |    |:

Given a number, output it in Emoji Math encoding. You may assume the absence of non-numeric characters.
This is code-golf, so the shortest answer in bytes wins.

Are we allowed to take the input number as a string?

... Or an array of digits.

Should we output one of the ten Emoticons with a digit input, or should we output any concatted Emoticons based on an input integer. Or to be more concrete, is [0,9] the only valid range of inputs, or can the input also be >= 10?

@Tau sounds like the intention was to accept a string - "You may assume the absence of non-numeric characters."; we should be asking "May we take the input as an integer?"

Can we assume that the input will be positive? If not, how should we represent zero?

Since it's encoding, should we support leading 0s?

What should an input of 0 output?

I've voted to close as unclear until the points above are addressed. But don't hesitate to ping me once it's fixed so that I can retract my vote or vote to reopen.

@mbomb007 from the looks of it, 0 should output :) since they're in the same row in the table

@Tau I was asking because of this. The OP needs to answer.

Japt, 29 24 bytes
-5 bytes thanks to @Shaggy
s":)=((:)=:():=)(=:||:"ò

Takes input as a string
Try it online!

Welcome to Japt :) m@ can be replaced with £ to save a byte. But this can be done in 24 bytes using base conversion.

Oops, seems this isn't actually your first Japt solution! You do still qualify for this bounty, though, if you want to try for it.

05AB1E, 26 bytes
"|:(=):)=:)"2ôºJ2ô`Šr)sSèJ

Try it online!

This is not working for numbers with multiple digits.

@izlin: Indeed. I hadn't realized that was part of the challenge. Fixed now though. Thanks :)

C (gcc), 62 58 bytes
-4 bytes thanks to ceilingcat
f(n){n&&write(1,":)=((:)=:():=)(=:||:"+n%10*2,2,f(n/10));}

Try it online!

Python 2, 65 62 bytes
lambda n:''.join(':=():)=(:|)(:=(:)=|:'[int(c)::10]for c in n)

Try it online!

TI-BASIC, 79 bytes
Ans→Str1:" :For(I,1,length(Str1:Ans+sub(":)=((:)=:():=)(=:||:",1+2expr(sub(Str1,I,1)),2:End:sub(Ans,2,length(Ans)-1

Input is a string of digits in Ans.
Output is the Emoji Math-encoded number.
Examples:
"134
134
prgmCDGF1C
:)(:)=
"2213894
2213894
prgmCDGF1C
(:(:=()=:||::(

Explanation:
Ans→Str1                                                 ;store the input in Ans
"                                                        ;leave " " in Ans
For(I,1,length(Str1                                      ;loop over each character in the
                                                         ; input string
Ans+sub(":)=((:)=:():=)(=:||:",1+2expr(sub(Str1,I,1)),2  ;convert the current character
                                                         ; to a number and use it as the
                                                         ; index into the encoding string
                                                         ; then append the encoded digit
End
sub(Ans,2,length(Ans)-1                                  ;remove the prepended space and
                                                         ; store the result in Ans
                                                         ;implicit print of Ans

Alternatively, here's a 94 byte solution that takes a number as input instead of a string:
int(10fPart(Ans₁₀^(seq(⁻X-1,X,0,log(Ans→L₁:" :For(I,dim(L₁),1,-1:Ans+sub(":)=((:)=:():=)(=:||:",1+2L₁(I),2:End:sub(Ans,2,length(Ans)-1

Examples:
134
             134
prgmCDGF1C
:)(:)=
2213894
         2213894
prgmCDGF1C
(:(:=()=:||::(

Explanation:
int(10fPart(Ans₁₀^(seq(⁻X-1,X,0,log(Ans→L₁     ;generate a list of the input's digits
                                             ; reversed and store it in L₁
"                                            ;leave " " in Ans
For(I,dim(L₁),1,-1                            ;loop over L₁ backwards
Ans+sub(":)=((:)=:():=)(=:||:",1+2L₁(I),2     ;use the value of the I-th element in L₁ as
                                              ; the index into the encoding string then
                                              ; append the encoded digit
End
sub(Ans,2,length(Ans)-1                       ;remove the prepended space and store the
                                              ; result in Ans
                                              ;implicit print of Ans

Notes:

TI-BASIC is a tokenized language.  Character count does not equal byte count.
| is the two-byte token 0xBBD8 that can only be accessed using this assembly program.

Perl 5 -p, 42 bytes
s/./substr":)=((:)=:():=)(=:||:",$&*2,2/ge

Try it online!

[R],  59    48  bytes
different approach:
 substr(":)=((:)=:():=)(=:||:",n<-2*scan()+1,n+1)

thanks to @aaron for directing me on again :)
original:
 el(strsplit(":)x=(x(:x)=x:(x):x=)x(=x:|x|:","x",T))[scan()]

beats
 c(":)","=(","(:",")=",":(","):","=)","(=",":|","|:")[scan()]

by 1 byte

The different approach is a bit off, you need to add one to the doubled scanned number 2*scan()+1, with a bit of rearrangement though you can still keep it as 48 bytes. Try it online!

JS ES6, 77 66 bytes
Down to 66 thanks to suggestions from @Charlie Harding and @asgallant
Had to finally make an account on codegolf since this was such a fun little challenge!
The most minimal form of the original answer, when expecting string-only input:
n=>[...n].map(c=>":)=((:)=:():=)(=:||:".match(/../g)[c]).join("")

Secondly, my original answer which uses a longer regex and first coerces the input into a string, This works with both number type input and a string of digits input.

I first coerce the input into a string, which is then destructured into an array using es6 spread. Then I map it through a matcher cb that grabs the correct emoticon from an array made with the regex /.{1,2}/g. Finally the resulting array of emoticons is joined back to a string.

n=>[...(""+n)].map(c=>":)=((:)=:():=)(=:||:".match(/.{1,2}/g)[c]).join("")

JS array stuff is fun. I'm sure there's still some room for optimization, this re-matches the regex on every loop of the map.
Crappily tested with the following:

let emoticonize = n=>[...(""+n)].map(c=>":)=((:)=:():=)(=:||:".match(/../g)[c]).join("")

let test = arr =>
console.log(arr.map(x => ({ask:x, ans: emoticonize(x)})))

test([1,40,3697, 2330])
test(["1","40","3697", "2330"])

Why are there spaces around the => arrow in the map? That could save two bytes, couldn't it?

And I believe the regex /../g does the same job too, saving another four bytes

Finally, if the input is necessarily a string then [...(""+n)] can be simplified to [...n], saving a further five bytes

map and regex search is actually costing you characters here; replace and substr work just as well, with fewer characters: 58 bytes: n=>n.replace(/./g,c=>':)=((:)=:():=)(=:||:'.substr(2*c,2)), assuming input as a string of digits.

man, that's a neat way to use replace @asgallant! Seems I gotta get to know my string functions as well :)

@Roope, feel free to update your answer with the suggestions, and continue to improve upon it if you find a new way to save bytes.

Java 8, 80 bytes
n->n.forEach(i->System.out.print(":)=((:)=:():=)(=:||:".split("(?<=\\G..)")[i]))

Try it online.
Explanation:
n->                           // Method with IntStream parameter and no return-type
  n.forEach(i->               //  For each digit `i` in the input:
    System.out.print(         //   Print without newline:
      ":)=((:)=:():=)(=:||:"  //    Push this String
        .split("(?<=\\G..)")  //    Split into parts of size 2
          [i]))               //    And print the `i`'th part

Haskell, 64 56Laikoni bytes
((words":) =( (: )= :( ): =) (= :| |: "!!).read.pure=<<)

Try it online
Ungolfed
Apply the function words to our space-separated string of symbols ":) =( (: )= :( ): =) (= :| |: " to get a list, and get the nth element (!!) for every n in our input string, combining the results. n.b. (=<<) is equivalent to concatMap in this case, mapping a string to a list of strings and concatenating the results.  read . pure converts a character to an int, by lifting a character to a string, then reading to an int.
f x = ((words ":) =( (: )= :( ): =) (= :| |: " !!) . read . pure) =<< x

56 bytes: Try it online!

PowerShell, 64 60 59 bytes
-1 byte thanks to mazzy
-join($args|% t*y|%{':)=((:)=:():=)(=:||:'|% S*g(2*"$_")2})

Try it online!
Takes a string, splits it in toCharArray, and then indexes into the emoji key by casting the character to its numerical value, doubles it because each emoji is two wide, and then takes the substring from that spot plus one higher. Finally it joins this all up into one string and pushes it to output.

59 bytes

@mazzy Yeah, I spaced on how to cast to int without getting the ASCII value, thanks.

Jelly, 21 bytes
“=:)|(”“ØḟƝoṣẈ’ṃs2ị@D

Try it online!

Icon, 78 75 bytes
procedure f(n);s:="";s||:=":)=((:)=:():=)(=:||:"[!n*2+1+:2]&/n;return s;end

Try it online!

C# (Visual C# Interactive Compiler), 87, 86, 82, 67 bytes
Props to @Artholl and @someone for helping to optimize
n=>$"{n}".SelectMany(x=>":)=((:)=:():=)(=:||:".Substring(x*2-96,2))

Try it online!

You can save 2 bytes. 1 byte if you use Substring instead of Skip & Take and 1 byte if you hardcode the zero char value.

@Artholl thank you! Could you show me what you mean by hardcoding the zero char value?

As you can see in the example. Just write 48 instead of '0'.

Several simple optimizations; 67 bytes. Try it online!

@Artholl woops my bad didn't see the link

@someone didn't know changing the type of output was allowed outside of the function

JavaScript (ES6), 87 bytes
n=>{for(s=":)=((:)=:():=)(=:||:",i=0;i<20;)n=n.split(i/2).join(s[i++]+s[i++]);return n}

This outputs ): instead of (: for 3

@Herman L Yes, thanks!

Jelly, 24 bytes
“LƇ§×Yþ’ḃ5$s2ị“:)=(|”ị@D

Try it online!

Attache, 34 bytes
Chop[":)=((:)=:():=)(=:||:",2]&Get

Try it online!