text:
Jam don't add like that
Background
Jelly's arithmetic atoms vectorize automatically. In fact, x + y is well-defined whenever x and y are numbers or ragged arrays of numbers. Jelly's source code implements this behavior using a generic vectorizer, but for this challenge, we'll only consider addition of integers and nested integer arrays.
Definitions
Define the depth of x as 0 if x is an integer, as 1 if it is a (possibly empty) flat array of integers, and as n + 1 if it contains at least one element of depth n and no elements of depth k > n.
This way, 1 has depth 0, [] and [1] and [1, 1] have depth 1, [[], []] and [[1], [1]] and [[1]] and [1, []] have depth 2, [1, [1, [1]]] has depth 3, etc.
The operation x + y is defined as follows.

If x and y have depth 0, return their sum.
If x and y have equal but positive depths, recursively apply + to all items of x and the corresponding items of y.
If x and y have different lengths, append the tail of the longer array to the array of sums.
Return the result.
If x's depth is strictly smaller than y's depth, recursively apply + to x and all items of y, and return the result.
Do the opposite if y's depth is strictly smaller than x's.

For example, consider the operation [1, [2, 3], [4]] + [[[10, 20], [30], 40, 50], 60].

The depth of the left argument is 2, while the depth of the right argument is 3, so we compute [1, [2, 3], [4]] + [[10, 20], [30], 40, 50] and [1, [2, 3], [4]] + 60.

[1, [2, 3], [4]] and [[10, 20], [30], 40, 50] both have depth 2, so we compute 1 + [10, 20], [2, 3] + [30] and [4] + 40.

1 + [10, 20] = [1 + 10, 1 + 20] = [11, 21]
[2, 3] + [30] = [2 + 30, 3] = [32, 3]
Note that 3 remains untouched, since it doesn't have a matching element.
[4] + 40 = [4 + 40] = [44]

50 doesn't have a matching element, so the result is [[[11, 21], [32, 3], [44], 50]].
[1, [2, 3], [4]] + 60 = [1 + 60, [2, 3] + 60, [4] + 60] = [61, [2 + 60, 3 + 60], [4 + 60]], resulting in [61, [62, 63], [64]].

The final result is [[[11, 21], [32, 3], [44], 50], [61, [62, 63], [64]]].

Task
Write a program or a function that takes two integers, two nested arrays of integers or a combination thereof as input and returns their sum, as defined above.
If your language has multiple array-like types (lists, tuples, vectors, etc.) you may choose any of them for your answer. The return type must match the argument type.
To prevent boring and unbeatable solutions, if a language has this exact operation as a built-in, you may not use that language.
All built-ins of all other languages are allowed. If your language of choice permits this, you may overload and/or redefine the built-in addition.
This is code-golf, so the shortest code in bytes wins.
Test cases
0 + 0                           = 0
[-1, 0, -1] + [1]               = [0, 0, -1]
[] + [0]                        = [0]
[] + 0                          = []
[] + []                         = []
[[], 0] + []                    = [[], []]
[1, 2, 3] + 10                  = [11, 12, 13]
[1, 2, 3] + [10]                = [11, 2, 3]
[1, 2, 3] + [10, [20]]          = [[11, 12, 13], [21, 2, 3]]
[1, 2, 3, []] + [10, [20]]      = [11, [22], 3, []]
[1, [2, [3, [4]]]] + [10, [20]] = [[11, [21]], [[12, [22]], [13, [24]]]]

To generate more test cases, you can use this Jelly program.

What if our language doesn't support ragged arrays? Are we allowed to restructure the input or should we implement ragged arrays? Or perhaps just use a different language?

What do you mean by restructuring the input?

In further thinking, I realize it would not work to restructure the input but anyways I'll summarize what I meant before. I thought about using a fill value to pad, which would eliminate some work but also create a different problem (probably different from your intended question) but realize now that your test cases include negative numbers too.

The arrays may also be heterogeneous, so fill values wouldn't suffice to make them rectangular. As a last resort, there's always the option to operate on strings, but that's probably too complicated.

Hey, nice title!..  now that Google helped me get it :-)

Pyth, 42 bytes
L?sIb0heSyM+b0M?qFyMJ,GH?yGgM.tJ0+GHgLFyDJ

Test suite
The last 4 bytes simply run the function on the input.
L?sIb0heSyM+b0M?qFyMJ,GH?yGgM.tJ0+GHgLFyDJ

L?sIb0heSyM+b0
                  Define y(b), a helper function to calculate the depth.
 ?                Ternary:
  sIb             If b is invariant under the s function, which is only the case
                  if s is an int.
     0            The depth is 0.
           +b0    Add a 0 on to b. This handles the edge case where b is [].
         yM       Map each to their depth
       eS         Take the max.
      h           Add one.

M?qFyMJ,GH?yGgM.tJ0+GHgLFyDJ
M                               Define g(G, H), which calculates the Jelly +.
 ?                              Ternary:
       ,GH                      Form [G, H].
      J                         Save it to J.
    yM                          Map each to its depth.
  qF                            Check if they are equal.
          ?yG                   If so, check if the depth is nonzero.
               .tJ0             If so, transpose J, pairing each element of each
                                argument with the corresponding element of the
                                other. Pad with zeroes.
             gM                 Map each to its Jelly +.
                   +GH          If the depths are zero, return the normal sum.
                         yDJ    If the depths are different, order J by depth.
                      gLF       Apply the function which left-maps the Jelly +
                                function to the two values. The first is
                                treated as a constant, while the second varies
                                over elements over the second values.

38 bytes

APL, 44 bytes
{1=≡⍺⍵:⍺+⍵⋄=/∆←|≡¨⍺⍵:⊃∇¨/↓↑⍺⍵⋄</∆:⍺∘∇¨⍵⋄⍵∇⍺}

APL's + distributes over arrays as well, but in a different enough manner that this can't really be used. However, there is a built-in depth function (≡).
Explanation:

1=≡⍺⍵:⍺+⍵: if the depths of ⍺ ⍵ are both zero (and therefore the depth of ⍺ ⍵ is 1), add them.
∆←|≡¨⍺⍵: take the absolute of the depth of both ⍺ and ⍵ and store them in ∆. (≡ gives a negative value if not all elements have the same depth.)
=/∆: if they have the same depth:

↓↑⍺⍵: pad the shortest array with zeroes to match the longer array
⊃∇¨/: distribute the function over both arrays

</∆: if the depth of ⍺ is less than that of ⍵:

⍺∘∇¨⍵: bind ⍺ and then map over ⍵

⍵∇⍺: if nothing else (so ⍵ is deeper than ⍺), swap the arguments and try again.

Sometimes I think I know APL okay. Then I see a masterpiece like this and I realize that I barely know it at all.

Do APL characters count as bytes really?

@metalim APL has legacy code pages that predate Unicode by a few decades. In those, each character is a single byte.

Then encoding type should be provided with solution. Just IMO.

@metalim I added a link.

Jelly, 24 22 bytes
ß"+ŒḊ?çⱮç€</ɼ?,ŒḊ€©Eɗ?

Try it online! or see all test cases
This technically violates

To prevent boring and unbeatable solutions, if a language has this exact operation as a built-in, you may not use that language.

However, this is by no means a boring or unbeatable solution. The only time + is used here is to add two flat integers. The rest of it is recursion to get to that point.
This is a full program which takes the two lists are arguments, and outputs the result.
How it works
ß"+ŒḊ?çⱮç€</ɼ?,ŒḊ€©Eɗ? - Main link f(A, B). Takes A on the left and B on the right
                     ? - If:
                    ɗ  -   Condition:
              ,        -     [A, B]
               ŒḊ€     -     Depth of each
                  ©    -     (Save in register, R)
                   E   -     Both depths are equal?
                           Then:
     ?                 -     If:
   ŒḊ                  -       Condition: depth of A is non-zero
ß"                     -       Then: Run f(A, B) on each subarray in A, B
  +                    -       Else: Return A+B
                           Else:
             ?         -     If:
          </ɼ          -       Condition: depth of A is less than that of B
      çⱮ               -       Then: Over each element b of B, yield f(A, b)
        ç€             -       Else: Over each element a of A, yield f(a, B)

We (ab)use ç in order to get Ɱ to work, as ßⱮ will error due to a bug in setting the arity of ß during execution. ç technically calls the link above explicitly as a dyad, but in a full program with only one link, this wraps around to call the same link.

Mathematica, 122 bytes
d=Depth
x_~f~y_/;d@x>d@y:=y~f~x
x_~f~y_/;d@x<d@y:=x~f~#&/@y
x_List~f~y_:=MapThread[f,{x,y}~PadRight~Automatic]
x_~f~y_=x+y

Defines a recursive function f which computes the sum. Making use of Mathematica's pattern matching, this function is made up of four separate definitions:
x_~f~y_/;d@x>d@y:=y~f~x

If the depth of x is greater than that of y, swap the arguments so that we only have to handle distribution in one direction (which we can do, since addition is commutative).
x_~f~y_/;d@x<d@y:=x~f~#&/@y

If the depth of x is less thann that of y, replace each value # in y with f[x,#], which takes care of the distribution for arguments of unequal depth.
x_List~f~y_:=MapThread[f,{x,y}~PadRight~Automatic]

Otherwise, if one argument is a list (which implies that the other also is a list, since we know they have the same depth), we put both arguments in a list, pad them to the same length with PadRight[..., Automatic] (which simply fills up a ragged array with zeros to make it rectangular), and then use MapThread to apply f to corresponding pairs from the two lists.
And finally, the base case:
x_~f~y_=x+y

If none of the other patterns match, we must be trying to add two numbers, so we just do that.

Haskell, 150 bytes
data L=S Int|V{v::[L]}
d(V z)=1+maximum(d<$>S 0:z);d _=0
S x!S y=S$x+y
x!y|d x<d y=V$(x!)<$>v y|d x>d y=y!x|1<2=V$v x#v y
(x:a)#(y:b)=x!y:a#b;a#b=a++b

Explanation
The first line defines an algebraic data type L, which is either a Scalar (containing an Int) or a Vector (containing a list of Ls, accessed using a record getter v, which is a partial function L → [L].)
The second line defines the depth function: the depth of a Vector is one plus its maximum depth. I prepend S 0 to the values in the vector, so that depth [] == 1 + maximum [depth (S 0)] == 1. The depth of “anything else” (a scalar) is 0.
The third line defines the base case for ! (the addition function): the sum of scalars is simply a scalar.
The fifth line defines a variant of zipWith (!) that just picks elements from the longest list when one of them is empty.
The fourth line is split in three cases:
x!y | d x<d y = V$(x!)<$>v y
    | d x>d y = y!x
    | True    = V$v x#v y

If the depth of x is strictly less than the depth of y, map (x!) over the elements of y. (The use of v is guaranteed to be valid, as d(y) ≥ 1.)
If the depth of x is strictly greater, flip the arguments and restart.
If their depths are equal, zip the arguments together with (!). (The use of v is guaranteed to be valid, as the case d(x) = d(y) = 0 was handled as a base case.)

Test cases
instance Show L where
  show (S x) = show x
  show (V x) = show x

lArg = V [S 1, V [S 2, V [S 3, V [S 4]]]]
rArg = V [S 10, V [S 20]]

Then show (lArg ! rArg) == "[[11,[21]],[[12,[22]],[13,[24]]]]".

I just fixed that, too ^^ (I had swapped the lines for readability, but I did it the wrong way…) The import is because Ideone has an old Haskell compiler. Modern versions of GHC put <$> in Prelude, so you don’t need to import Control.Applicative to use it these days.

Agh too many edits at the same time as my other actions :P And sure, it seems ok now, but I find it pretty weird that that causes a compilation error. Do all the pattern matching bits of a function have to be consecutive?

That’s exactly right.

Alright, thanks for all your help :) "I'll get the hang of this language some day" - FryAmTheEggman 7 years ago.

Java, 802 794 754 746 bytes
I decided to take up @Dennis♦ for the challenge to operate on strings "as a last resort" because it was probably "too complicated". Also, in the worst language to golf on.
Arrays in the input are comma-separated, surrounded with square brackets, and without whitespace.
Full program with functions wrapped into a class and with test cases
import java.util.*;
List<String>p(String s){List r=new ArrayList<String>();String p="";int l=0;for(char c:s.substring(1,s.length()-1).toCharArray()){l+=c=='['?1:c==']'?-1:0;if(c==','&&l<1){r.add(p);p="";}else p+=c;}if(p!="")r.add(p);return r;}
int d(String s){int l=0;if(s.contains("[")){for(String c:p(s))l=d(c)>l?d(c):l;l++;}return l;}
String f(String x,String y){int i=0;String r="";if(d(x)<1&&d(y)<1)r+=Integer.valueOf(x)+Integer.valueOf(y);else{r="[";if(d(x)<d(y))for(String k:p(y))r+=(i++<1?"":",")+f(x,k);else if(d(x)>d(y))for(String k:p(x))r+=(i++<1?"":",")+f(k,y);else for(;i<p(x).size()||i<p(y).size();i++)r+=(i<1?"":",")+(i<p(x).size()&&i<p(y).size()?f(p(x).get(i),p(y).get(i)):i<p(x).size()?p(x).get(i):p(y).get(i));r+="]";}return r;}

I might port this to C++ later since it's the other language I know that doesn't support ragged arrays, since I'm pretty sure almost certain it'll be shorter than this answer. This was mostly a proof of concept but any golfing tips would still be appreciated!
-31 bytes from @user902383 suggesting using a foreach over a converted character array, and then I saved a little more from rearranging the if blocks in the final part.

That's impressive.

I think if you replace your loops with foreach loop trough char array obtained from string, you could save quite lot of bytes.

Errr... Java supports ragged arrays; I'm not sure what you mean by that. Use Object[], which contains either nested Object[] or Integer. Or just non-generic List.

C (GCC), 377 354 bytes
-23 bytes thanks to @ceilingcat
d(w,r,i,x)S w;{for(r=i=0;w.v&&i<w.n;r=x>r?x:r)x=d(w.v[i++]);return!!w.v+r;}s(S*z,S x,S y){int e=d(x),f=d(y);if(e-f){S X=e<f?x:y,Y=e<f?y:x;for(z->v=calloc(e=z->n=Y.n,16);e--;)s(z->v+e,X,Y.v[e]);}else if(e+f){z->v=malloc(x.n+y.n<<4);for(e=0;e<x.n|e<y.n;++e)e>=x.n|e>=y.n?z->v[e]=(e<x.n?x:y).v[e],0:s(z->v+e,x.v[e],y.v[e]);z->n=e;}else z->n=x.n+y.n,z->v=0;}

Attempt This Online!
(footer contains main, non-golfed functions, and other useful functions)
Assumes that ragged arrays are represented with the following struct:
typedef struct S{
    int n;
    struct S *v;
} S;

where

if x is an integer, x.n is its value, and x.v is set to NULL;
if x is a ragged array, x.n is its length, and x.v is the array containing the sub-elements.

Possible improvement: write a function that computes the sum in-place instead of allocating a new ragged array.

Thanks to @zoomlogo for pointing to this old interesting challenge in this bounty

Suggest if(e) instead of if(e+f)

Python 2.7, 261 209 202 198 191 185 197 181 bytes
FGITW trivial solution
EDIT: Of course @Dennis beats it
Thanks to @LeakyNun for saving 57 bytes with tips on lambda expressions, and 2 bytes from unneeded brackets.
Thanks to @Adnan for 4 bytes due to suggestion to use type instead of isinstance
Thanks to @Lynn for 7 bytes with -~ and map
Thanks to @FryAmTheEggman for z>=[] instead of type
+12 bytes to convert lambda to if else and fix a major bug
-16 bytes thanks to @Kevin Lau - not Kenny
Try it online
d=lambda z:z==[]or z>[]and-~max(map(d,z))
p=lambda x,y:p(y,x)if d(x)>d(y)else(x+y if d(x)<1 else[p(a,b)for a,b in zip(x,y)]+x[len(y):]+y[len(x):])if d(x)==d(y)else[p(a,x)for a in y]

It’s even shorter to switch to Python 2.7 and write z==[]or`z`>']'and ...

Also, I think replacing max(d(a)+1for a in z) with -~max(d(a)for a in z) saves a byte (because you can remove the space before max). Which is then just -~max(map(d,z)).

Switching to python 2 saves even more in that you can change [p(a,b)for a,b in zip(x,y)] into map(p,x,y). You can still do this in 3 but you need to add a call to list. I think you could also improve Lynn's suggestion to be z>=[]. Unrelated, you should also be able to swap the type comparison order to save a space.

Err, I meant or`z`>'[', of course, but I can’t change my comment anymore. But indeed, z>[] is even shorter (the == case is already handled)!

@FryAmTheEggman map doesn't work when the lists are of different sizes; zip truncated correctly. I will update with the list check tho

@Dennis yup, that's right, and doesn't like 0. p(-1,1) should do the same thing. Fixing

@Dennis I think Blue may have slightly misinterpreted my suggestion, here is a python 2 version working with the test cases that do not add to zero. To fix that I think you need an if...else construct instead.

Because of how Python zip truncates to the smaller of the two lists, could you do [p(a,b)for a,b in zip(x,y)]+x[len(y):]+y[len(x):] instead of doing the length check and swapping the arguments if x is bigger?

@KevinLau-notKenny oh, I thought that would thrown an oob error, but it doesn't. Thanks!

Also, it's "not Kenny", not "not Kenney"...

Python 2, 145 136 bytes
d=lambda t:t>{}and-~max(map(d,t+[0]))
s=lambda x,y:s(y,x)if d(y)<d(x)else map(s,(x,[x]*len(y))[d(x)<d(y)],y)if d(y)else(x or 0)+(y or 0)

Test it on Ideone.
How it works
In Python 2, all integers are less than all dictionaries, but all lists are greater. d recursively computes the depth of t by returning 0 for integers or the incremented maximum of the depths of its elements and 0. t+[0] avoids special-casing the empty list.
s recursively computes the Jelly sum of x and y.
If y's depth exceeds x's, s(y,x) calls s with swapped arguments, making sure that d(x) ≤ d(y).
If y has positive depth, map(s,(x,[x]*len(y))[d(x)<d(y)],y) does the following.

If the x's and y's depths match, it executes map(s,x,y), mapping s over all elements of x and the corresponding elements of y.
In the case of lists of different lengths, map will pass None as left or right argument for missing elements in the shorter list.
If x's depth is lower than y's, it executes map(s,[x]*len(y),y), mapping s(x, · ) over y.

If y (and, therefore, x) has depth 0, (x or 0)+(y or 0) replaces falsy arguments (None or 0) with zeroes and returns the sum of the resulting integers.

Scala 3, 496 bytes
Port of @Value Ink's Ruby anwer in Scala.

Golfed version. Attmept this online!
496 bytes, it can be golfed much more.
val d:Any=>Int={case l:Seq[_]=>1+l.map(d).maxOption.getOrElse(0)case _=>0}
def f(x:Any,y:Any):Any=(d(x),d(y))match{
case(a,b)if a<b=>y.asInstanceOf[Seq[_]].map(f(x,_))
case(a,b)if a>b=>x.asInstanceOf[Seq[_]].map(f(_,y))
case _=>(x,y)match{
case(x:Int,y:Int)=>x+y
case(x:Seq[_],y:Seq[_])=>
val(a,b)=(math.min(x.size,y.size),math.max(x.size,y.size))
val z=x.take(a).zip(y.take(a)).map((f _).tupled)
z++(if(x.size==b)x.takeRight(b-a)else Seq())++(if(y.size==b)y.takeRight(b-a)else Seq())
case _=>x}}

Ungolfed version. Attmpt this online!
object Main {
  val depth: Any => Int = {
    case x: List[_] => 1 + x.map(depth).maxOption.getOrElse(0)
    case _ => 0
  }

  def function(x: Any, y: Any): Any = (depth(x), depth(y)) match {
    case (dx, dy) if dx < dy => y.asInstanceOf[List[_]].map(element => function(x, element))
    case (dx, dy) if dx > dy => x.asInstanceOf[List[_]].map(element => function(element, y))
    case _ => (x, y) match {
      case (x: Int, y: Int) => x + y
      case (x: List[_], y: List[_]) =>
        val minLen = math.min(x.size, y.size)
        val maxLen = math.max(x.size, y.size)
        val zipPart = x.take(minLen).zip(y.take(minLen)).map((function _).tupled)
        val remainingPartX = if(x.size == maxLen) x.takeRight(maxLen - minLen) else List()
        val remainingPartY = if(y.size == maxLen) y.takeRight(maxLen - minLen) else List()
        zipPart ++ remainingPartX ++ remainingPartY
      case _ => x
    }
  }

  def main(args: Array[String]): Unit = {
    println(function(List(1, List(2, List(3, List(4)))), List(10, List(20))))
    println(function(List(-1, 0, 1), List(1)))
  }
}

JavaScript (ES6), 152 bytes

f=(a,b,g=a=>a.map?1+Math.max(0,...a.map(g)):0)=>g(a)<g(b)?f(b,a):g(b)<g(a)?a.map(e=>f(e,b)):g(a)?a.length<b.length?f(b,a):a.map((e,i)=>f(e,b[i]||0)):a+b
;t=(x,y,z)=>o.textContent+=`
${JSON.stringify(x)}
${JSON.stringify(y)}
${JSON.stringify(z)}
${JSON.stringify(f(x,y))}
`;`
0 + 0                           = 0
[-1, 0, -1] + [1]               = [0, 0, -1]
[] + [0]                        = [0]
[] + 0                          = []
[] + []                         = []
[[], 0] + []                    = [[], []]
[1, 2, 3] + 10                  = [11, 12, 13]
[1, 2, 3] + [10]                = [11, 2, 3]
[1, 2, 3] + [10, [20]]          = [[11, 12, 13], [21, 2, 3]]
[1, 2, 3, []] + [10, [20]]      = [11, [22], 3, []]
[1, [2, [3, [4]]]] + [10, [20]] = [[11, [21]], [[12, [22]], [13, [24]]]]`.slice(1).split`
`.map(l=>t(...l.split(/ [+=] /).map(a=>JSON.parse(a))));
<pre id=o></pre>

g=a=>a.map?-~Math.max(...a.map(g)):0

Ruby, 143 145 148 149 147 bytes
Ruby has all these little quirks in how zip works with different-length arrays and map with multi-argument functions, making this pretty fun to golf down.
The function has to be explicitly declared as a proc because -> declares a lambda, which has strict argument checking that won't splat arguments passed in through Array#map.
d=->a{-~(a.map(&d).max||0)rescue 0}
f=proc{|x,y|d[x]<d[y]?y.map{f[x,_1]}:d[x]>d[y]?x.map{f[_1,y]}:d[x]<1?x+(y||0):[*x.zip(y).map(&f),*y[x.size..]]}

Attempt This Online!

That's very interesting-- I've never seen that error before for this function. I still patched some things up because of other bugs now, but other than that it works for me (but still fails on ideone). I think it's because ideone runs 2.1 and I have 2.3, so perhaps 2.1 can't just map on a two-arg function the way I set it up at the end. Here's a version edited for 2.1 that works that tweaks the map call at the end to work. http://ideone.com/q1jqTA

Julia, 113 bytes
~=endof;!t=0t!=0&&1+maximum(!,[t;0])
x::Array+y::Array=(!x,~x)>(!y,~y)?y+x:!x<!y?map(t->x+t,y):~x<~y?[x;0]+y:x.+y

Try it online!
How it works
~=endof

creates a 1-byte alias for endof, which returns the length of an array.
!t=0t!=0&&1+maximum(!,[t;0])

defines a depth function. The depth of t is zero if and only if 0t == 0. If not, t is an array, and its depth is calculated as the incremented maximum of the depths of its elements and 0. [t;0] appends a 0 to the array t, thus avoiding the need to special-case the empty array.
Julia's built-in sum + already behaves like Jelly's sum if either (or both) of its arguments is an integer. However, the sum of two arrays (+) requires arrays of the same shape, and even the vectorized sum (.+) required arrays that can be broadcast to a common shape.
We redefine + for a pair of arrays via
x::Array+y::Array=(!x,~x)>(!y,~y)?y+x:!x<!y?map(t->x+t,y):~x<~y?[x;0]+y:x.+y

This does not affect the definition of + for integer/integer, array/integer or integer/array arguments.
(!x,~x)>(!y,~y) lexicographically compares the pairs of depths and lengths of both x and y. If x's depth exceeds y's, or if their depth match and x's length exceeds y's, y+x recursively calls + with swapped arguments.
Otherwise, !x<!y tests if x's depth is lower than y's. If it is, map(t->x+t,y) maps x + · over y.
If the depths match, ~x<~y tests if x is shorter than y. If it is, [x;0]+y recursively calls + after appending a 0 to the left argument.
Finally, if both depths and lengths are identical, x.+y maps + over all elements of x and the corresponding elements of y.


text:
Stack Overflowing
(Inspired by this question)
Objective
Your task is to write a program or function to print an ASCII version of the Stack Overflow logo to STDOUT
 \|/
(-)
(-)
(-)
(-)

Your program should take two inputs, referred to here as H and N.
The height of the stack "container" (the parentheses) is determined by H. The number of items in the stack is determined by N. If N>H, the stack will "overflow".
Input/Output
H will determine the height of the containers
For example:
H=1:
( )

H=2:
( )
( )

H=3:
( )
( )
( )

H will always be at least 1
N will determine how many items are in the stack. The following examples are all H = 2:
N=0
( )
( )

N=1
( )
(-)

N=2
(-)
(-)

N=3
 \
(-)
(-)

N=4
 \|
(-)
(-)

N=5
 \|/
(-)
(-)

N=6
 \|/
(-)-
(-)

N=7
 \|/
(-)-
(-)-

N will never be more than 2H+3 (In other words, the stack will never go through the ground).
Rules

No Standard Loopholes.
Your program must not produce any errors.
All test cases must pass.
You can input H and N any way you want.
I seriously doubt that your language has a built-in for this.
Each line may optionally have an extra space at the end. A blank line above a stack where N <= H is optional, as is a trailing newline.
This is code-golf, so shortest code in bytes wins!

Test Cases
In addition to all of the H=2 test cases from the Input/Output section, all of the following test cases must pass:
H=1, N=1
(-)

H=1, N=5
 \|/
(-)-

H=4, N=7
 \|/
(-)
(-)
(-)
(-)

H=5, N=0
( )
( )
( )
( )
( )

Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

May I post a non-competing program that actually overflows the stack instead of printing the logo?

@dorukayhan If it only overflows when n>h :)

I mean, may I make a program that crashes from a stack overflow?

@dorukayhan only if it crashes when there are more items than the stack can hold

Pyth, 43 41 40 bytes
<" \|/"g#0hK-QJEVJs[\(?<N_Kd\-\)*<N-K3\-

Try it online. Test suite.
First pass, quick and dirty. Input to STDIN as N\nH.
Explanation

Save the second input (height) to J (JE), and subtract it from the first input (the number of items). (-QJE)
Save the difference (number of overflowing items) to K. (K-QJE)
Add 1 to the number. (hK-QJE)
Take max(0, previous). This is required as negative numbers would break the next step. (g#0hK-QJE)
Take at most that many letters from the string " \|/" to get the first line and print. (<" \|/"g#0hK-QJE)
Loop N over range(0, J). (VJ) For each N print the concatenation of the following: (s[)

"(" (\()
" " if there are at least N+1 free spaces in the stack (<N_K), "-" otherwise. (?<N_Kd\-)
")" (\))
"-" if there are at least N+4 overflowing pieces in the stack (<N-K3), "" otherwise. (*<N-K3\-)

JavaScript (ES6), 105 102 bytes
@Edit: Saved 3 bytes thanks to @PatrickRoberts.

f=
(n,h)=>` \\|/`.substr(0,n+1-h)+[...Array(h)].map((_,i)=>`
(${i+n<h?` `:`-`})${i+h+3<n?`-`:``}`).join``
;

n<input id=n type=number min=0 value=0>h<input id=h type=number min=0 value=0>

You can replace substring with substr to save 3 bytes, and replace i+n<h?' ':'-' with '- '[i+n<h] to save 2 bytes and replace i+h+3<n?'-':'' with ' -'[i+h+3<n] to save 1 byte. That'll get you under 100

@PatrickRoberts I couldn't remember whether substr ignored negative subscripts or not, but I can't use your other tips because string subscripts are strings, so booleans aren't good enough.

crap I forgot about that, good point

Really clever use of tagged template in order to save those two characters!

@BenjaminGruenbaum what is a "tagged template"?

@PatrickRoberts ECMASCript 2015 brings template strings with backticks ()s - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals - the fun part is that you can pass a _function_ before them which will allow you to do nifty things with them (escape SQL automatically, write parsers, lots of fun things). This answer uses this using .join_as if_ it was a template tag, thethis` value remains and the empty string is passed as the template - tagged template take the template parts as the first argument so this just happens to work. Pretty clever trick.

@BenjaminGruenbaum thank you for that resource. I always just assumed that if the function took a single string argument that you could omit the parentheses. Now I understand why.

JavaScript (ES6), 126 122 112 bytes
h=>n=>' \\|/'.substr(0,(o=n-h)+1)+`
( )`[r='repeat'](0>-o?0:-o)+`
(-)-`[r](o=0>o-3?0:o-3)+`
(-)`[r](n<h-o?n:h-o)

Test

f=h=>n=>' \\|/'.substr(0,(o=n-h)+1)+`
( )`[r='repeat'](0>-o?0:-o)+`
(-)-`[r](o=0>o-3?0:o-3)+`
(-)`[r](n<h-o?n:h-o)
document.write(`<pre>${[[2,0],[2,1],[2,2],[2,3],[2,4],[2,5],[2,6],[2,7],[1,1],[1,5],[4,7],[5,0]].map(a=>f(a.shift())(a.shift())).join`

`}</pre>`)

Alternate Test (if your browser does not support ES6)
See the test on Babeljs.io and check "evaluate".
Interesting alternate approach at 136 bytes
h=>n=>' \\|/'.substr(0,(o=n-h)+1)+`
( )${0>-o?0:-o}
(-)-${o=0>o-3?0:o-3}
(-)${n<h-o?n:h-o}`.replace(/(\n.*)(\d+)/g,(_,s,r)=>s.repeat(r))

This moves the repeat amounts into the template string and uses a regexp and replace to inject the repeating groups. Unfortunately the signature for .replace() is just too long.

I get an error...?

@VTCAKAVSMoACE your browser must support ES6 syntax. It works fine for me. Feel free to paste the test into Babel.

@VTCAKAVSMoACE Chrome 52 (in beta as of June 2016) supports all of ES6 and ES7 except tail call optimisation and module loading.

C++14 (lambda function), 196
Saved 1 byte thanks to Quentin.
Saved 2 bytes thanks to Adam Martin.
#include<iostream>
using namespace std;[](int h,int n){auto s=" \\|/( ) (-) (-)-"s;int t=max(min(n-h,3),0);n-=t;cout<<s.substr(0,t+1)+'\n';for(;h;h--)n-=t=n>h?2:h<=n,cout<<s.substr(4+4*t,4)+'\n';}

The function itself takes 157 bytes.
See it in action here.
Ungolfed version:
[](int h, int n) {
    auto s = " \\|/( ) (-) (-)-"s;
    int t = max(min(n - h, 3), 0);
    n -= t;
    cout << s.substr(0, t + 1) + '\n';
    for(; h; h--) {
        if (n > h) t = 2;
        else if (h > n) t = 0;
        else t = 1;
        n -= t;
        cout << s.substr(4 + 4 * t, 4) + '\n';
    }
};

I see no point in including includes and using namespace std; in byte count, unless your answer is a complete program (which it isn't).

CJam, 57 bytes
Sri:X'(*+X),W%X)X')*+X),X))f+]zN*X5*,X'-*_"\|/"\++ri<S+er

Test it here.
Could definitely use some improvement. The idea is to build a grid where the -\|/- cells are replaced with consecutive integers, e.g.
 345
(2)6
(1)7
(0)8

And then to replace them with the correct characters (potentially spaces) at the end.

Python 2, 101 100 98 bytes
def f(h,n):
 print" \|/"[:max(0,n-h+1)]
 for i in range(h):print("(-)","( )")[h-i>n]+"-"*(n>i+h+3)

Spaces after print are unnecessary

@Cyoce Thanks, that saves 2 chars.

JavaScript (ES6), 87 80 bytes
F=(h,n)=>h?F(h-1,n-1)+`
(${n>0?'-':' '})${n>2*h+2?'-':''}`:' \\|/'.substr(0,n+1)

Uses recursion to create the output string from the bottom up.
EDIT: Thanks to @Neil for shaving 7 bytes off from 87 bytes
Original
(h,n)=>(E=s=>h--?E(`
(${n>0?'-':' '})${--n>2*h+3?'-':''}`+s):` \\|/`.substr(0,n+1)+s)``

Test snippet:

F=(h,n)=>h?F(h-1,n-1)+`
(${n>0?'-':' '})${n>2*h+2?'-':''}`:' \\|/'.substr(0,n+1)

h.oninput = n.oninput = () => output.innerHTML = F(+h.value, +n.value);
h <input type="number" min="0" value="0" id="h" />
n <input type="number" min="0" value="0" id="n" />

thanks for the nice snippet! Should give an extra point :P

@Kimmax Thanks mate, no one wants to be messing about with the console

At least when I tried, the stack was pretty large, and it would only be 78 bytes with ordinary recursion.

The snippet console is showing a SyntaxError for me.

@ArtOfCode Need to use an ES6 compliant browser

@GeorgeReith I think I am... Chrome 53

@ArtOfCode Strange works fine for me. What's the full error? That is a preview browser though. I am on Chrome 51 FYI

@Neil None of the major browsers implement TCO yet. It's just a note. How would it be 78 bytes? This is normal recursion.

I miscounted and it was 80: f=(h,n)=>h?f(h-1,n-1)+\\n)${n>0?'-':' '})${n>2*h+2?'-':''}`:' \|/'.substr(0,n+1)`

@Neil That's really cool thanks! Not sure why that didn't occur to me to not pass the string down.

@PatrickRoberts Thanks good spot, was used to just pasting the definition from my other answers

JavaScript (ES6), 149 139 137 bytes
h=>n=>` ${[(g=(j,m=1)=>` -\\|/`[(j<n)*m])(h,2),g(h+1,3),g(h+2,4)].join``}${[...Array(h)].map((_,i)=>`
(${g(h-i-1)})${g(h+i+3)}`).join``}`

I liked @MartinEnder's idea about indexing the -\|/ characters and I wanted to see how it would fare in ES6. Apparently I didn't do so well. Trying to figure out if this could be improved using for...of.
Edits

I managed to remove regexp and the call to .replace, moving the indexing directly into g() instead.
I accidentally counted f= in the second byte count

Test

f=h=>n=>` ${[(g=(j,m=1)=>` -\\|/`[(j<n)*m])(h,2),g(h+1,3),g(h+2,4)].join``}${[...Array(h)].map((_,i)=>`
(${g(h-i-1)})${g(h+i+3)}`).join``}`
document.write(`<pre>${[[2,0],[2,1],[2,2],[2,3],[2,4],[2,5],[2,6],[2,7],[1,1],[1,5],[4,7],[5,0]].map(a=>f(a.shift())(a.shift())).join`

`}</pre>`)

Java, 186 177 bytes
void f(int h,int n){for(int i=0;i<h+1;i++)System.out.print((i>0?"(":" ")+(i>0?n>h-i-2?"-":" ":n>h+0?"\\":" ")+(i>0?")":n>h+1?"|":" ")+(i>0?n>h+2+i?"-":" ":n>h+2?"/":" ")+"\n");}

Ungolfed try online
String f(int h, int n)
{
    String s=" ";
    s+=n>h+0?"\\":" ";
    s+=n>h+1? "|":" ";
    s+=n>h+2? "/":" ";
    s+="\n";

    for(int i=0; i<h; i++)
    {
        s+="(";
        s+=n>h-i-1?"-":" ";
        s+=")";
        s+=n>h+3+i?"-":" ";
        s+="\n";
    }

    return s;
}

You can save bytes by using a lambda- you can probably even leave out the lambda body

Do I need some custom IDE to compile Ungoled Java code? :D

@Kimmax .. D'oh!

Excel, 131 bytes
Input taken as a tuple, Height H in A1, N in B1.  Cell containing formula needs to have Text Wrapping turned on. Suggest using a Mono-spaced font.
=LEFT(" \|/",MAX(0,B1-A1+1))&"
"&REPT("(-)-
",MAX(0,B1-A1-3))&REPT("( )
",MAX(0,A1-B1))&REPT("(-)
",A1-MAX(0,B1-A1-3)-MAX(0,A1-B1))

Wonderful solution! You should add that this take input as the 2-tuple from A1 and B1 and add the simple note that this does require the calling cell to have the wrap text option to be true. Also maybe that to get the proper alignment it should have a mono-spaced font such as Courier New or Lucidia Console

Thanks @TaylorScott.  Updated answer with your suggestions.

C++11, 155 148 145 bytes
void f(int h,int n){cout<<string{" \\|/",max(min(3,n-h),0)+1}<<'\n';for(int i=0;i<h;++i)cout<<(h-i<=n?"(-)":"( )")<<(i<max(n-h-3,0)?"-\n":"\n");}

Ungolfed:
void f(int h,int n)
{
  cout << string{" \\|/", max(min(3, n-h), 0) + 1} << '\n';
  for(int i=0; i<h; ++i)
    cout << (h-i <= n ? "(-)" : "( )") << (i < max(n-h-3,0) ? "-\n" : "\n");
}

Usage:
#include <iostream>
#include <string>
using namespace std;

void f(int h,int n){cout<<string{" \\|/",max(min(3,n-h),0)+1}<<'\n';for(int i=0;i<h;++i)cout<<(h-i<=n?"(-)":"( )")<<(i<max(n-h-3,0)?"-\n":"\n");}

int main()
{
  int h,n;
  cin >> h >> n;
  f(h, n);
}

137 bytes

Vyxal, 34 bytes
ð₴-0∴`\|/`Ẏ,(\(₴¹n->\)-2↳3¹+n+⁰<-,

Try it Online!
ð₴                                 # Output a space
  -                                # Difference
   0∴                              # or 0 if diff. is negative
     `\|/`                         # String literal
          Ẏ,                       # First (max(N - H, 0)) letters
            (                      # Height times do...
             \(₴                   # Output a (
                ¹n-                # The difference of (iteration number) and (height)
                   >               # Is greater than (N)
                    \)-            # That many -s before a )
                       2↳          # Justified to the right, so space if not empty
                         3¹+       # 3 + (Height)
                            n+     # Plus iteration number
                              ⁰<   # Is less than (N)
                                -  # That many -s appended to the previous string
                                 , # Output with trailing newline.

Python 3, 134 121 118 111 bytes
def f(h,n):print('\|/'[:max(0,n-h)]+'\n'+'\n'.join('(-)-'if h<n-x-3else('(-)','( )')[x+n<h] for x in range(h)))

Test it here: https://repl.it/CYL1/0
Un-golfed:
def f(h,n):
  top=['\|/'[:max(0,n-h)]]
  stack=['( )'if x+n<h else'(-)'for x in range(h)]
  overflow=top+stack
  v=n-3
  while v>h:
      overflow[h-v]+='-' #add side overflow
      v-=1

  print('\n'.join(overflow))

I'd like to have added the side overflow to the list comprehension, but I couldn't squeeze it in, so I had to go with the while loop. Saved 13 bytes!

The output is off, you probably need to change the '\|/'[:max(0,n-h)] to be like the Python 2 solution.

Perl 5, 91 bytes
say((' \|/'=~/./g)[0..-($a=<>)+($b=<>)]);say$b<=$a-$_?'( )':'(-)'.'-'x($b-2>$a+$_)for 1..$a

Try it online!

Pip, 50 bytes
Ps.(0Xa."\|/")@<bDC0Fi,aP"()"WV"- "@[b<a-ib<a+4+i]

Try it online!
Ugh, this is too long... don't know how to shorten it any more, though. Cyclical indexing, which is usually helpful, cost extra bytes this time.

PowerShell, 109 108 104 bytes
param($n,$h)-join" \|/"[0..(($d=$n-$h),0)[$d-lt0]]
1..$h|%{("( )","(-)")[$h-$_-lt$n]+"-"*($h+$_+2-lt$n)}

Try it online!
Lost a lot on expensive indexing but still decent-ish. I'm not sure my index math is optimal however. Stole some logic from the other answers to save a byte. Also remembered precedence to pop some parens for -4 bytes.

05AB1E, 45 bytes
-U…( )¸¹иε²N›ið'-:]RεX4-N@i'-«]" \|/"XdX*>£š»

Can definitely be golfed.. Not too happy about it in its current form tbh.
Try it online or verify all test cases.
Explanation:
-                # Subtract the 2nd (implicit) input `n` from the 1st (implicit) input `h`
                 #  i.e. `h`=3, `n`=8 → 5
 U               # Pop and store it in variable `X`
…( )             # Push string "( )"
    ¸            # Wrap it into a list: ["( )"]
     ¹и          # Repeat it the first input (`h`) amount of times
                 #  i.e. 3 → ["( )","( )","( )"]
ε                # Map each to:
 ²N›i            #  If the second input `n` is larger than the map-index N:
                 #    i.e. `n`=8 >= N=0 → 1 (truthy)
     ð'-:       '#   Replace the space with a "-"
                 #    i.e. "( )" → "(-)"
]                # Close both the if and map
 R               # Reverse the list
ε                # Map each to:
 X4-N@i          #  If `X` minus 4 is larger than or equal to the map-index N:
                 #     i.e. `X`=5 and N=0 → 5-4 >= 0 → 1 (truthy)
                 #     i.e. `X`=5 and N=2 → 5-4 >= 2 → 0 (falsey)
       '-«      '#   Append a "-"
]                # Close both the if and map
 " \|/"          # Push String " \|/"
       Xd        # Check if `X` is 0 or positive (0 if negative, 1 if 0 or positive)
                 #  i.e. `X`=5 → 1 (truthy)
         X*      # Multiply it by `X`
                 #  i.e. 1 * 5 → 5
           >     # Increase it by 1
                 #  i.e. 5 → 6
            £    # Take that many character of the string " \|/"
                 #  i.e. 6 → " \|/"
             š   # Prepend it to the list
                 #  i.e. ["(-)-","(-)-","(-)"] and " \|/" → [" \|/","(-)-","(-)-","(-)"]
              »  # Join the list by newlines (and output implicitly)
                 #  i.e. [" \|/","(-)-","(-)-","(-)"] → " \|/\n(-)-\n(-)-\n(-)"

If it makes you feel better here's what I had: LR'(ì')«¹x‚3+¬UŸ¦ζJ¹XŸJ¦1úr)˜» and that's only half done.

source: Stack Exchange

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

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

sort: votes


text:
Simulate a 'battle' in the playing card game 'Oorlog'
Let's build a simulation for an aspect in the card game, which I personally know by the Dutch name 'Oorlog' (translates to 'War').
How does 'Oorlog' work?
Two decks of cards (each including two Jokers) are equally divided between the amount of players playing. Each player shuffles their own stock, put it upside down in front of them, and all players open up the first card of the stock at the same time.
The winner of that 'battle' is determined by the values of the cards following these rules: Joker/Ace defeats King; King defeats Queen; Queen defeats Jack; Jack defeats 10; 10 defeats 9; .... In addition, both 2 and 3 defeat Ace/Joker. The last rule may lead to a cycle where 2 or 3 beats Ace or Joker, Ace or Joker beats some other card, which in turn beats the 2 or 3. In this case, the 2 or 3 wins the battle.
(Suit is irrelevant in this card game.)
When two or more players have the equal highest cards, they have a 'war'. This means they put one card upside down, and then each opens up a new card from their stock, again looking who has the highest card. This continues until a single player wins the entire battle.
(All cards of that battle go to the discard pile of the player that won the battle. Then everyone opens up a new card. When a player's stock is out of cards, they turn their discard pile upside down and continue with this new stock. This continues until a player is out of all his/her cards and then the player with the highest amount of cards wins.)
Example 'battles' with three players:

4, 8, Jack:
Jack wins.
7, Ace, Queen:
Ace wins.
10, 10, King:
King wins.
3, Joker, 2:
3 wins.
Ace, Joker, 2:
2 wins.
3, Queen, Ace:
3 wins.
Queen, Queen, 9:
Queen & Queen are having a 'war', so it continues with two new cards: 4, 8;
8 wins.
4, 4, 4:
All are having a 'war', so it continues with three new cards: 8, Ace, 2;
2 wins.
Jack, 5, Jack:
Jack & Jack are having a 'war', so it continues with two new cards: 5, 5;
5 & 5 are also equal, so the 'war' continues again with two new cards: 10, King;
King wins.
Joker, Joker, Ace:
All are having a 'war', so it continue with three new cards: 9, 7, 9;
9 & 9 are also equal, so the 'war' continues with two new cards: Jack, 3;
Jack wins.

So, onto the code challenge:
Input:
STDIN with an array, or a string simulating an array (your call - even if your language does support arrays). This array contains the cards of a battle in chronological order (see test cases for a clearer understanding of this).
Output:
STDOUT the index of the player that won the battle.
You can choose whether you want a zero-indexed (i.e. 0, 1, or 2) or one-indexed output (i.e. 1, 2, 3).
Challenge rules:

The input will be a single array / string representing an array. So you can't have an array of arrays to simplify it. You also can't have surrogate items for cards not participating in the war.
We use number notations for the face-cards instead of letter notation. So Ace/Joker = 1; Jack = 11; Queen = 12; and King = 13.
In this challenge we can assume we are always playing with 3 players.
The first three indicate the start of the 'battle'. When two or more players have a 'war' the continuing cards in the array indicate their battle (see test cases for a clearer understanding of this).

General rules:

This is tagged code-golf, so shortest answer in bytes wins.
This doesn't mean non code-golfing languages shouldn't enter. Try to come up with an as short as possible code-golf answer for 'every' programming language.
Please mention which indexing (zero- or one-indexed) you've used for the output.

Test cases:
Test case 1:  [4, 8, 11]                 ->  2 (or 3)
Test case 2:  [7, 1, 12]                 ->  1 (or 2)
Test case 3:  [10, 10, 13]               ->  2 (or 3)
Test case 4:  [3, 1, 2]                  ->  0 (or 1)
Test case 5:  [1, 1, 2]                  ->  2 (or 3)
Test case 6:  [3, 12, 1]                 ->  0 (or 1)
Test case 7:  [12, 12, 9, 4, 8]          ->  1 (or 2)
Test case 8:  [4, 4, 4, 8, 1, 2]         ->  2 (or 3)
Test case 9:  [11, 5, 11, 5, 5, 10, 13]  ->  2 (or 3)
Test case 10: [1, 1, 1, 9, 7, 9, 11, 3]  ->  0 (or 1)
Test case 11: [13, 13, 4, 1, 3]          ->  1 (or 2)
Test case 12: [13, 4, 13, 2, 3]          ->  2 (or 3)

The English name is indeed War (minus the jokers and minus the 2-and-3-beat-ace rule).

@MartinEnder also, when there is a tie, both players flip 3 cards face down, and a 4th face up. The 4th decides the winner of the round, and the face down cards are the "spoils of war". Also, doesn't the game keep going until 1 player has all the cards? I dunno if this was a local rule or not, anyone else remember this? That's how I remember playing.

@MagicOctopusUrn I remember flipping over the discard piles to continue playing until one player had it all.

@KamilDrakari yeah! That's the way I played too. I was in Louisiana growing up playing this.

@MagicOctopusUrn My experience is from Minnesota, and since we now have 2 data points I think it's safe to say all of America is the same.

@MagicOctopusUrn The way I played it was with one card face down for each played who was at war. So when the opening is 10, 10, 4, the first two players laid down a face-down card AND a face-up card. And then the two face-up cards are compared again. And the winner of the war indeed took all, both face-up and face-down. Also, because it usually takes quite a while, we continued until one player had no cards left, and whomever had the most at that moment won. But you could continue until one player has all cards.

q - 142 characters
{p:til 3;while[1<(#:)p;h:(n:(#:)p)#x;x:n _x;$[1~min h;p:$[max a:h in(2;3);$[1<(#:)(?:)h(&:)a;p(&:)h=3;p(&:)a];p(&:)h=1];p:p(&:)h=max h]];(*:)p}

Note: zero indexed.
There is no notion of reading stdin in q, so you should call it as a function:
{p:til 3;while[1<(#:)p;h:(n:(#:)p)#x;x:n _x;$[1~min h;p:$[max a:h in(2;3);$[1<(#:)(?:)h(&:)a;p(&:)h=3;p(&:)a];p(&:)h=1];p:p(&:)h=max h]];(*:)p}[1,2,3]
Pretty long, actually, but there are plenty of corner cases. It keeps a roster of active players, and consumes the list of cards in a loop. The most problematic thing is to detect the correct winner in hands like [13, 2, 3], since 3 beats 2, as normal, but it had to be duplicated to be put into the corner case.

JavaScript (ES6), 146 bytes
f=a=>(b=a.splice(0,3)).filter(m=>m-n,n=Math.max(...b.includes(1)?b.filter(m=>m<4):b)).length>1?b.indexOf(n):f([...b.map(m=>m-n?0:a.shift()),...a])

Returns a zero-based index. 127 bytes if I'm allowed the initial deal as a separate array (this also works for an arbitrary number of hands of course):
f=(b,a)=>b.filter(m=>m==n,n=Math.max(...b.includes(1)?b.filter(m=>m<4):b)).length<2?b.indexOf(n):f(b.map(m=>m-n?0:a.shift()),a)

Java 8, 257 247 bytes
int c(int[]a){int t=0,f=0,q,r=0,i=-1,l=a.length,x[];for(;++i<3;t=a[i]>t?a[r=i]:t)a[i]+=a[i]==1?f++*0+13:0;for(;i-->0;t=f<1|a[i]>3|t==3&2<a[i]?t:a[r=i]);for(f=i,x=new int[q=l<7?3:l>7?l-3:5];l>3&++i<q;)x[i]=t==a[i]|i>2?a[++f+3]:0;return l>3?c(x):r;}

-10 bytes thanks to @ceilingcat.
Ok, my challenge is harder than I thought it would be with everything in a single array like that. ;) But since it's been more than I year ago since I posted this challenge, I decided to give it a go myself. Took me quite a while with multiple work-arounds and quirks.. So it can definitely be golfed some more, but I'll look into that another time. This already took way longer than I expected..
Explanation:
Try it here.
int c(int[]a){      // Recursive method with integer-array parameter & integer return
  int t=0,f=0,q,    //  Temp integers
      r=0,          //  Result-integer
      i=-1,         //  Index-integer
      l=a.length,   //  Length of the input-array
      x[];          //  Temp array we use when there is a war
  for(;++i<3        //  Loop `i` in the range [0,3):
      ;t=           //    After every iteration, change `t` to:
         a[i]>t?    //     If the current item is larger than `t`:
          a[r=i]    //      Use the current item (and save its index in `r`)
         :          //     Else:
          t)        //      Leave `t` the same
    a[i]+=a[i]==1?  //   If the current item is a 1 (Ace/Joker):
         f++*0      //    Increase `f` by 1,
         +13        //    and change the 1 to 14 (by increasing with 13)
        :           //   Else:
         0;         //    Leave the current item the same (by increasing with 0)
  for(;i-->0;       //  Loop `i` in the range (3,0]:
    t=f<1           //   If no Joker/Ace was present
      |a[i]>3       //   Or the current item is NOT a 2 or 3
      |t==3         //   Or `t` is 3:
       &a[i]>2?     //   and the current item is NOT a 2:
        t           //    Leave `t` unchanged
      :             //   Else:
       a[r=o]);     //    Change `t` to the current item (and save its index in `r`)
  for(f=i,          //  Reset `f` to -1
      x=new int[    //  Create the temp array `x` with length:
         q=l<7?     //   If the current length is 6 or lower:
            3       //    New length after war is 3
           :l>7?    //   Else-if the current length is 8 or higher:
            l-3     //    New length after war is the current length - 3
           :        //   Else(-if current length is 7):
            5];     //    New length after war is 5
      l>3&          //  If there is a war:
          ++i<q;)   //   Loop `i` in the range [0,3):
    x[i]=t==a[i]    //    If the current item is at war,
         |i>2?      //    or the current item is after the first 3 items:
          a[++f+3]  //     Fill the new array with the correct next item
         :          //    Else:
          0;        //     Fill the item of the new array with 0
                    //     (since it won't participate in the next round)
  return l>3?       //  If there was a war:
          c(x)      //   Recursive-call with the new array
         :          //  Else:
          r;}       //   Return the index of the card that won

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


text:
Generate a "GitHub" Avatar
Background / Description
Note: as @HelkaHomba points out, the actual GitHub identicons are not actually random but based on the hash of a username
The default GitHub avatar is a 5x5-pixel image. A color is picked randomly, and then random pixels are filled in on one side (right or left, 2x5 size) using that color. Then that side is copied & flipped to the other side, across the y-axis. The pixels left over that are not filled in are #F0F0F0, or rgb(240,240,240).
The center column's pixels (1x5 size) are then randomly filled in, using the same color as previously.
Output
Note: for this challenge we will ignore the space that encloses the GitHub avatars
The program should output a 5x5 pixel image file. See http://meta.codegolf.stackexchange.com/a/9095/42499 for specifics
Examples
Note: these were obviously scaled up from 5x5 so you can see them

Good luck!

@trichoplax The output is a 5x5 pixel image, thanks. Also note the space around the 5x5 pixels (shown in the example GitHub avatars) should be excluded.

I'd suggest some smaller sample images. These take up way more space than necessary. Also the technical term for these is "identicons" and they are not actually random but based on the hash of a username (but having them random for the challenge is fine).

@HelkaHomba thank you, I added better examples.

@trichoplax thank you, I'm editing now

I assume "random pixels" means each pixel is colored or blank with 0.5 probability, independently of all other pixels on the same size. And "random color" means each RGB component is independently uniform on [0, 255]. Correct?

Trivia: You can use the identicon API to generate your own identicon, even if you have a real avatar, at https://github.com/identicons/<your_github_username>.png.

@LuisMendo It does not matter for randomness if you pick 3 uniform 256 values or one 256^3 value (if the period of the RNG is over 256^3 of course).

GitHub identicons are... based on the hash of a username Hold on a second, how can this be a hash?

I didn't feel it was a valid answer since it doesn't output an actual image, but I made a command line version using ANSI codes: https://gist.github.com/anonymous/3c879c5b01983a07fb7da7a25d778f1b!

@dorukayhan the same input always generates the same output, and you can't determine the input from the output. it's a hash

@DomHastings Displaying output on the screen is acceptable by default. I'd say that output via ANSI color codes to a console is close enough, but that's ultimately the OP's call.

Pyth - 27 bytes
.wC+Kc3O^Cm,240O256 3 15_PK

Obviously doesn't work online, but you can have it print color codes here.

Perl 5 + -M5.10.0, 77 bytes
This solution only has a 256 colour palette.
sub x{".[48;5;@{[rand>.5?$-||=rand 254:254]}m "}say$}=x,$b=x,x,$b,$}for 0..4
Try it online!
Explanation
Nothing particularly clever except perhaps:

Use $- to automatically round the colour number for use in the escape sequence, used instead of $n=0|rand 254.

MATL, 36 29 bytes
5l$rtP+!kllII$r*O16tQ/XE'a'YG

This saves the result in file a.png.
Replacing 'a' by 2 in the code displays the image (scaled up) instead of saving a file:
5l$rtP+!kllII$r*O16tQ/XE2YG

Here's an example output:

Explanation
5l$r     % 5×5 matrix of independent random values with uniform distribution
         % on the interval (0,1)
tP+!     % Duplicate, flip vertically, add, transpose. This gives a horizontally
         % symetric matrix. Center column pixels are uniformly distributed on the
         % interval (0,2). Rest have a triangular distribution on (0,2)
k        % Round down. In either of the above cases, this gives 0 and 1
         % with the same probability
llII$r   % 1×1×3 array of independent random numbers with uniform distribution
         % on (0,1). This is the foreground color.
*        % Multiply the two arrays with broadcast. Gives a 5×5×3 array. Ones in the
         % 5×5 array become the random foreground color. Zeros remain as zeros.
O        % Push 0
16tQ/    % 16, duplicate, add 1, divide: gives 16/17, or 240/255
XE       % Replace 0 by 16/17: background color
'a'      % Push file name
YG       % Write image to that file

Actually, 53 bytes
3'≡*;╗`┘#8╙r-J┌`MΣ╝5`3"2rJ└"£n3╟;RdX+Σ`nkΣ"P6 5 5 255

Try it online!
Actually is bad at string processing. I think I've mentioned that before. This program outputs a P6 netpbm image using CP437, like the following:
P6 5 5 255
εεεεεεå♠ƒεεεεεεå♠ƒå♠ƒεεεå♠ƒå♠ƒεεεεεεεεεεεεεεεεεεεεεå♠ƒεεεεεεå♠ƒå♠ƒå♠ƒå♠ƒå♠ƒ

This can be converted to a PNG using ImageMagick:
seriously -f prog.srs | convert - out.png

Scaled up PNG version:

Explanation:
3'≡*;╗`┘#8╙r-J┌`MΣ╝5`3"2rJ└"£n3╟;RdX+Σ`nkΣ"P6 5 5 255
3'≡*                                                   push "≡≡≡" (char 240, 3 times)
    ;╗                                                 save a copy to reg0
      `┘#8╙r-J┌`M                                      map:
       ┘#                                                cp437 char code, as list ([240])
         8╙r-J                                           random value in range(2**8) that is not 240
              ┌                                          char code
                 Σ╝                                    concatenate, push to reg1
                   5`3"2rJ└"£n3╟;RdX+Σ`n               do this 5 times:
                     3"2rJ└"£n                           do this 3 times:
                       2rJ└                                randomly pick 0 or 1, push the value in that register
                              3╟                         push the top 3 items to a list
                                ;RdX+                    duplicate, reverse, discard first value, append (mirror the list)
                                     Σ                   concatenate
                                       kΣ              push stack as list, concatenate
                                         "P6 5 5 255   prepend header

Sorry, but "P6 netpbm" is not in the specified list of allowed image formats, so you should probably add the length of the ImageMagick command line to your answer. :/

@ZeroOne It is an allowed image format - it's a ppm image.

I stand corrected! Sorry about that, and thanks for the clarification. Looks like I need to do some learning on image formats. :)

Mathematica, 105 102 98 94 bytes
c=1~RandomReal~3;r@l_:={c,4{4,4,4}/17}~RandomChoice~{l,5};Image[Join[#,r@1,Reverse@#]&@r@2]

 is the Transpose operator.
Edit 1: Saved 3 bytes by replacing Round + RandomReal with RandomInteger
Edit 2: Saved 4 bytes by replacing RandomInteger with RandomChoice
Edit 3: Saved 4 bytes by replacing RandomColor and GrayLevel with RandomReal

Python, 167 164 155 148 bytes
Output as ppm
from random import*
print"P3 5 5 255"
C,P=choice,[[240]*3,[randint(0,255)for _ in"RGB"]]
exec"a,b=C(P),C(P);print' '.join(map(str,a+b+C(P)+b+a));"*5

Edit1: range(5) to " "*5
Edit2: shoved a byte at the first print
Edit3: Replaced list comprehension with map since only str(p) was used
Edit4: exec""*5 instead for _ in " "*5:

Some improvement over old, string-based code:
from random import*
print "P3 5 5 255"
j,c,a=' '.join,choice,['']*5
P=["240 "*3,j([str(randint(0,255))for _ in"RGB"])]
for _ in a:a=[c(P)]*5;a[1]=a[3]=c(P);a[2]=c(P);print j(a)

You could save a few by replacing the newlines with a space in the header.  The spec just calls for whitespace.  http://netpbm.sourceforge.net/doc/ppm.html

MATLAB, 102 bytes
Hi, this is my matlab solution:
p=@(x)(imwrite(floor(randi(2,5,2)*[eye(2) ones(2,1)./2 fliplr(eye(2))]),[0.9412*[1 1 1];rand(1,3)],x))

The input x of the function is the name of the output file. For example:
p('output.png')

produces a png image called 'output.png'.
Here the results of some executions of this code.

Swift 2.3, 593 585 bytes
var t = 0,g = UIGraphicsGetCurrentContext(),c = UIColor(hue:CGFloat(drand48()),saturation:1,brightness:1,alpha:1).CGColor
srand48(time(&t))
UIGraphicsBeginImageContext(CGSizeMake(5,5))
for x in 0..<3 {for y in 0..<5 {CGContextSetFillColorWithColor(g,drand48()>0.5 ? c : UIColor.whiteColor().CGColor)
var r = [CGRect(x:x,y:y,width:1,height:1)]
if x<2 {let m = x==0 ? 4 : 3;r.append(CGRect(x:m,y:y,width:1,height:1))}
CGContextFillRects(g,&r,r.count)}}
let i = UIGraphicsGetImageFromCurrentImageContext()
UIImagePNGRepresentation(i)!.writeToURL(NSURL(string:"/a/a.png")!,atomically:true)

Update
Swift 3, 551 bytes
var t = 0,g = UIGraphicsGetCurrentContext()!,c = UIColor(hue:CGFloat(drand48()),saturation:1,brightness:1,alpha:1).cgColor
srand48(time(&t))
UIGraphicsBeginImageContext(CGSize(width:5,height:5))
for x in 0..<3 {for y in 0..<5 {g.setFillColor(drand48()>0.5 ? c : UIColor.white().cgColor)
var r = [CGRect(x:x,y:y,width:1,height:1)]
if x<2 {let m = x==0 ? 4 : 3;r.append(CGRect(x:m,y:y,width:1,height:1))}
g.fill(&r,count: r.count)}}
let i = UIGraphicsGetImageFromCurrentImageContext()!
try!UIImagePNGRepresentation(i)!.write(to: URL(string:"/a/a.png")!)

I'm at WWDC and just got the Xcode 8 beta with Swift 3.  Apple made some of the CoreGraphics calls more "Swifty," and I am able to reduce the bytecount.
Swift 2 code Ungolfed:
var t = 0
srand48(time(&t))

UIGraphicsBeginImageContext(CGSizeMake(5,5))
let context = UIGraphicsGetCurrentContext()
let color = UIColor(hue: CGFloat(drand48()),saturation:1,brightness:1,alpha:1).CGColor

for x in 0..<3 {
    for y in 0..<5 {
        CGContextSetFillColorWithColor(context, drand48() > 0.5 ? color : UIColor.whiteColor().CGColor)
        var rects = [CGRect(x:x,y:y,width:1,height:1)]

        if x < 2 {
            let mirror = x==0 ? 4 : 3
            rects.append(CGRect(x: mirror, y: y, width: 1, height: 1))
        }

        CGContextFillRects(context, &rects, rects.count)
    }
}

let image = UIGraphicsGetImageFromCurrentImageContext()
UIImagePNGRepresentation(image)!.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains:.UserDomainMask).first!.URLByAppendingPathComponent("a.png"), atomically:true)

This answer assumes UIKit is available and uses the Cocoa Touch framework.
Some example output images:

I know I can't compete with most of the other answers but I wanted to give this a shot as a personal challenge.  There is definitely room for improvement with this answer, but I think it will be hard to get this down below a few hundred bytes due to the length of the UIKit and CoreGraphics image writing method names.  I opted to write an actual PNG file rather than PPM values as an exercise for myself, but shorter answers would definitely be possible if I used the PPM format.
I already start out as a loss by having to declare a variable to seed srand48 with time.  I chose this over arc4random() or arc4random_uniform() because ultimately I would lose more bytes with those.  I seed the rng to use drand48 to generate a random color and pick when to write a color to a pixel.
CGSize vs CGSizeMake and CGRect vs CGRectMake:
I switch between the inline C API functions and their Swift extensions to find the shortest constructor for each.  CGSizeMake ends up being shorter than CGSize(), and CGRectends up being shorter than CGRectMake():
CGSizeMake(5,5)
CGSize(width:5,height:5)

CGRect(x:x,y:y,width:1,height:1)
CGRectMake(CGFloat(x),CGFloat(y),1,1)

I would have to create CGFloats x and y due to the nature of the for loop.  I'm really not thrilled with the 2D loop and if equality checks, but I was really struggling to find a shorter way.  There's definitely room to shave off a few bytes here.
Calling CGContextFillRects with an array of CGRect structs is cheaper than calling CGContextFillRect twice with two different values, so I save a few bytes with the array and pointer.
I also save 27 bytes by not calling UIGraphicsEndImageContext().  While this would normally be a "bug" in production code, it's not necessary for this toy program.
Colors:
Colors are also a pain to deal with, since I'm creating UIColor objects but need to write a CGColor opaque type to each pixel.  The shortest code I found to create a random color was to use the UIColor constructor and get the CGColor from that UIColor.  Same with white.  If I were using the Cocoa framework instead of Cocoa Touch, I might be able to save some bytes using CGColorGetConstantColor(), but unfortunately that method is unavailable in the Cocoa Touch SDK.
Writing to to file:
Writing to a file takes almost 100 bytes.  I'm not sure how to even go about optimizing this.  On some systems depending on your permissions, you may need to use the Documents directory which would be even longer:
UIImagePNGRepresentation(i)!.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains:.UserDomainMask).first!.URLByAppendingPathComponent("a.png"), atomically:true)

Definitely open to further optimizations.
Edit 1: Saved a few bytes by rearranging some variable declarations.

Dyalog APL, 43 42 bytes
'P3',5 5 256,∊(3⍴240)(?3⍴256)[⌈(⊢+⌽)?5 5⍴0]
'P3',5 5a,∊(3⍴240)(?3⍴a←256)[⌈(⊢+⌽)?5 5⍴0]
Right to left:
?5 5⍴0 generates a 5×5 matrix of random numbers between 0 and 1 (but never 0 or 1)
(⊢+⌽) is a train that adds the matrix with its reflection
⌈ ceiling, returns 1 or 2 for each element
(3⍴240)(?3⍴256) colours - white-ish and a random one
[ ] use each element of the matrix as an index in colours
'P3',5 5 256,∊ flatten and add header

PHP, 236 bytes
I know this is an old challenge but I just like to challenge myself.
$o=imagecreate(5,5);$t=imagecolorallocate;$r=rand;for($c=[$t($o,240,240,240),$t($o,$r(0,255),$r(0,255),$r(0,255))];$y++<5;)for($x=-2,$a=[];$x<3;)imagesetpixel($o,$x+2,$y,isset($a[$v=abs($x++)])?$a[$v]:($a[$v]=$c[$r(0,1)]));imagepng($o);

Ungolfed:
// Store these frequently used functions
$t=imagecolorallocate;
$r=rand;

// Create 5x5 image
$o=imagecreate(5, 5);

// Define array of the possible colors
$c=[$t($o,240,240,240),$t($o,$r(0,255),$r(0,255),$r(0,255))];

// Loop over y axis
for($y=0;$y++<5;) {

    // This stores values for colors used in the current row indexed by the absolute value of x starting from -2
    $a = [];

    // Loop over x axis
    for($x=-2;$x<3;) {

        // Set a pixel of a random color for current coordinate. If it exists in the array, use the array value.
        imagesetpixel($o,$x+2,$y, isset($a[$v=abs($x++)]) ? $a[$v] : ($a[$v]=$c[rand(0,1)]) );
    }

    // Empty the array
    $a = [];
}

// Output as PNG
imagepng($o);

Sample Output:

Javascript ES6, 296 bytes
Note: does not produce a file, draws to a canvas.
See it in action in this JS Fiddle.
s=20;W='#fff';M=Math;R=M.random;ctx=document.getElementById('c').getContext('2d');cr=`#${M.floor(R()*16777215).toString(16).slice(0,3)}`;f=Array(5).fill();a=f.map((_,i)=>f.map((_,j)=>R()*2|0));a.map((c,x)=>c.map((v,y)=>{ctx.fillStyle=y>=3?c[y==3?1:0]?cr:W:c[y]?cr:W;ctx.fillRect(y*s,x*s,s,s);}));

Welcome to the site! :)

After running it a few times it generated this twice - a single black pixel in the top left, and nothing else. Not sure if this is a problem with the code or the fiddle.

Right – the code to generate the random hex value was buggy. Updated the link in the answer!

Uiua SBCS, 36 35 bytes
&ims≡⍉⍉⊂⇌↘1.⊏⁅⊞⋅⋅⚂⊚3⊚5⊟⚂_⚂_⚂▽3 0.94

Try it!
&ims≡⍉⍉⊂⇌↘1.⊏⁅⊞⋅⋅⚂⊚3⊚5⊟⚂_⚂_⚂▽3 0.94
                            ▽3 0.94  # gray color
                       ⚂_⚂_⚂         # random color
                      ⊟              # couple
             ⁅⊞⋅⋅⚂⊚3⊚5               # random 3x5 binary matrix
            ⊏                        # select
        ⇌↘1.                         # duplicate, drop first row, reverse
       ⊂                             # join
    ≡⍉⍉                              # rotate image
&ims                                 # display image

Ruby, 132 bytes
Outputs a PPM image.
c=(1..3).map{rand 256}
puts"P3 5 5 255",(1..15).map{rand 2}.join.gsub(/(..)./){$&+$1.reverse}.gsub(/./){($&==?0?c:["240"]*3)*" "+$/}

Attempt This Online!


text:
Faro shuffle an array
A Faro shuffle is a technique frequently used by magicians to "shuffle" a deck. To perform a Faro shuffle you first cut the deck into 2 equal halves then you interleave the two halves. For example
[1 2 3 4 5 6 7 8]

Faro shuffled is
[1 5 2 6 3 7 4 8]

This can be repeated any number of times. Interestingly enough, if you repeat this enough times, you will always end up back at the original array. For example:
[1 2 3 4 5 6 7 8]
[1 5 2 6 3 7 4 8]
[1 3 5 7 2 4 6 8]
[1 2 3 4 5 6 7 8]

Notice that 1 stays on the bottom and 8 stays on the top. That makes this an outer-shuffle. This is an important distinction.
The Challenge
Given an array of integers A, and a number N, output the array after N Faro shuffles. A may contain repeated or negative elements, but it will always have an even number of elements. You can assume the array will not be empty. You can also assume that N will be a non-negative integer, although it may be 0. You can take these inputs in any reasonable manner. The shortest answer in bytes wins!
Test IO:
#N, A,                                              Output
1,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 5, 2, 6, 3, 7, 4, 8]
2,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 3, 5, 7, 2, 4, 6, 8]
7,  [-23, -37, 52, 0, -6, -7, -8, 89]               [-23, -6, -37, -7, 52, -8, 0, 89]
0,  [4, 8, 15, 16, 23, 42]                          [4, 8, 15, 16, 23, 42]
11, [10, 11, 8, 15, 13, 13, 19, 3, 7, 3, 15, 19]    [10, 19, 11, 3, 8, 7, 15, 3, 13, 15, 13, 19]

And, a massive test case:
23, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]

Should output:
[1, 30, 59, 88, 18, 47, 76, 6, 35, 64, 93, 23, 52, 81, 11, 40, 69, 98, 28, 57, 86, 16, 45, 74, 4, 33, 62, 91, 21, 50, 79, 9, 38, 67, 96, 26, 55, 84, 14, 43, 72, 2, 31, 60, 89, 19, 48, 77, 7, 36, 65, 94, 24, 53, 82, 12, 41, 70, 99, 29, 58, 87, 17, 46, 75, 5, 34, 63, 92, 22, 51, 80, 10, 39, 68, 97, 27, 56, 85, 15, 44, 73, 3, 32, 61, 90, 20, 49, 78, 8, 37, 66, 95, 25, 54, 83, 13, 42, 71, 100]

Can the array contain zero elements?

@LeakyNun We'll say no, you don't have to handle zero elements.

Related. Related. Related.

Related

Any permutation of a finite set, if repeated enough times, will end up back where it started; this isn't special to Faro shuffles.

I guess we can assume that the elements are unique?

@titus No. A may contain negative or repeated elements.

05AB1E, 5 bytes
Code:
F2äø˜

Explanation, input: N, array:
F      # Do the following N times
 2ä    # Split the array into 2 pieces
   ø   # Zip
    ˜  # Deep flatten

Uses the CP-1252 encoding. Try it online!.

Damn, I was too slow!

vim, 62 59 54
qrma50%mb:norm@q<cr>ggqOjdd'apjma'b@q<esc>0"qDJ<C-a>D@"i@r<esc>xxdd@"

Wow. This is possibly the hackiest thing I've written for PPCG, and that's saying something.
Input is taken as N on the first line followed by the elements of the array, each on its own line.
qr         first, we're going to record the contents of the @r macro. this is
             the macro which does the faro-shuffle operation.
  ma       set the mark 'a at the beginning of the file
  50%      move to the 50% point of the file (i.e. halfway down)
  mb       set another mark here
  :norm@q  evaluate the recursive macro @q. we'll get to what that does later,
             but the interesting part here is that it's :norm@q instead of @q.
             this is because a recursive macro terminates at the end of the
             file, which means when @q terminates, @r would also abort, which
             would make calling it with a count impossible. running @q under
             :norm prevents this.
  gg       move back to the top of the file for the next iteration
q          end recording
O          now we're inserting contents of the @q macro, the recursive part
             we can't record it directly because it's destructive
  j        move to line directly below mark 'b (which was just set before @q)
  dd       delete this line and bring it...
  'ap      up after mark 'a (which starts on line 1, bringing the N/2th line
             directly below line 1, aka line 2)
  jma      replace mark 'a one line below this so that the next time we call
             'ap, the line from the second half is interleaved with the lines
             from the first half
  'b       jump back to mark 'b (remember, 'b is the last line of the first
             half of the file, originally reached via 50%)
  @q       call ourselves, causing the macro to run until hitting EOF
0"qD       delete this into register "q
J          delete the empty line that remains
<C-a>      here's another interesting bit: we want to run @r N times. but 0@r
             means "go to column 0, and then run @r once." so we have to
             increment the input number...
D@"        and then *that* many times...
  i@r        insert @r...
xx         ... and finally, delete two characters, which is the extra @r from
             the increment
dd         delete the sequence of @rs into the "" register...
@"         and run it!

I actually possibly found several vim bugs while writing this answer:

recording macros is not possible within other macros (when setting their text manually, not with q) or within :*maps.
:let @a='<C-v><cr>'<cr>i<C-r>a outputs two newlines, not one, for whatever arcane reason.

I might investigate those further later.
Thanks to Dr Green Eggs and Ham DJ for 3 bytes!

This is beautiful and horrifying. I probably don't have enough patience to do this in vim. :P Also, you can take off 2 bytes by doing "rck instead of vgg"rc, and you can take off another 5 by doing dw@"i@r<esc> instead of AA@R<C-v><esc><esc>0D@"

@DrGreenEggsandHamDJ Can't do that first one because that grabs a trailing newline as well, but that second optimization works. Thanks!

I wrote a different approach that almost works really well, but it gets tripped up if not every line is the same length. If someone can salvage it, be my guest: Try it online!

Python, 68 57 bytes
f=lambda n,x:n and f(n-1,sum(zip(x,x[len(x)/2:]),()))or x

Thanks to @Sp3000 for golfing off 11 bytes!
Test it on Ideone.

Python 2, 59 bytes
def f(n,L):exec"l=len(L)/2;L=(L+L[1:]*~-l)[::l];"*n;print L

A different approach, slightly longer than the other Python answers. Only works for positive even numbers of elements.
e.g. for 1, [1,2,3,4,5,6,7,8], take the array and append len(L)/2-1 copies of itself minus the first element, e.g.
[1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8]

Then take every len(L)/2th element.
[1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8]
 ^       ^       ^       ^       ^       ^       ^       ^

Haskell, 62 bytes
0!a=a
n!a|s<-length a=(n-1)![a!!mod(div(s*i+i)2)s|i<-[0..s-1]]

Let s = 2·t be the size of the list. The i-th element of the new list is obtained by taking the -th element of the old list, zero-indexed, modulo s.
Proof: if i = 2·k is even, then

and if i = 2·k + 1 is odd, then

Thus the values used for indexing are 0, t, 1, t + 1, 2, t + 2, …

Pyth - 8 7 bytes
saved 1 byte thanks to @issacg
usCc2GE

Try it online here.

Hmm... there must be something wrong in the Jelly answer if Pyth beats Jelly.

Swap the input order and remove the Q to save a byte. There must be something wrong with the Pyth answer if Jelly beats Pyth. :)

@isaacg darn, could've sworn i'd tried that before. Why does that work? shouldn't that hook onto the default for u with None and do fixed point?

@Maltysen You're right, I think it only happened to work on the one test case I tried. Sorry about that.

@LeakyNun Thanks to @Dennis and @issacg, Pyth and Jelly are now equal (7 bytes). ;D

J - 12 bytes
Adverb (!) taking number of shuffles on the left and the array to shuffle on the right.
/:#/:@$0,#^:

The J parser has rules for writing tacit adverbs, but they have very low precedence: if you want to use a train of verbs as a left argument, you can omit an otherwise necessary set of parentheses. So the above is actually short for (/:#/:@$0,#)^:, which takes the number of shuffles on the left as an adverb, and then becomes a monadic function taking the array to shuffle on the right.
That said, we shuffle as follows. # is the length of the array, so 0,# is a two element list: 0 followed by something nonzero. Then #/:@$ replicates that into a list as long as the input array, and takes its sort vector.
The sort vector of a list is the information for how to sort the list: the (0-based) invdex of the smallest element, followed by the index of the next-smallest, and so on. For example, the sort vector of 0 1 0 1 ... will thus be 0 2 4 ... 1 3 5 ....
If J were now to sort this sort vector, it would Faro-shuffle it; but that would be trivial, since we'd get 0 1 2 3 ... back. So we use dyadic /: to sort the input array as if it were 0 2 4 ... 1 3 5 ..., which Faro-shuffles it.
Example usage below. Try it yourself at tryj.tk!
   1 (/:#/:@$0,#^:) 1 2 3 4 5 6 7 8
1 5 2 6 3 7 4 8

   f =: /:#/:@$0,#^:

   2  f  1 2 3 4 5 6 7 8
1 3 5 7 2 4 6 8

   7  f  _23 _37 52 0 _6 _7 _8 89   NB. "negative 1" is spelled _1
_23 _6 _37 _7 52 _8 0 89

   1  f  0 0 0 0 1 1 1              NB. odd-length lists
0 1 0 1 0 1 0

Jelly, 9 7 bytes
2 bytes thanks to Dennis!
œs2ZFð¡

Try it online!
Explanation
œs2ZFð¡  Main dyadic chain. Arguments: x,y
      ¡  Repeat the following y time:
œs2          Split into two.
   Z         Transpose.
    F        Flatten.

Previous 9-byte version:
œs2ZF
Ç⁴¡

Try it online!

MATL, 11 bytes
w:"tn2/e!1e

Thanks to @Dennis for a correction
Try it online!
Explanation
w         % Take the two inputs N and A. Swap them
:         % Generate [1 2 ... N]
"         % Repeat N times
  tn2/    %   Duplicate A. Number of elements divided by 2
  e       %   Reshape to that number of rows
  !       %   Transpose
  1e      %   Reshape to one row
          % End (implicit)
          % Display (implicit)

Why is the w necessary?

@David That was the correction. Without it, for N = 0 the loop is not entered and the second input is not taken

Ahh that's annoying!

J, 22 19 17 bytes
3 bytes thanks to @Gareth.
2 bytes thanks to @algorithmshark.
-:@#({.,@,.}.)]^:

Usage
>> f =: -:@#({.,@,.}.)]^:
>> 2 f 1 2 3 4 5 6 7 8
<< 1 3 5 7 2 4 6 8

Where >> is STDIN and << is STDOUT.
Previous 22-byte version:
({~[:,/@|:@i.2,-:@#)^:

Usage
>> f =: ({~[:,/@|:@i.2,-:@#)^:
>> 2 f 1 2 3 4 5 6 7 8
<< 1 3 5 7 2 4 6 8

Where >> is STDIN and << is STDOUT.

Because of J's parsing rules, you can drop the outer parens for 2 chars.

Alternative using a transposed index {~2,@|:@i.@,-:@#^: for 18 bytes.

Another alternative that uses 17 bytes also [:,@|:]]\~_2%~#^:

@milesI believe ,@|:@$~2,-:@#^: works for 15 bytes

JavaScript (ES6), 61 51 bytes
(n,a)=>[...a].map((e,i)=>a[(i<<n)%~-a.length||i]=e)

Modifies the input array in place and returns a copy of the original array. If this is unacceptable, &&a can be suffixed to return the modified array. Only works for small values of n due to the limitations of JavaScript's integer arithmetic. 61 60 byte recursive version that works with larger n, based on @Lynn's formula:
f=(n,a,l=a.length)=>n?f(n-1,a.map((_,i)=>a[(i*-~l>>1)%l])):a

Julia, 45 42 bytes
a\n=n>0?reshape(a,endof(a)÷2,2)'[:]\~-n:a

Try it online!
How it works
We (re)define the binary operator \ for this task. Let a be an array and n a non-negative integer.
If n is positive, we shuffle the array. This is achieved by reshaping it into a matrix of length(a) ÷ 2 rows and two columns. ' transposes the resulting matrix, creating of two rows, then flattening the result with [:]. Since Julia stores matrices in column-major order, this interleaves the two rows.
Afterwards, we call \ recursively with the shuffled a and n - 1 (~-n) as arguments, thus performing additional shuffles. Once n reaches 0, we return the current value of a.

APL, 23 21 chars
({⊃,/⍵(↑,¨↓)⍨2÷⍨⍴⍵}⍣N)A

Without the assumption (Thanks to Dennis) and 1 char shorter:
({{∊,⌿2(2÷⍨≢⍵)⍴⍵}⍣⎕)⎕

Try it on online.

Mathematica 44 bytes
With 4 bytes saved thanks to @miles.
Riffle@@TakeDrop[#,Length@#/2]&~Nest~##&

Riffle @@ TakeDrop[#, Length@#/2] &~Nest~## &[list, nShuffles] splits the list into two equal sublists and shuffles (Riffles) them.

 Riffle @@ TakeDrop[#, Length@#/2] &~Nest~## &[Range@8, 1]

{1, 5, 2, 6, 3, 7, 4, 8}

Riffle @@ TakeDrop[#, Length@#/2] &~Nest~## &[Range@100, 23]

{1, 30, 59, 88, 18, 47, 76, 6, 35, 64, 93, 23, 52, 81, 11, 40, 69,
98, 28, 57, 86, 16, 45, 74, 4, 33, 62, 91, 21, 50, 79, 9, 38, 67, 96,
26, 55, 84, 14, 43, 72, 2, 31, 60, 89, 19, 48, 77, 7, 36, 65, 94, 24,
53, 82, 12, 41, 70, 99, 29, 58, 87, 17, 46, 75, 5, 34, 63, 92, 22,
51, 80, 10, 39, 68, 97, 27, 56, 85, 15, 44, 73, 3, 32, 61, 90, 20,
49, 78, 8, 37, 66, 95, 25, 54, 83, 13, 42, 71, 100}

Using TakeDrop we can find a solution using 40 bytes as Riffle@@TakeDrop[#,Length@#/2]&~Nest~##& while also taking the sequence ## to be parsed as additional arguments to Nest.

@miles.  Very nice use of TakeDrop.  And it is better to use ## to insert the sequence.

java, 109 bytes
int[]f(int[]a,int n){for(int x,q=a.length,d[];0<n--;a=d){d=new int[q];for(x=0;x<q;x++)d[(2*x+2*x/q)%q]=a[x];}return a;}
Explanation:
There is a pattern to how the elements move when they are faro shuffled:
let x be the original index
let y be the new index
let L be the length of the array

y is double x
if x is greater than or equal to half of L then increment y
keep y within the array's bounds

or as code: y=(2*x+x/(L/2))%L
This assumes that indicies start at 0. Here's the code further explained:
int[] faroShuffle( int[] array, int numberOfShuffles ) {
    //repeat the faro shuffle n times
    for( int index, length=array.length, destination[]; 0<numberOfShuffles--; array=destination ) {
        //new array to copy over the elements
        destination=new int[length];
        //copy the elements into the new array
        for( index=0; index<length; index++ )
            destination[(2*index+2*index/length)%length]=array[index];
        //at the end of each loop, copy the reference to the new array and use it going forward
    }
    return array;
}

see ideone for test cases

I know it's been more than a year, but you can golf a few parts: void f(int[]a,int n){for(int x,q=a.length,d[];0<n--;a=d)for(d=new int[q],x=0;x<q;)d[(2*x+2*x/q)%q]=a[x++];} (107 bytes - your current answer is 119 btw, not 109, so -12 bytes). Since you modify the input array, there is no need to return it, so you can change it to a void to reduce bytes. Oh, and if you convert to a Java 8 lambda with currying you could make it even shorter: a->n->{for(int x,q=a.length,d[];0<n--;a=d){d=new int[q];for(x=0;x<q;x++)d[(2*x+2*x/q)%q]=a[x];}} (96 bytes)

Pyke, 7 bytes
VDlec,s

Try it here!
V       - Repeat N times:
 D      -  a,b = a (2nd arg first time round)
  le    -  b = len(b)//2
    c   -  a = chunk(a,b)
     ,  -  a = zip(*a)
      s -  a = sum(a, [])

Actually, 15 bytes
`;l½≈@│t)HZ♂i`n

Try it online!
Explanation:
`;l½≈@│t)HZ♂i`n
`            `n  do the following n times:
 ;l½≈              push half the length of the array
     @             swap
      │            duplicate entire stack
       t)H         last L//2 elements, first L//2 elements
          Z♂i      zip, flatten each element

Prolog, 116 bytes
a([],[[],[]]).
a([H,I|T],[[H|U],[I|V]]):-a(T,[U,V]).
f(X,0,X).
f(X,N,Y):-N>0,M is N-1,f(X,M,Z),a(Z,[A,B]),append(A,B,Y).

Usage
?- f([1,2,3,4,5,6,7,8],2,X).
X = [1, 5, 2, 6, 3, 7, 4, 8] ;
false.

Perl 5 -lan, 52 bytes
$a=<>;@F=map@F[$_,@F/2+$_],0..$#F/2while$a--;say"@F"

Try it online!

PHP, 98 bytes
function($a,$n){while($n--)for($z=count($a)/2;$z;)array_splice($a,$z--,0,array_pop($a));return$a;}

Try it online.


text:
Determine the winner of a game of War
The card game War is interesting in that the final outcome is entirely determined by the initial arrangement of the deck, so long as certain rules are followed for the order in which cards are picked up from the playing field and moved to decks. In this challenge, there will only be 2 players, simplifying things greatly.
The Game

Each player is dealt a deck of 26 cards.
Each player places the top card in their deck face-up. The player with the higher-ranking card (Ace > King > Queen > Jack > 10 > 9 > 8 > 7 > 6 > 5 > 4 > 3 > 2) wins the round, and places their card on top of their opponent's card, flips them over, and adds them to the bottom of their deck (so their winning card is on the bottom of the deck, and the other player's losing card is just above it). This is done until one of the players runs out of cards.

If the cards are of equal rank, then each player places the top 2 cards of their deck face-up on top of their previous card (so that the card that was on top of the deck is the second card in the stack, and the card that was second-from-top is on top). Then, the ranks (of the top card of each stack) are compared again, and the winner places their entire stack on top of the loser's entire stack, turns the stack upside-down, and places it on the bottom of their deck. If there is another tie, more cards are played in the same way, until a winner is chosen or one player runs out of cards.

If at any point one of the players needs to draw a card from their deck, but their deck is empty, they immediately lose the game.
The Challenge
Given two lists of cards in the players' decks, in any convenient format, output a truthy value if Player 1 wins, and a falsey value if Player 2 wins.
For convenience, a 10 card will be represented with a T, and face cards will be abbreviated (Ace -> A, King -> K, Queen -> Q, Jack -> J), so that all cards are one character long. Alternatively, ranks may be represented with decimal integers 2-14 (Jack -> 11, Queen -> 12, King -> 13, Ace -> 14) or hex digits 2-E (10 -> A, Jack -> B, Queen -> C, King -> D, Ace -> E). Since suits don't matter, suit information will not be given.

You may assume that all games will terminate at some point (though it may take a very long time), and one player will always run out of cards before the other.
Each player places cards simultaneously, and one card at a time, so there is never any ambiguity about which player ran out of cards first.

Test Cases
The test cases use 23456789ABCDE to represent the ranks (in ascending order).
D58B35926B92C7C4C7E8D3DAA2, 8E47C38A2DEA43467EB9566B95 -> False
669D9D846D4B3BA52452C2EDEB, E747CA988CC76723935A3B8EA5 -> False
5744B95ECDC6D325B28A782A72, 68394D9DA96EBBA8533EE7C6C4 -> True
87DB6C7EBC6C8D722389923DC6, E28435DBEBEA543AA47956594A -> False
589EAB9DCD43E9EC264A5726A8, 48DC2577BD68AB9335263B7EC4 -> True
E3698D7C46A739AE5BE2C49286, BB54B7D78954ED526A83C3CDA2 -> True
32298B5E785DC394467D5C9CB2, 5ED6AAD93E873EA628B6A4BC47 -> True
B4AB985B34756C624C92DE5E97, 3EDD5BA2A68397C26CE837AD48 -> False
9A6D9A5457BB6ACBC5E8D7D4A9, 73E658CE2C3E289B837422D463 -> True
96E64D226BC8B7D6C5974BAE32, 58DC7A8C543E35978AEBA34D29 -> True
C2978A35E74D7652BA9762C458, 9A9BB332BE8C8DD44CE3DE66A5 -> False
BEDB44E947693CD284923CEA82, 8CC3B75756255A683A6AB9E7DD -> False
EEDDCCBBAA8877665544332299, EEDDCCBBAA9988776655443322 -> False
EEDDCCBBAA9988776655443322, DDCCBBAA9988776655443E3E22 -> True

Reference Implementation
This reference implementation is written in Python 3, and takes input in the same format as the test cases (except separated by a newline instead of a comma and a space).
#!/usr/bin/env python3

from collections import deque

p1, p2 = [deque(s) for s in (input(),input())]
print(''.join(p1))
print(''.join(p2))

try:
    while p1 and p2:
        p1s = [p1.popleft()]
        p2s = [p2.popleft()]
        while p1s[-1] == p2s[-1]:
            p1s.append(p1.popleft())
            p2s.append(p2.popleft())
            p1s.append(p1.popleft())
            p2s.append(p2.popleft())
        if p1s[-1] > p2s[-1]:
            p1.extend(p2s+p1s)
        else:
            p2.extend(p1s+p2s)
except IndexError:
    pass
finally:
    print(len(p1) > 0)

Related

For a deck of cards 1, 2, 3 the game has no end as you keep winning your opponent's 1. Is that a quirk of having an odd number of cards?

@Neil What deck of cards has a 1?

@Suever Sorry, I didn't think too hard, I just picked the first three different numbers that came in to my head. Just pick any three cards where the first is the lowest.

@Neil Just giving you a hard time :) Point taken!

@Neil I believe that is the case - the only examples I can think of have players having odd numbers of cards. Since in a standard 52-card deck, each player has 26 cards, the game should end at some point. I added in the disclaimer just in case there is some case that I'm missing where the game won't ever end.

I just ran 5744B95ECDC6D325B28A782A72, 68394D9DA96EBBA8533EE7C6C4 by hand and Player 2 won (Player 1 lost his last ace on move 115). What am I doing wrong?

@Neil Here is a detailed game summary for those initial decks. Perhaps you will be able to spot your mistake by reading through it.

Oh, I overlooked the bit about the top two cards. (I was taught a similar game without that rule.)

@Neil When I originally learned War (back when I was a wee little lad), I learned a variant that involved flipping 4 cards during a war, and comparing them in turn. The first player to have a higher-ranked card won all 8 cards. Unfortunately, that causes games to be very quick, and not very interesting. Going by what Wikipedia calls the normal rules (flipping two cards each and comparing the second) makes for more interesting games, with more back-and-forth, and is much easier to program.

Actually I had confused this with a completely different game. Maybe I should post that game as a challenge! heads off to sandbox

JavaScript (ES6), 134 bytes

f=([p,...r],[q,...s],t=[],u=[],v)=>!q||p&&(v|p==q?f(r,s,[...t,p],[...u,q],!v):p>q?f([...r,...u,q,...t,p],s):f(r,[...s,...t,p,...u,q]))

Player 1's cards: <input id=p>

Player 2's cards: <input id=q>

<input id=o type="checkbox"> Player 2 loses

Return undefined if Player 2 wins, true otherwise. Accepts comparable iterators, usually arrays of integers or strings of hex characters. Answer is composed of over 22% of . characters, which I think must be a record for me.

I don't seem to get the right results when I try this with the test cases.  See https://jsfiddle.net/xbq5xzco/

@ChuckMorris Sorry about that, I'd overlooked one of the rules. Should be fixed now.

@Mego Try again, I've just updated it.

Everything seems to check out now.

OK, now I'm impressed!

Python, 160 (155?) bytes
f=lambda x,y,z=1:f(*((x,y,z+2),(x[z:]+y[:z]+x[:z],y[z:]),(x[z:],y[z:]+x[:z]+y[:z]))[(x[z-1]>y[z-1])+(x[z-1]<y[z-1])*2])if len(y)>z<len(x)else len(x)>len(y)

This solution is theoretically valid, but it require the default python maximum recursion depth to be increased for some of the test cases.
The second solution is 5 bytes longer, but work for all the test cases.
f=lambda x,y,z=1:(f(x,y,z+2)if x[z-1]==y[z-1]else f(x[z:]+y[:z]+x[:z],y[z:])if x[z-1]>y[z-1]else f(x[z:],y[z:]+x[:z]+y[:z]))if len(y)>z<len(x)else len(x)>len(y)

Edit: Ungolfed solution 1:
def f(x,y,z=1):
    if len(y)<z>len(x):
        return len(x)>len(y)
    else:
        return f(*(
            (x,y,z+2),
            (x[z:],y[z:]+x[:z]+y[:z]),
            (x[z:]+y[:z]+x[:z],y[z:])
        )[(x[z-1]>y[z-1])+(x[z-1]<y[z-1])*2])

Since IronPython will run the first solution fine (the default recursion depth is unlimited), I'm going to say that the first solution is valid.

Python, 261 to 265 bytes
def f(a,b):
 if a==""or b=="":return b==""
 p=a[0];q=b[0];a=a[1:];b=b[1:]
 if p>q:a+=q+p
 if p<q:b+=p+q
 while p[-1]==q[-1]:
  if len(a)<2 or len(b)<2:return len(b)<2
  v=a[1];w=b[1];p+=a[0:2];q+=b[0:2];a=a[2:];b=b[2:]
  if v>w:a+=q+p
  if v<w:b+=p+q
 return f(a,b)

As posted, this is 265 bytes and it works in both Python 2 and Python 3.  You can save 4 bytes in Python 2 by replacing the spaces with a single tab in the while loop.
Try it online

Haskell, 372
My first Haskell Program
(It's my first functional programming, too...)
w[]_=False
w _[]=True
w a b=if length j==0 then a>b else w (drop(d$head j)a++fst(head j))(drop(d$head j)b++snd(head j))where j=p a b
d(a,b)=quot(maximum[length a,length b])2
f (Just a)=a
p a b=map f$filter(/=Nothing)[t(a!!x,take(x+1)a,b!!x,take(x+1)b)|x<-[0,2..minimum[length a,length b]-1]]
t(a,b,c,d)=if a==c then Nothing else if a>c then Just(d++b,[])else Just([],b++d)

I'd love to have tips on how to improve.
Usage:
w "D58B35926B92C7C4C7E8D3DAA2" "8E47C38A2DEA43467EB9566B95"
w "669D9D846D4B3BA52452C2EDEB" "E747CA988CC76723935A3B8EA5"
w "5744B95ECDC6D325B28A782A72" "68394D9DA96EBBA8533EE7C6C4"
w "87DB6C7EBC6C8D722389923DC6" "E28435DBEBEA543AA47956594A"
w "589EAB9DCD43E9EC264A5726A8" "48DC2577BD68AB9335263B7EC4"
w "E3698D7C46A739AE5BE2C49286" "BB54B7D78954ED526A83C3CDA2"
w "32298B5E785DC394467D5C9CB2" "5ED6AAD93E873EA628B6A4BC47"
w "B4AB985B34756C624C92DE5E97" "3EDD5BA2A68397C26CE837AD48"
w "9A6D9A5457BB6ACBC5E8D7D4A9" "73E658CE2C3E289B837422D463"
w "96E64D226BC8B7D6C5974BAE32" "58DC7A8C543E35978AEBA34D29"
w "C2978A35E74D7652BA9762C458" "9A9BB332BE8C8DD44CE3DE66A5"
w "BEDB44E947693CD284923CEA82" "8CC3B75756255A683A6AB9E7DD"
w "EEDDCCBBAA8877665544332299" "EEDDCCBBAA9988776655443322"
w "EEDDCCBBAA9988776655443322" "DDCCBBAA9988776655443E3E22"

Haskell is quick... :)
real    0m0.039s
user    0m0.022s
sys     0m0.005s