text:
Determine ranges from a list of values
Given an unsorted list of unique, positive integers, output the shortest list of the longest possible ranges of sequential integers.
INPUT

An unsorted list of unique, positive integers

e.g. 9 13 3 11 8 4 10 15

Input can be taken from any one of the following:

stdin
command-line arguments
function arguments

OUTPUT

An ordered list of ranges or individual values printed on one line to stdout or your language's closest similar output.

If two or more sequential integers (sequential by value, not by location in the list) are present, they will be denoted as an inclusive range using -, e.g. 8-11
All other integers are simply printed with no other notation
A single space will delimit the output

Numbers not present in the input should not be in the output, e.g. 3 5 6 cannot be shortened to 3-6 because 4 is not present

EXAMPLES
Successful:
 IN> 9 13 3 11 8 4 10 15 6
OUT> 3-4 6 8-11 13 15

 IN> 11 10 6 9 13 8 3 4 15
OUT> 3-4 6 8-11 13 15

 IN> 5 8 3 2 6 4 7 1
OUT> 1-8

 IN> 5 3 7 1 9
OUT> 1 3 5 7 9

Wrong:
 IN> 9 13 3 11 8 4 10 15
OUT> 3-15

Range contains values not in the input
 IN> 9 13 3 11 8 4 10 15
OUT> 3 4 8 9 10 11 13 15

All sequential values should be represented as a range
 IN> 9 13 3 11 8 4 10 15
OUT> 3-4 8-9 10-11 13 15

Divided range, 8-9 and 10-11 should be 8-11
 IN> 9 13 3 11 8 4 10 15
OUT> 8-9 13 10-11 3-4 15

Output not ordered correctly
RULES

Standard loopholes are disallowed
If your language has a function to do this it's not allowed
You may write a full program, or a function
trailing whitespace doesn't matter

SCORING

Least bytes wins

In the first example you have 3-4, which is a range of length 1. In this situation could we just put 3 4 instead?

No. All sequential numbers go in a range.

The first sentence is really confusing.  I'd recommend saying "output the shortest list of the longest possible ranges of sequential integers".  Otherwise, nice challenge!

As long as people understand that "longest range" doesn't allow "smallestNum-largestNum" if a few numbers are missing. I was trying to avoid that.

I'm pretty sure we've had this challenge before, but I'm not coming up with the right search terms. Anyone remember?

@CoreyOgburn By the way, what prompted you to post on PPCG? We're trying to figure out why we got a whole bunch of new users coming in.

@xnor I've kept an eye on the site for months. None of the languages I use are usually good candidates for answers and I've never had a question to post until today.

@xnor: It's similar to Maltysen's homework list one but not identical.

@AlexA. I have vague memories of one from earlier, because I also remember being reminded of it when I saw Maltysen's problem.

Does it have to work if only one integer is given? And do we have to account for negative integers?

No negative numbers. Input is always a list of at least two numbers.

Inverse challenge

Python 2, 123 120 bytes
N=sorted(map(int,raw_input().split(' ')));print(''.join((''if n+1in N else'-'+`n`)if n-1in N else' '+`n`for n in N)[1:])

If the input can be a list as a function argument then (thanks mbomb007 and xnor for the conditionals)
93 90 81 bytes
def f(N):print''.join((' '+`n`,`-n`*-~-(n+1in N))[n-1in N]for n in sorted(N))[1:]

(77 bytes if leading whitespace is acceptable - drop the final [1:])

You can change str(n) to \n`` to save a few bytes, if you switch to Python 2.

You can also create a function that takes a list as input instead of using raw_input(), and you can change '-'+\n`to`-n`. And since you're now using Python 2, you can remove the parentheses after the print`.

Generating the string piece by piece is clever. For byte saving, it's generally shorter to do conditionals by list selection or arithmetic, like def f(N):print''.join([' '+`n`,`-n`*(n+1 not in N)][n-1 in N]for n in sorted(N))[1:](which can be golfed further).

You might be able to use set(N) instead of sorted(N); this will correctly iterate from smallest to lowest when using cPython but is not guaranteed to work for all implementations so there is some question about whether or not this is valid.

JavaScript (ES6): 171 154 140 137  bytes
Thanks edc65 and vihan1086 for the tips! [...n] is very nice but it doesn't work in these cases due to multi-digit numbers.
f=n=>{s=e=o='';n.split` `.map(Number).sort((a,b)=>a-b).map(v=>{s=s||v;if(e&&v>e+1){o+=`${s<e?s+'-'+e:s} `;s=v}e=v});return o+(s<e?s+'-'+e:e)}

ES5 variant, 198 184 183 174 bytes
f=function(n){s=e=o='';n.split(' ').map(Number).sort(function(a,b){return a-b}).map(function(v){s=s||v;if(e&&v>e+1){o+=(s<e?s+'-'+e:s)+' ';s=v}e=v});return o+(s<e?s+'-'+e:e)}

f = function (n) {
    s = e = 0, o = '';
    n.split(' ').map(Number).sort(function (a, b) {
        return a - b
    }).map(function (v) {
        s = s || v;
        if (e && v > e + 1) {
            o += (s < e ? s + '-' + e : s) + ' ';
            s = v
        }
        e = v
    });
    return o + (s < e ? s + '-' + e : e)
}

// Demonstration
document.body.innerHTML = f('1 2');
document.body.innerHTML += '<p>' + f('9 13 3 11 8 4 10 15 6');
document.body.innerHTML += '<p>' + f('11 10 6 9 13 8 3 4 15');
document.body.innerHTML += '<p>' + f('5 8 3 2 6 4 7 1');
document.body.innerHTML += '<p>' + f('5 3 7 1 9');

n.split with no parentheses is totally new to me! But [...n] is better

@edc65 Thanks, never thought of unpacking the string like that.

Have a look at this http://codegolf.stackexchange.com/questions/37624/tips-for-golfing-in-ecmascript-6

... but ... does it work with any of the examples? there are multidigit numbers, so you need a split on a " "(blank space) not "" (empty string). I probably gave you the wrong tip

@edc65 I thought something looked different then I realized the test cases failed. Still good to learn something new though

SWI-Prolog, 165 162 159 bytes
b(Z,C,[D|E]):-Z=[A|B],(A=:=D+1,(B=[],put(45),print(A);b(B,C,[A,D|E]));(E=[],tab(1),print(A);writef('-%t %t',[D,A])),b(B,A,[A]));!.
a(A):-sort(A,B),b(B,_,[-1]).

Pretty bad but then again Prolog is a terrible golfing language
Example: a([9,13,3,11,8,4,10,15,6]). outputs 3-4 6 8-11 13 15

Ruby, 70 bytes
Problems like these tend to make me check the Ruby API for suitable methods, and today I discovered a new one: Array#slice_when, newly  introduced in Ruby v2.2 and seemingly intended for this exact situation :)
f=->a{puts a.sort.slice_when{|i,j|j-i>1}.map{|x|x.minmax.uniq*?-}*' '}

After sorting and appropriately slicing the array, it takes each sub-array and creates a string out of the highest and lowest element, and then joins this whole array into a string.
Example:
f.call [9,13,3,11,8,4,10,15,6] prints 3-4 6 8-11 13 15

Ruby, 86 84 bytes
s=->*a{puts a.sort.slice_when{|i,j|i+1!=j}.map{|e|e.size<2?e:[e[0],e[-1]]*"-"}*" "}

# demo
s[9, 13, 3, 11, 8, 4, 10, 15, 6]
# => 3-4 6 8-11 13 15

This is a slightly golfed version from an example in the docs for slice_when.

CJam, 35 bytes
l~${__0=f-ee::=0+0#/((oW>Wf*S+oe_}h

Try it online in the CJam interpreter.
How it works
l~$     e# Read a line from STDIN, evaluate it and sort the result.
{       e# Do:
  _     e#   Push a copy of the array.
  _0=f- e#   Subtract the first element from all array elements.
  ee    e#   Enumerate the differences: [0 1 4] -> [[0 0] [1 1] [2 4]]
  ::=   e#   Vectorized quality: [i j] -> (i == j)
  0+    e#   Append a zero.
  0#    e#   Push the first index of 0.
  /     e#   Split the array into chunks of that size.
  (     e#   Shift out the first chunk.
  (o    e#   Print its first element.
  W>    e#   Discard all remaining elements (if any) except the last.
  Wf*   e#   Multiply all elements of the remainder by -1.
  S+o   e#   Append a space and print.
  e_    e#   Flatten the rest of the array.
}h      e# Repeat while the array is non-empty.

CJam, 38 33 bytes
New version, using ideas and code fragments suggested by @Dennis:
l~$_,,.-e`{~T+\_T+:T;(_2$+W*Q?S}/

Try it online
The input format is a CJam array in square brackets.
The basic idea here is that I subtract a monotonic sequence from the sorted input sequence first:
3  4  8  9 10 11 13 15
0  1  2  3  4  5  6  7  (-)
----------------------
3  3  6  6  6  6  7  8

In this difference, values that are part of the same interval have the same value. Applying the CJam RLE operator to this difference directly enumerates the intervals.
The subtracted sequential values need to be added back during output. I'm not entirely happy with how that's done in my code. I suspect that I could save a few bytes with a more elegant way of handing that.
For generating the output of the intervals, this uses Dennis' idea of generating a negative number for the end value, which takes care of producing a -, and also simplifies the logic because only one value needs to be added/omitted depending on the interval size.
Explanation:
l~    Get input.
$     Sort it.
_,,   Create monotonic sequence of same length.
.-    Calculate vector difference between the two.
e`    Calculate RLE of difference vector.
{     Loop over entries in RLE.
  ~     Unpack the RLE entry, now have length/value on stack.
  T+    Add position to get original value for start of interval.
  \     Bring length of interval to top of stack.
  _T+:T;  Add length of interval to variable T, which tracks position.
  (     Decrement interval length.
  _     Copy it, we need it once for calculating end value, once for ternary if condition.
  2$    Copy interval start value to top...
  +     ... and add interval length - 1 to get end value.
  W*    Negate end value.
  Q?    Output end value if interval length was > 1, empty string otherwise.
  S     Add a space.
}%    End loop.

That's a clever use of RLE! By borrowing the range handling and input format from my answer, you can get down to 34 bytes: l~$_,,.-e`{~T+\_T+:T;,f+(\W>Wf*S}/

When I had originally looked at your solution, I was kind of mystified how you got a - into the output without it showing up in the code, and without a condition. Now I get it: It comes from turning the end value into a negative number! I never would have come up with this, so I would feel bad about copying it. I'll try to learn from it for next time! :)

Fair enough. How about l~$_,,.-e{~T+_T+:T;(_2$+W*Q?S}/` though? That's a lot more similar to your own code and weighs only 33 bytes.

@Dennis Ok, if you insist. :) Actually, taking the key idea of generating a negative value for the interval end, this looks like a reasonably straightforward way of implementing it. Thanks.

Jelly, 16 bytes
ṢI’kƊ.ịⱮUQ€j€”-K

Try it online!
How it works
ṢI’kƊ.ịⱮUQ€j€”-K - Main link. Takes an array L on the left
Ṣ                - Sort L; Call this A
    Ɗ            - Monad. Link the previous three links together f(A):
 I               -   Forward differences
  ’              -   Decrement
   k             -   Partition
                   This groups consecutive runs
                   Take A = [3, 4, 6, 8, 9, 10, 11, 13, 15]
                   I: [1, 2, 2, 1, 1, 1, 2, 2]
                   ’: [0, 1, 1, 0, 0, 0, 1, 1]
                   k then partitions A at truthy elements in I’
                   [[3, 4], [6], [8, 9, 10, 11], [13], [15]
       Ɱ         - For each:
     .ị          -   Take the 0.5th element

                   For non-integer left argument, x, Jelly's ị atom takes
                   floor(x) and ceil(x) and returns [floor(x)ịy, ceil(x)ịy]
                   As Jelly's indexing is 1-based and modular:
                     0ị returns the last element
                     1ị returns the first element
                     .ị returns [0ị, 1ị]

        U        - Reverse each
         Q€      - Deduplicate each
           j€”-  - Join each with "-"
               K - Join by spaces

Husk, 21 20 bytes
;moJ'-?I§e←→ε†sġ·=←O

Try it online!
A bit lacking in the strings department, but does well.
No matter what I tried, it somehow stubbornly stayed at 21.
-1 byte from Dominic Van Essen.
Explanation
;moJ'-?I§e←→ε†sġ§=…eO
                    O order the list
               ġ      group the list by the following:
                   e  elements paired
                §=    equal
                  …   the range between them?
             †s       convert all the numbers to strings
 mo                   map each group to the following:
      ?     ε         if it's a single element:
       I              leave as is
        §e←→          otherwise, move the first and last elements to a list
   J'-                join with '-'
;                     nest to display in one line

Nice use of groupBy!   ġ·=← gives 20 bytes

CoffeeScript, 178 161 bytes
Just like my JavaScript answer. I need to figure out if using comprehensions will result in shorter code.
f=(n)->s=e=o='';n.split(' ').map(Number).sort((a,b)->a-b).map((v)->s=s||v;(o+=s+(if s<e then'-'+e else'')+' ';s=v)if(e&&v>e+1);e=v);o+(if s<e then s+'-'else'')+e

Original:
f=(n)->o='';s=e=0;n.split(' ').map(Number).sort((a,b)->a-b).forEach((v,i)->if!i then s=v else(o+=s+(if s<e then'-'+e else'')+' ';s=v)if(v!=e+1);e=v);o+(if s<e then s+'-'else'')+e

Python 2, 126 122 121 Bytes
I know this can get shorter, just don't know where.. Requires input in form [#, #, #, #, ..., #].
l=sorted(input());s=`l[0]`;c=0;x=1
while x<len(l):y,z=l[x],l[x-1];s+=(('-'+`z`)*c+' '+`y`)*(y-z>1);c=(y-z<2);x+=1
print s

You seem to find solutions with exec quite often.

@mbomb007 You might be thinking of xnor :) And I think in this situation looping might be the same length, even shorter (haven't played around with it enough yet).

You should be able to replace while x<len(l) with while l[x:] to save a few bytes.

Java, 191 bytes
void f(int[]a){java.util.Arrays.sort(a);for(int b=a.length,c=b-1,i=0,j=a[0],l=j;++i<b;){if(a[i]!=++j||i==c){System.out.print((l+1==j?l+(i==c?" "+a[c]:""):l+"-"+(i==c?j:j-1))+" ");l=j=a[i];}}}

Checks for ranges and prints them accordingly. Unfortunately I had to make a special case for the last element in the array since the program would terminate without printing the last number or range.

Java, 171 162 bytes
String s(int[] n){Arrays.sort(n);int p=0,b=0;String r="",d="";for(int c:n){if(c==++p)b=1;else{if(b==1){r+="-"+--p+d+c;p=c;b=0;}else{r+=d+c;p=c;}d=" ";}}return r;}

Takes input as an int array, returns output as a space-separated String list

Japt -S, 17 16 bytes
ÍòÈnYÉÃ®é ¯2 Ôq-

Try it

Vyxal S, 120 bitsv1, 15 bytes
s:¯Ǐ⁽ṅḋ•ꜝƛ₍htU\-j

Try it Online!
Explained
s:¯Ǐ⁽ṅḋ•ꜝƛ₍htU\-j
s:                 # Push two copies of the input list but sorted
  ¯Ǐ               # Forward differences of items with the first item appended - this is for making sure the length of the deltas matches the length of the input
    ⁽ṅḋ            # Grouped by whether they are <= 1
       •           # Reshape the sorted input to that shape
        ꜝ          # and remove the 0
                   # the top of the stack will be a list of lists of numbers that are ranges
         ƛ         # to each range
          ₍htU     #   either get the first and last item or just the first
              \-j  #   join on "-"
# S flag joins the result on spaces

Scala, 204 bytes
Modified from @steenslag's Ruby answer.

Golfed version. Try it online!
def s(a:Int*):Seq[String]={val s=a.sorted;(Seq[Seq[Int]](Seq(s(0)))/:s.sliding(2)){(c,p)=>if(p(0)+1==p(1))c.init:+(c.last:+p(1))else c:+Seq(p(1))}.map(r=>if(r.size<2)r.mkString else s"${r(0)}-${r.last}")}

Ungolfed version. Try it online!
object Main {
  def s(a: Int*): Unit = {
    val sorted = a.sorted
    val sortedRanges = sorted.sliding(2).foldLeft(List[List[Int]](List(sorted.head))) { (acc, pair) =>
      if (pair(0) + 1 == pair(1)) acc.init :+ (acc.last :+ pair(1))
      else acc :+ List(pair(1))
    }
    val ranges = sortedRanges.map(range => if (range.size < 2) range.mkString else s"${range.head}-${range.last}")
    println(ranges.mkString(" "))
  }

  def main(args: Array[String]): Unit = {
    s(9, 13, 3, 11, 8, 4, 10, 15, 6)
  }
}

Haskell, 187 bytes
import Data.List
g p[x]=[[x]]
g p(a:b:c)|let(d:e)=g p(b:c)=if p a b then(a:d):e else[a]:(d:e)
p[x]=show x++" "
p x=show(head x)++"-"++show(last x)++" "
f=concatMap p.g(((-1==).).(-)).sort

Try it online!

Ly, 35 bytes
a0r[r0Ir::u[ps`=]pl~!['-olu!]p' o];

Try it online!
This is pretty brute force.  It sorts the numbers then iterates until all the numbers have been consumed.  After printing the "current" number on the stack, an inner loop consumes all the entries after that which are consequitive.  Then it either appends a -# string or not before printing a space and iterating again.
# prep work... created sorted list of numbers with trailing "0"
a0r
a    - read numbers from STDIN, sort stack
 0   - push a "0"
  r  - reverse stack

# loop over all numbers, then exit
[                             ];
[                             ]   - iterate while top of stack not "0"
                               ;  - exit to avoid dumping junk on stack

# remember the current number for comparison later
r0Ir
r     - reverse stack
 0I   - copy bottom of stack entry to the top
   r  - reverse the stack

# print the current number, loop/consume all sequential nums on stack
::u[ps`=]p
::          - duplicate top of stack twice
  u         - print current number
   [    ]p  - loop until top of stack is "0"
    p       - delete previous number
     s      - save the current number
      `=    - increment current number, compare to next num on stack

# print "-X"  if needed to cover delete numbers, then print space
l~!['-olu!]p' o
l                - load saved num (last number deleted)
 ~               - search stack for that number
  !              - negate result
   [      ]p     - "then" code block
    '-o          - print "-"
       lu        - load last num in sequence (last deleted)
         !       - flip top of stack to "0" to exit loop
            ' o  - print " "

Perl 5 -pa, 95 bytes
$_=join$",sort{$a-$b}@F;$b=$_,s/(\d+)\K (?=(\d+))/$2-$1-1?$":"-"/ge while$_ ne$b;s/(-\d+)+/$1/g

Try it online!


text:
Calculate the Orthocenter of a Triangle
Try to write the shortest program or function you can that prints or returns the calculated orthocenter of a triangle.
The orthocenter of a triangle is the intersection point of the three altitudes of a triangle. The altitude of a triangle is a perpendicular segment from the vertex of the triangle to the opposite side.

Input:

Three points in 2D space correponding to the triangle's vertices

Output:

The calculated orthocenter of the triangle

A sample input would be
A(0,0)
B(3,6)
C(6,0)

and a sample output would be:
Calculated Othocenter (3, 1.5)

One formula for orthocenter can be written as
(x, y) = ((ax*tan(α) + bx*tan(β) + cx*tan(γ))/(tan(α) + tan(β) + tan(γ),
          (ay*tan(α) + by*tan(β) + cy*tan(γ))/(tan(α) + tan(β) + tan(γ))

Shortest program in bytes wins.

I added a description, and yes, the use of global's as a function was a slip up on my part, I copy and pasted from the wrong notepad file I had open without realizing it. The use of arrays is purely optional, it is just a habit of mine to do so, vs a naming convention like Ax, Ay, Bx...

Welcome to PPCG. Language specific challenges are frowned on here, because they limit participation and are frequently homework questions in disguise. I will cast a reopen vote if the language restriction is removed (and I say this despite the fact that most of my answers are in C.)

I cleaned this whole thing up for you, but you need to specify how the points are to be supplied to the function or program and what exactly the points are (angles, coordinates?)

@BetaDecay it was fairly clear to me that the given points and required orthocentre are x.y coordinates. See 3rd comment from the top.

This question would benefit greatly from a good set of test cases; and, as with all questions involving floating point numbers, the spec isn't complete without a carefully thought out constraint on numerical accuracy.

For a triangle or any shape? My attempt but it's really ugly and I don't know if I should really post it as an answer

Since your input is defined as "several points", what's the definition of the orthocenter for more than 3 points? What if there are less than 3 points in the input?

3 points is a mandatory input, cases in which there is a missing point are out of the scope of this challenge, or course, one could write a program to find that missing side.

Is web scraping allowed?

As in using an online resource to do it for you?(Example -curl and an online calculator?)No

Python, 193 168
Should work for any valid triangle...
def h(a,A,b,B,c,C):
 if A==B:b,B,c,C=c,C,b,B
 m=(a-b)/(B-A)
 return m,C-m*c
def f(a,A,b,B,c,C):
 m,q=h(a,A,b,B,c,C)
 k,z=h(c,C,b,B,a,A)
 x=(q-z)/(k-m)
 return (x,k*x+z)

CJam, 90 bytes
q~:C2$]_2ew::.-:D;;D1=0=D2=0=*D1=1=D2=1=*+D0=1=D2=0=*D0=0=D2=1=*-/_D0=1=*C0=+C1=@D0=0=*-S\

Try it online
CJam isn't really optimized for geometry, so the code isn't doing anything fancy. It uses the parametric representation for two of the lines passing through a corner and being orthogonal to the opposite side, and solves the 2x2 system of equations resulting from intersecting the two lines. Well, it only needs one of the resulting parameters, which is then used for calculating the intersection point.
Note that some of the signs in the intermediate values are wrong. Instead of flipping them with additional code, I kept them the way they are, and corrected for the wrong sign by changing additions to subtractions (or vice versa) when the value is used later. For example, if you see a + where you would normally expect a - when calculating a determinant, that's because one of the terms has the wrong sign. In fact, both determinants have the wrong sign (at least relative to my paper notes), but that doesn't matter because they are divided by each other.
Since the input format was not precisely specified, I made it CJam friendly. The code expects 3 points in CJam array format, where the values have to be floating point. For the given example, the expected input is:
[0. 0.] [3. 6.] [6. 0.]

Explanation:
q~      Get and interpret input.
:C      Store away the last point in variable C. Will be needed at the end
        to calculate the intersection point.
2$]     Repeat the first point, and wrap all points in an array.
_2ew    Generate array with all pairs of points [[A B] [B C] [C A]].
::.-    Calculate the vector difference of all point pairs [A-B B-C C-A].
        These are the vectors for each side of the triangle.
:D;;    Store the side vectors in a variable, and clear the stack.
D1=0=D2=0=*D1=1=D2=1=*+
        Calculate determinant for first unknown in 2x2 system of equations.
D0=1=D2=0=*D0=0=D2=1=*-
        Calculate main determinant of 2x2 system of equations.
/       Divide the two determinants. This gives the parameter of the
        intersection point for the line starting at C and orthogonal to A-B.
_       Copy it because we'll need it twice.
D0=1=*C0=+
        Calculate x-coordinate of intersection point.
C1=@D0=0=*-
        Calculate y-coordinate of intersection point.
S\      Put a space between the two values.

R, 102 70 68 bytes
As an unnamed function which implements the formula in the question.  The parameter for the function a vector of complex numbers (X+Yi) and it returns a complex number.  I'm assuming that complex numbers are okay for input and output.
function(E)sum((F=tan((D=Arg(E-E[c(3,1,2)]))-D[c(2,3,1)]))*E)/sum(F)

Edit Vectorized it a lot
Expanded explanation
f=function(E){
    D=Arg(E-E[c(3,1,2)]); # Angles of sides
    F=tan(D-D[c(2,3,1)]); # Internal triangle angles tangents
    sum(E*F)/sum(F);      # Orthocenter coordinate return
}

Test
> f=function(E)sum((F=tan((D=Arg(E-E[c(3,1,2)]))-D[c(2,3,1)]))*E)/sum(F)
> f(c(0+0i,3+6i,6+0i))
[1] 3+1.5i

Is the code shorter if you use complex numbers or just required for the calculation?

@BetaDecay both really.  They made the calculation easier and shorter.  If it turns out that they aren't allowed as input or output I would probably still us them internally.

Cobra - 247
def f(p as System.Drawing.Point[])
    a,b,c=p
    d,e,f=for q in[[b,c],[a,c],[a,b]]get if(z=q[0].x-q[1].x,(q[0].y-q[1].y)/z,0f)
    print (a.x*(g=((e-f)/(1+e*f)).abs)+b.x*(h=((d-f)/(1+d*f)).abs)+c.x*(i=((e-d)/(1+e*d)).abs))/(j=g+h+i),(a.y*g+b.y*h+c.y*i)/j

source: Stack Exchange

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

sort: votes


text:
National Scheduling Conflict Championships

(I meant to post this while 1542: Scheduling Conflict
was still the current xkcd, but I had a scheduling conflict.)
Input
The input will be a list of 3n elements, which represent n events. The
first element in each group of 3 will be the name of an event; the second and
third, the start and end time respectively. For example:
foo 12 34 bar 56 78

represents an event foo that starts at "time 12" (times are represented
simply by integers; you can think of them as minutes past midnight) and ends at
34, and a second event bar that starts at 56 and ends at 78.
The names of events will always consist of only alphanumeric characters, and
the times will always be integers ≥ 0 and < 1440. The end time will always be
at least 1 greater than the start time. They are not guaranteed to be sorted in
any way.
If you would like, you may take this as a single space-separated string;
otherwise it should be taken as an array, list, vector, or your language's
equivalent.
Output
The output should be a space-separated list of event names. The rules for which
event names to output are as follows:

None of the events that you output may conflict with each other. For example,
with the input a 0 10 b 5 15, you may not output both a and b because
the times conflict (that is, partially overlap). If an event ends exactly as
another one starts, you may include both.
You may not output the event called NSCC ("National Scheduling Conflict
Competition"), of which there will always be exactly one of in the input.
You also must output at least one event that conflicts (partially
overlaps) with NSCC (and there will always be at least one of those as
well).
You must output as many events as possible while following the above two
rules. (This is so that you look as busy as possible, so that missing the
NSCC seems more credible.)

This may also be output as either a single space-separated string or an array,
list, vector, etc.
There can be more than one possible output.
Test cases
Note that the outputs listed are only examples. Your code may output something
different, as long as it still follows the three rules above (notably, this
means there must be the same amount of events as the example).
In: UnderwaterBasketWeavingConvention 50 800 NSCC 500 550
Out: UnderwaterBasketWeavingConvention
In: SconeEating 0 50 RegexSubbing 45 110 CodeGolfing 95 105 NSCC 100 200
Out: SconeEating CodeGolfing
In: VelociraptorHunting 0 300 NerdSniping 200 500 SEChatting 400 700 DoorknobTurning 650 750 NSCC 725 775
Out: NerdSniping DoorknobTurning
In: NSCC 110 115 A 100 120 B 120 140 C 105 135 D 100 105 E 135 500
Out: C D E
In: A 800 900 NSCC 700 1000 B 650 750 C 950 1050 D 655 660 E 660 665 F 1030 1040 G 1040 1060
Out: A D E F G
In: A 10 11 B 11 12 C 12 13 D 13 14 NSCC 15 1090 E 10 16
Out: E
Feel free to add more test cases in an edit if there are edge-cases that I
missed.
Rules

Your code must complete within 30 seconds for all of the provided test cases
(this is more of a sanity check, as it should probably complete much faster
for all the test cases combined) on a reasonable personal machine.
This is code-golf, so the shortest code in bytes wins.

Is it acceptable to use camelCase for events in inputs ? for instance using underwaterBasketWeavingConvention 50 800 nscc 550 instead of your example?

@Fatalize Not sure what you mean; the input is given exactly as it is shown. You should be able to support any combination of alphanumberic characters.

I'll have to work on a solution to this later; I have a scheduling conflict right now.

In the second example there are two spaces between "CodeGolfing" and "95" -- is this a mistake, or do we need to account for arbitrary numbers of spaces in the input? For right now, I'm going to assume the former, since you seem a little bit lenient on the format of the input.

@VijayRamamurthy Yes, it is. Fixed.

Pyth, 45 bytes
AGH.gqhk"NSCC"m,hdrFtdcQ3hMef&.{KseMT@KehHtyG

This one was quite tough to golf. Found quite a few 45 byte solutions, this one is probably the most exotic one, since it uses A (pair-assign) and .g (group-by).
Try it online: Demonstration or Test harness
Explanation
                            implicit: Q = input list
                      cQ3   split Q into triples
              m             map each triple d to:
               ,              the pair containing
                hd              - d[0] (name)
                  rFtd          - range from start-time to end-time
   .g                       group these tuples k by:
     qhk"NSCC"                k[0] == "NSCC"
AGH                         pair assign to G,H. This assigns all
                            tuples != NSCC to G, and the NSCC one to H

                  yG        generate all subsets of G
                 t          remove the first one (the empty subset)
   f                        filter for subsets T, which satisfy:
         eMT                  get the last item (the range) for all tuples in T
        s                     and combine them (sum)
       K                      assign to K
     .{                       check for uniqueness of K (no overlapping times)
    &                         and
            @KehH             check the intersection of K and H[0][1]
  e                         take the last element (most events)
hM                          get the first item (name) for each event
                            and implicitly print this list

SWI-Prolog, 537 524 516 502 447 436 bytes
z(A:B:C,[D:E:F|G]):-(A=D;B>=F;E>=C),(G=[];z(A:B:C,G)).
u([A|B],C):-z(A,C),(B=[];u(B,C)).
y([A,B,C|D])-->[A:B:C],(y(D);{_=_}).
d-->[A:_],{write(A),tab(1)},d;{_=_}.
l([H|T],R):-T=[],R=H;length(H,N),l(T,X),length(X,M),(N>M,R=H;R=X).
v([],_,R,R).
v([A|T],Z,B,R):-u(A,A),\+z(Z,A),v(T,Z,[A|B],R);v(T,Z,B,R).
s([E|T],[F|N]):-E=F,(N=[];s(T,N));s(T,[F|N]).
x(A):-y(A,D,[]),K="NSCC":_,select(K,D,E),setof(L,s(E,L),B),v(B,K,[],R),l(R,S),d(S,[]),!.

Brief explanation of what each predicate does:

z(A,B) checks that an event A doesn't conflict with any event of a list of events B
u(A,B) checks that every event of a list A does not conflict with any event of a list B (used to check that there are no conflicts in list A by calling u(A,A))
y(A,B,C) splits a List into a list of triplets (to transform inputs into a list of events)
d(A) prints the names of events in a list A
l(A,R) evaluates the longest list of events R contained in the list of lists A
v(A,NSCC,C,R) returns a list R containing every list of events in A that have no internal conflict and that conflict with the event NSCC
s(A,B) true if B is a subset of A
x(A) main predicate, A is the input.

Test cases: execute test. in the interpreter after loading the code above with the following added after it:
test:-
    x(["UnderwaterBasketWeavingConvention",50,800,"NSCC",500,550]),
    nl,
    x(["SconeEating",0,50,"RegexSubbing",45,110,"CodeGolfing",95,105,"NSCC",100,200]),
    nl,
    x(["VelociraptorHunting",0,300,"NerdSniping",200,500,"SEChatting",400,700,"DoorknobTurning",650,750,"NSCC",725,775]),
    nl,
    x(["NSCC",110,115,"A",100,120,"B",120,140,"C",105,135,"D",100,105,"E",135,500]),
    nl,
    x(["A",800,900,"NSCC",700,1000,"B",650,750,"C",950,1050,"D",655,660,"E",660,665,"F",1030,1040,"G",1040,1060]),
    nl,
    x(["A",10,11,"B",11,12,"C",12,13,"D",13,14,"NSCC",15,1090,"E",10,16]).

This took me way more time than I thought it would. This can probably be golfed significantly more. Also you could probably use the various constraint programming libraries that exist to get shorter solutions.
Edit: Thanks to @Oliphaunt for the idea of using A:B:C instead of [A,B,C] for triplets. Saves 14 bytes.
Edit2: Thanks again to @Oliphaunt for  pointing out that the predicate ``t/3`was useless. Saves 55 bytes
Edit3: Gained 11 bytes using definitive clause grammar on predicates y and d.

Love answers in Prolog! Nice one.

I'm a Prolog lover too. Suggestions: 1. I think you can use e.g. A/B/C instead of [A,B,C] for the triplets, saving 10 bytes; 2. Can you use \+ instead of not? 3. Could you explain why you need the final cut in x(A)?

I'll come back to you tomorrow, from my laptop. Right now in bed with the tablet which makes for clumsy typing and I should probably sleep anyway. :-)

Here is a version that saves 14 bytes. I used : instead of / to benefit from the former's right-associativity, i.e. so I could write A:_ as shorthand for A:_:_ (but A+B/C works just as well: you can then use A+_). By the way, also in your original you could've used [A|_] instead of [A,_,_]. Note finally that my version of SWI-Prolog didn't have nth0/4, so I used select/3 instead.

I wondered before about the need for t(S,T) but then forgot. Now tested: you can save 55 more bytes by dropping it entirely and directly calling s(E,L) from setof/3.

Hmm... I found a library predicate subset/2...

@Oliphaunt subset/2 in Swi-Prolog contains a cut at the end of its execution, thus making it unusable with setof or findall. You can see its implementation here.

JavaScript (ES6), 228
Second try, I hope this one works.
My target is the longest sequence of events that has a timing conflict, but no timing conflict when the event NSCC is removed. This modified sequence with NSCC removed is the output requested.
I use a Breadth First Search examining a queue of candidate solutions, starting with longest (the first is the initial list). From a candidate solution of n events I build and enqueue n more candidate solutions, removing one of the events and keeping the others.
A candidate solution is valid if there is a timing conflict 'as is', but when the NSCC event is filtered out there is no conflict. I use a subfunction K to check for conflicts.
Probably could be golfed a little more...
Test running the snippet below (being EcmaScript 6, FireFox only)

F=l=>(K=>{
  l.map(v=>l.push(l.splice(0,3)));// I'm particularly proud of this trick for grouping in triplets (in pith it's "cQ3")
  for(S=[l.sort((a,b)=>a[1]-b[1])];!K(l=S.shift())|K(m=l.filter(x=>x[0]!='NSCC'));)
    l.map((v,i)=>(S.push(n=[...l]),n.splice(i,1)));
})(l=>l.some(x=>[p>+x[1],p=+x[2]][0],p=0))||m.map(x=>x[0])

// Less golfed and ES5

function Find(l) {
  var n,m;
  var Check = function(l) {
    // check timing conflict comparing start time and end time of previous event (events must be sorted)
    var p = 0 // previous event end time, init to 0
    return l.some( function(x) {
      var err = p > +x[1]; // unary plus convert string to number
      p = +x[2]; // update end time
      return err;
    });
  };
  // group initial array in triplets
  // forEach repeats for the initial number of elements in l, even if l becomes shorter
  // so it loops more times than necesary, but it works anymay
  l.forEach(function() {
    l.push(l.splice(0,3)); // remove first 3 elements and add to back as a triple
  })
  l.sort(function(a,b) { return a[1]-b[1]} ); // sort by start time
  var S=[l]; // S is the main queue, start with complete list

  while (l = S.shift(), // current list
         m = l.filter( function(x) { return x[0]!='NSCC'} ), // current list with NSCC removed
         !Check(l)|Check(m)) // loop while list ha no errors or filtered list do have errors
  {
    // build new candidate to check
    l.forEach ( function(v,i) {
      n = l.slice(); // make a copy of l
      n.splice(i,1); // remove ith element
      S.push(n); // put in S
    });
  }
  // when exiting while, m has the list with NSCC removed
  return m.map( function(x) { return x[0]; }); // keep the event name only
}

// Test

out=(...x)=>O.innerHTML += x + '\n';

test=[
  ['UnderwaterBasketWeavingConvention 50 800 NSCC 500 550','UnderwaterBasketWeavingConvention']
, ['SconeEating 0 50 RegexSubbing 45 110 CodeGolfing  95 105 NSCC 100 200','SconeEating CodeGolfing']
, ['VelociraptorHunting 0 300 NerdSniping 200 500 SEChatting 400 700 DoorknobTurning 650 750 NSCC 725 775'
  ,'NerdSniping DoorknobTurning']
, ['NSCC 110 115 A 100 120 B 120 140 C 105 135 D 100 105 E 135 500','C D E']
, ['A 800 900 NSCC 700 1000 B 650 750 C 950 1050 D 655 660 E 660 665 F 1030 1040 G 1040 1060','A D E F G']
, ['A 10 11 B 11 12 C 12 13 D 13 14 NSCC 15 1090 E 10 16','E']
]

test.forEach(x=>{
  var l=x[0].split(/\s+/), r=F(l).sort().join(' '), e=x[1].split(/\s+/).sort().join(' ');
  out('Test ' + (r==e ? 'OK':'FAIL')+'\nInput:    '+x[0]+'\nResult:   '+r+'\nExpected: '+e)
} )

May I ask the point of a Stack Snippet if the program doesn't do anything if you don't call the function?

@BetaDecay: edc65 usually adds test cases that run in the snippet. Sounds like he'll be returning to this answer soon, at which time I assume he'll add the runnable stuff. :)

@BetaDecay Was in a hurry. And (worse yet) it fails one of the test.

Java, 828 bytes
There's probably a more concise Java implementation out there, but here's my stab:
String s(String e){String[] a=e.split(" ");String m="";String[] c=g(a.length/3);int l=0;for(int i=0;im.length())m=p;String r="";for(int i=0;i<m.length();i++)r+=a[3*(m.charAt(i)-48)]+((i==m.length()-1)?"":" ");return r;}boolean h(String c, String[] e){for(int i=0;i<c.length()-1;i++){int p=c.charAt(i)-48;for(int j=i+1;j<c.length();j++){int q=c.charAt(j)-48;if((Integer.parseInt(e[3*p+1])-Integer.parseInt(e[3*q+2]))*((Integer.parseInt(e[3*p+2])-Integer.parseInt(e[3*q+1])))<0)return true;}}return false;}String[] g(int n){if(n>1){String[] result=new String[(int)Math.pow(2,n)];String[] l=g(n-1);for(int i=0;i<l.length;i++){result[2*i]=l[i];result[2*i+1]=l[i]+(n-1);}return result;}else return new String[]{"","0"};}

Declaring all variables in one place will save bytes.

You don't need to else return.

Python, 373 characters
import itertools as j
a=zip(*[iter(input())]*3)
f,g,r=[],0,"NSCC"
p=f
for q in a:
 p=(p,q)[q[0]==r]
for h in range(1,len(a)+1):
 for i in j.combinations(a,h):
  s,i,l,m=0,sorted(i,key=lambda k:int(k[1])),-1,len(i)
  for n in i:
   s=(s,1)[p[1]<n[2]or p[2]<n[1]]
   if r==n[0]or n[1]<l:
    m=-1
    break
   else:
    l=n[2]
  if s*m>g:
   g,f=m,i
for o in f:
 print o[0]

Creates all possible combinations and checks each one.
Test
Input: ["NSCC",110,115,"A",100,120,"B",120,140,"C",105,135,"D",100,105,"E",135,500]
Output:

D
C
E

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


text:
Snakes and Ladders probability of winning
(This is my first Q here, and I don't know much about code golfing.)
Your aim is to predict the winner of an ongoing Snakes and Ladders game.
INPUT

A single number (2-1000) indicating the number of spaces on the board, say x.
Another number (2-4) indicating number of players, say n.
n numbers, each giving the position of each player on the game board.
Another number (1-15) indicating number of snakes and ladders (combined), say s.
s lines of input, each with 2 numbers - the start and end of each snake/ladder.

OUTPUT
n decimal numbers, accurate to 2 decimal places, indicating the probability of each player winning.
WINNER
The person to give the fastest program wins, not necessarily the shortest code. This might help those using a different algorithm to gain a huge advantage.
Notes
Players start on space 1, not 0. They win on reaching space x.
All players use a fair 6 sided dice. There are no re-rolls for 6s.
We assume that there is no 'bad' input given, such as more than 4 players, or a snake starting at the last space.
Players are given the same order of play as your input. The first player is the first to roll now, then the second and so on.
Even if you overshoot the win space, you still win.

Could you provide some sample inputs/outputs?  Also, fastest algorithm is for the the theoretical fastest algorithm (Aka, O(n) beats O(n^2) ).  If you want actual fastest code, then use the tag [tag:fastest-code]

Is an exact roll required to reach the last square or is overshooting OK?

@trichoplax I assume the specification makes it clear: "s lines of input, each with 2 numbers - the start and end of each snake/ladder.": If the first number is higher than the second it's a snake, otherwise a ladder.

@SebastianHöffner that does make it clear - thanks for that

@feersum Overshooting is allowed; you still win.

@Nathan I don't know how to write the code myself, so I can't provide a large input with right results. And I've edited the tag.

I think I remember reading about someone doing this already in R, probability of every space. Want me to try finding it?

C, ~.25 seconds
I have calculated by using dynamic simulations instead of probability of each dice roll. The more accurate the probability, the slower... here a brief code...
Compile using:
gcc -o Snakes snakes.c

Code:
#include <time.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
    srand(time(0));

    // initialize principal variables
    int NumberOfSpaces   = 100,
    NumberOfPlayers  = 4,
    PlayerPosition[] = { 46, 56, 36, 66 };
    //PlayerPosition[] = {0, 0, 0, 0};

    // arrays of positions, must be in numerical order,
    // must be in (start, end) format. correct - 1, 2, 5, 6, 8, 9
    //                               incorrect - 1, 2, 8, 9, 5, 6
    int LadderPositions[10] = { 3, 10, 5, 20, 20, 31, 22, 49, 44, 87 },      // positions of ladders
    SnakePositions[10] = { 11, 3, 15, 1, 35, 22, 54, 29, 60, 20 }, // positions of snakes
    SnakesLadders    = 10;                                       // # of snakes + ladders

    // static arrays to hold
    // # of dice rolls to complete game
    int Player1Wins[10000],
    Player2Wins[10000],
    Player3Wins[10000],
    Player4Wins[10000];

    int NumberOfSimulations = 10001;

    int OutsideLoop, Counter = 1, i, a, Win, EvenArray;
    for (OutsideLoop = 0; OutsideLoop < NumberOfPlayers; OutsideLoop++)      // do a simulation for each player
        for (a = 0; a < NumberOfSimulations; a++)                       // play for each simulation
        {
            for (i = PlayerPosition[OutsideLoop]; i <= NumberOfSpaces + 1; i += (rand() % 6 + 1)) // roll the dice for each turn
            {
                Counter++ ;
                for (EvenArray = 0; EvenArray < SnakesLadders; EvenArray+=2) // check if space is snake or ladder
                {
                    if (i == LadderPositions[EvenArray])
                        i = LadderPositions[EvenArray + 1];
                    if (i == SnakePositions[EvenArray])
                        i = SnakePositions[EvenArray + 1];
                }
             }
             // put value in array
             if (OutsideLoop == 0)
                 Player1Wins[a] = Counter;
             else if (OutsideLoop == 1)
                 Player2Wins[a] = Counter;
             else if (OutsideLoop == 2)
                 Player3Wins[a] = Counter;
             else if (OutsideLoop == 3)
                 Player4Wins[a] = Counter;
             Counter = 0;
        }

    // count how many time each person won
    int P1Wins = 0, P2Wins = 0, P3Wins = 0, P4Wins, Ties = 0;
    for (Win = 0; Win < NumberOfSimulations; Win++)
    {
        if (Player1Wins[Win] < Player2Wins[Win] && Player1Wins[Win] < Player3Wins[Win] && Player1Wins[Win] < Player4Wins[Win])
            P1Wins++;
        else if (Player2Wins[Win] < Player1Wins[Win] && Player2Wins[Win] < Player3Wins[Win] && Player2Wins[Win] < Player4Wins[Win])
            P2Wins++;
        else if (Player3Wins[Win] < Player1Wins[Win] && Player3Wins[Win] < Player2Wins[Win] && Player3Wins[Win] < Player4Wins[Win])
            P3Wins++;
        else if (Player4Wins[Win] < Player1Wins[Win] && Player4Wins[Win] < Player2Wins[Win] && Player4Wins[Win] < Player3Wins[Win])
            P4Wins++;
        else if (Player2Wins[Win] == Player1Wins[Win] == Player3Wins[Win])
            Ties++;
    }

    printf("[ + ] Namaste! Welcome to the Snakes & Ladders guess who wins program!\n");
    printf("[ + ] I will run 10K simulations of the game to make a guess on the probability of the winner.\n");
    printf("[ + ] Given %i players, with starting positions of :\n[ + ] P1 - %i\n[ + ] P2 - %i\n[ + ] P3 - %i\n[ + ] P4 - %i\n[ + ] Here's the probability I think each player has of winning...\n", NumberOfPlayers, PlayerPosition[0], PlayerPosition[1], PlayerPosition[2], PlayerPosition[3]);
    printf("[ + ] P1 = %i / 10000\n[ + ] P2 = %i / 10000\n[ + ] P3 = %i / 10000\n[ + ] P4 = %i / 10000\n[ + ] Ties = %i\n", P1Wins, P2Wins, P3Wins, P4Wins, Ties);
    return 0;
}

Environment - timed using time (bash command) on linux core i7
10    simulations ~ .003 second
10000 simulation  ~ .030 second
Sample outputs :
time ./Snakes
[ + ] Namaste! Welcome to the Snakes & Ladders guess who wins program!
[ + ] I will run 10K simulations of the game to make a guess on the probability of the winner.
[ + ] Given 4 players, with starting positions of :
[ + ] P1 - 10
[ + ] P2 - 21
[ + ] P3 - 50
[ + ] P4 - 70
[ + ] Here's the probability I think each player has of winning...
[ + ] P1 = 86 / 10000
[ + ] P2 = 254 / 10000
[ + ] P3 = 131 / 10000
[ + ] P4 = 9098 / 10000
[ + ] Ties = 0
real    0m0.036s
user    0m0.036s
sys 0m0.000s

Alt input position:
[ + ] Given 4 players, with starting positions of :
[ + ] P1 - 15
[ + ] P2 - 5
[ + ] P3 - 60
[ + ] P4 - 50
[ + ] Here's the probability I think each player has of winning...
[ + ] P1 = 955 / 10000
[ + ] P2 = 3041 / 10000
[ + ] P3 = 1833 / 10000
[ + ] P4 = 3572 / 10000
[ + ] Ties = 0
real    0m0.024s
user    0m0.024s
sys     0m0.000s

More input:
[ + ] Given 4 players, with starting positions of :
[ + ] P1 - 46
[ + ] P2 - 56
[ + ] P3 - 36
[ + ] P4 - 66
[ + ] Here's the probability I think each player has of winning...
[ + ] P1 = 94 / 10000
[ + ] P2 = 442 / 10000
[ + ] P3 = 2454 / 10000
[ + ] P4 = 6319 / 10000
[ + ] Ties = 0
real    0m0.018s
user    0m0.018s
sys     0m0.000s

I just realised that, for me to compare response time, I will have to test it myself (each person's machine and language may vary). Please give the exe file so I can check the time required.

Maybe you could upload it to Google Drive and share it, otherwise I don't know how to share an exe....

Also I may need to enter values greater than 100 to compare, so please allow for input upto 1000. Sorry and thanks!

@ghosts_in_the_code: Couldn't you just copy and paste the code into a .c file on your computer and compile it using the gcc line provided in the answer?

I don't think it's a good habit to start sharing binaries when we have the source. I've tried to keep the variable names as descriptive as possible so it's easy to edit. There are no limits, so you can change # of spaces, players, etc.

Also, whether the answer is a simulation or calculated probability, the only way to verify the accuracy of the answer is to set up many, real life games of Snakes & Ladder's where real people roll the dice, record the results, then compare it to answers posted here. Anything else is theoretical.

@AlexA. Don't I have to first download the compiler?

@ghosts_in_the_code: Do you not have gcc? Try going to your command line and entering gcc -v. If you don't have it, take a look here.


text:
Find the optimal nim move
The game
Nim is a mathematical strategy game, where 2 players take turns taking items from distinct heaps. On your turn, you must take at least one item, and you may take as many as you want, provided that you only take from one heap. The player that takes the last item wins! This is a solved game. Before I go into the strategy, you can try playing it online here.
The Strategy
The winning strategy is explained very clearly and simply here at this link. I will explain it using a little bit more technical terms. The way to win this game, is to always take as many items as possible so that the binary-digital-sum is always 0. Consider the following board:
         *
       * *
     * * *
   * * * *
 * * * * *
 1 2 3 4 5

To find the binary-digital-sum of this board, you must:

Convert the number in each row to binary. So we have 001, 010, 011, 100 and 101.
Add all the numbers together, and ignore any carrying.
 001
 010
 011
 100
+101
----
 001

You can also bitwise-xor each number, and this will achieve the same result.

Now, if the sum in this current configuration is 001, then this is not (yet) a winning board. But you can make it a winning board! If we take one item off of columns 1, 3 or 5, the sum will be 0. This is a winning board, which means that, provided you don't make a mistake, the next player to move will lose. So you must always end your turn with a winning board. Lets say you take one item off of column 5. Now the board looks like this:
       * *
     * * *
   * * * *
 * * * * *
 1 2 3 4 5

As long as you don't screw up, you have a guaranteed win. There is nothing your opponent can do to stop you. Lets say he takes all of the items from column 5.
       *
     * *
   * * *
 * * * *
 1 2 3 4 5

Where would you go next? Don't scroll down yet, and try to figure it out for yourself.

Right now, the sum is 100. The best move (and only winning move) would be to take everything from column 4. That would leave the board like this:
     *
   * *
 * * *
 1 2 3 4 5

and the sum like this
 001
 010
+011
----
 000

that means that you are in a winning board! Yay!
The Challenge
You must write a program or function that, given a nim board, will return a winning move, or a falsey value if there is no winning move.
Your input:

Will be your languages native list format, where each item in the list corresponds to the number of items in a given column. For example, the input {4, 2, 1, 0, 3} corresponds to the following nim board:
*
*           *
*  *        *
*  *  *     *
1, 2, 3, 4, 5

(optional) The number of rows. (For languages like C/C++ where this is not known from the list itself.)

Your output:

Can go to STDOUT or be returned from the function
Must be two numbers, 1) the column we are removing from (Remember that the columns are 0-indexed) and 2) the number of items to remove from that row. This could be a 2-item array, a string of the two numbers, etc. Keep in mind that the answer might be more than 2 digits long, so returning the string "111" is not valid because it isn't clear if this means "Remove one item from column eleven" or "Remove eleven items from column one". "1,11" or "11,1" would both be acceptable.
If there is no answer, return or print a falsy value. If your langauge can only return one type of variable (again, like C/C++), a negative number for the column, or 0 or less for the number to remove would both be acceptable falsey values.
If the column number or number to remove are too large, this is seen as an invalid output.

Sample Inputs/Outputs
[1, 2, 3, 4, 5] ---> [0, 1] or [4, 1] or [2, 1]
[1, 3, 5, 6] ---> [0, 1] or [1, 1] or [2, 1]
[1, 2, 0, 0, 5] ---> [4, 2]
[1, 2, 3] ---> ERROR
If you choose to do a function instead of full program, then you must write a full program to demonstrate the function in action. This will not count towards your full score. Also, programs are expected to run in a reasonable amount of time. I'm not planning to enter any excessively large inputs, so as long as your program isn't doing a brute force search over the entire game tree, you should be fine.
As usual, this is code-golf, so standard loop-holes apply, and answers are counted in bytes.
Leaderboard
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

var QUESTION_ID=52356;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
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

Can we assume, that the input list contains at least one positive number?

@Jakube yes, you can.

Related-ish?

Pyth, 33 22 21 20 19 bytes
eS.e*<JxxFQbb,k-bJQ

You can try it in the online compiler here.
Thank you to Jakube for removing 12 bytes and Maltysen for removing an additional byte!
This prints a winning move from the current position. If there are no winning moves, it doesn't print anything.
I used the algorithm on wikipedia. Here is the breakdown:
  .e              Q    While enumerating every element in the input:
      J                    Assign variable J to:
        xFQ                 Every element of the input bitwise xor'ed together,
       x   b                bitwise xor'ed with the current element of the input
             ,             Create a tuple containing:
              k             The index of the current element, and
               -bJ          the difference between the current element and J
    *<J     b              Put that tuple into a list if J < b, otherwise put an empty tuple
 S                     Sort the list
e                      Print the last element of the list

Pyth, 23 bytes
eSs.em*,kd!xxxFQb-bdSbQ

Try it online: Demonstration
This iterates over all possible moves and even does sorting. Therefore it has a time-complexity of O(N*log(N)) and a memory complexity of O(N), where N is the sum of the input list or the number of items.
Because of the bad time complexity, this might not be a valid answer. Though it solves all games, that you can play in real life with real objects, instantly.
Explanation:
                          implicit: Q = input list
   .e                 Q   map each (index k, item b) of Q to:
     m              Sb      map each d of [1, 2, ..., b] to:
       ,kd                      the pair (k, d)
      *                       multiplied by
             xFQ                xor of all numbers in Q
            x   b               xor with b
           x     -bd            xor with b-d
          !                     not (1 if xor==0 else 0)

So the input [1, 2, 0, 0, 5] gives [[[]], [[], []], [], [], [[], [4, 2], [], [], []]]

  s                       add all lists to one big list
 S                        sort

Now it looks like this: [[], [], [], [], [], [], [], [4, 2]]

e                         pick the last element and print

CJam, 21 20 bytes
Saved a byte compared to original version, and error handling also works now:
l~__:^f^.-_:g1#_@=S\

Try it online
Input is a CJam array, e.g.:
[1 2 3 4 5]

If no solution is found, it prints -1 0, which meets my understanding of the output requirements.
Explanation:
l~      Get input.
__      Make two copies for following operations.
:^      Reduce with xor operator, producing xor of all columns.
f^      xor all input values with the result. For each column, this calculates
        the value that the column would have to change to make the overall
        xor zero. Consider this the "target values".
.-      Subtract the target values from the input values.
_:g     Per element signum of difference between target value and input value.
1#      Find index with value 1, which is the first positive value.
_@=     Get the value at the index.
S\      Put a space between index and value.

Ruby, 95
->(a){r=[false,c=0]
a.each{|e|c^=e}
a.each_index{|i|(n=a[i]-(c^a[i]))>0&&n>r[1]?(r=[i,n]):0}
r}

I wrote 2 separate anonymous functions. The first, assigned to f in the program below, prints all solutions, and the second g (corresponding to the score above, as it is both shorter and more compliant with the spec) returns only the solution which requires removing the greatest number.
in both cases, the digit sum is totalized in c. Then the array is looped over and the expression n=a[i]-(c^a[i]) is used to calculate the number of counters to be removed (obviously this can only be done if it exceeds zero).
in f, all possible solutions are printed (if c is found to be 0, error is printed without looping.) I was surprised to see that the different piles can require quite different numbers of counters to be removed.
in g the output array r is only updated if the number of counters to be removed exceeds the previous number. the array r=[pile index, number to be removed] is returned. If there is no solution, the number of counters to be removed is always zero, r remains unchanged, and the initial value of r=[false,0] is returned.
Minor savings are possible if false can be changed to for example"!" and if any valid solution rather than the largest one can be returned (by deleting &&n>r[1].)
Formatted in test program
f=->(a){
  c=0
  a.each{|e|c^=e}
  c<1?(p "error"):(a.each_index{
     |i|(n=a[i]-(c^a[i]))>0?(p"#{i},#{n}"):0
   })
}

g=->(a){
  r=[false,c=0]
  a.each{|e|c^=e}
  a.each_index{
     |i|(n=a[i]-(c^a[i]))>0&&n>r[1]?(r=[i,n]):0
  }
  r
}

#Change the following two lines according to the number of values youj want to use for testing.
t=[rand(15),rand(15),rand(15),rand(15)] #Generate some random numbers for testing.
t=[gets.to_i,gets.to_i,gets.to_i]       #User input. Delete this line if you want to test with random numbers.
print t,"\n"

f.call(t)
puts g.call(t)

Actually, because r[1] is always at least zero, I think  >0&&n>r[1] can be shortened to >r[1]

Mathematica, 73 bytes
{f=BitXor;p=Position[#,x_/;BitAnd[x,a=f@@#]==a][[1,1]],(n=#[[p]])-n~f~a}&

What. Mathematica doesn't have a builtin for this?

JavaScript (ES6), 54 bytes
Returns either the pair [column, number] or false
a=>a.some((n,i)=>r=(n-=n^eval(a.join`^`))>0&&[i,n])&&r

Try it online!
Commented
a =>                        // a[] = input array
  a.some((n, i) =>          // for each value n at position i in a[]:
    r = (                   //   save the result of the iteration in r
      n -=                  //   subtract from n:
        n ^ eval(a.join`^`) //     n XOR (all values in a[] XOR'ed together)
    ) > 0                   //   if the above value is positive:
    && [i, n]               //     yield the solution [i, n] and exit the some() loop
                            //   (otherwise: yield false and go on with the next value)
  ) && r                    // end of some(); return r

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


text:
Triangular Square Numbers
Square numbers are those that take the form of \$n^2\$ where \$n\$ is an integer. These are also called perfect squares, because when you take their square root you get an integer.
The first 10 square numbers are: (OEIS)
0, 1, 4, 9, 16, 25, 36, 49, 64, 81

Triangular numbers are numbers that can form an equilateral triangle. The n-th triangle number is equal to the sum of all natural numbers from 1 to n.
The first 10 triangular numbers are: (OEIS)
0, 1, 3, 6, 10, 15, 21, 28, 36, 45

Square triangular numbers are numbers that are both square and triangular.
The first 10 square triangular numbers are: (OEIS)
0, 1, 36, 1225, 41616, 1413721, 48024900, 1631432881, 55420693056, 1882672131025, 63955431761796

There is an infinite number of square numbers, triangle numbers, and square triangular numbers.
Write a program or named function that given an input (parameter or stdin) number \$n\$, calculates the \$n\$th square triangular number and outputs/returns it, where n is a positive nonzero number. (For \$n=1\$ return 0)
For the program/function to be a valid submission it should be able to return at least all square triangle numbers smaller than \$2^{31}-1\$.
Bonus
-4 bytes for being able to output all square triangular numbers less than 2^63-1
-4 bytes for being able to theoretically output square triangular numbers of any size.
+8 byte penalty for solutions that take nonpolynomial time.
Bonuses stack.
This is code-golf challenge, so the answer with the fewest bytes wins.

I have added an 8 byte penalty for solutions that take >O(n) time to make it more fair for those who aim for faster code.

@Rodolvertice I don't think you mean linear time. The iterative solution I have is quadratic time because there are n steps, and in each step the arithmetic takes linear time because the number of digits grows linearly in n. I don't think linear time is possible. Unless you're saying arithmetic operations are constant time?

@xnor You said that your answer should not qualify for the bonuses because it is in exponential time, so thats what caused me to think there was a way to do it in linear time. Yes I assumed arithmetic is constant time, or at least close enough to constant to call it constant time. Does linear amortized time better fit the description?

@xnor then again your solution would be linear time by that definition if I'm not mistaken.

@Rodolvertice I mean that my iterative solution is not O(n). I think the cleaner thing to do is say "polynomial time" instead. If you assume linear time arithmetic, you get weird things like a solution using exponentiation being called constant time. Amortization doesn't come into play here.

@xnor you mean constant time arithmetic in that sentence, right?

Hardcoding the numbers could be competitive, especially in a language with good base-255 to decimal conversion.

@ThomasKwa You are completely right, they would only need to hardcode 8 4-byte integers! Thats 8*4= 32 bytes, at minimum, and cannot claim any bonus. I think I will let this be, unless theres a good reason not to.

love to see something like that tagged in [tag:fastest-code]

All real solutions (as opposed to those which hard-code the first few values) take non-polynomial time, because the size of the output is exponential in the size of the input.

I don't want to encourage hardcoding, so I removed the 8 byte penalty.

"The first 10 square triangular numbers..." Surely you meant 11? :P

CJam, 12 8 bytes
XUri{_34*@-Y+}*;

Makes use of the recurrence relation from the Wikipedia article.
The code is 16 bytes long and qualifies for both bonuses.
Try it online in the CJam interpreter.
How it works
My code turned out to be identical to xnor's in always every aspect, except that I use CJam's stack instead of variables.
XU               e# Push 1 and 0 on the stack.
                 e# Since 34 * 0 - 1 + 2 = 1, this compensates for 1-based indexing.
  ri{        }*  e# Do int(input()) times:
     _34*        e#   Copy the topmost integer and multiply it by 34.
         @-      e#   Subtract the bottommost integer from the result.
           Y+    e#   Add 2.
               ; e# Discard the last result.

It runs instantly for very large inputs, but over 3000 it gives a Javascript range error on the online interpreter. Im going to try it on the java implementation.

@Rodolvertice: I've switched to an iterative approach. It's actually shorter and it's less memory intensive.

Python 2, 45 - 4 - 4 = 37
a=1;b=0
exec"a,b=b,34*b-a+2;"*input()
print a

Iterates using the reccurence
f(0) = 1
f(1) = 0
f(k) = 34*f(k-1)-f(k-2)+2

In theory, this supports numbers of any size, but runs in exponential time, so it shouldn't qualify for the bonuses. Should work for numbers of any size. For example, for 100, gives
1185827220993342542557325920096705939276583904852110550753333094088280194260929920844987597980616456388639477930416411849864965254621398934978872054025

A recursive solution uses 41 chars, but shouldn't qualify because it takes exponential time.
f=lambda k:k>2and 34*f(k-1)-f(k-2)+2or~-k

That is quite cheaty, a 'loop' by string multiplication, haha.

@Rodolvertice: Not cheaty at all really. Rather clever, and indeed fairly common on the site.

I believe your recursive solution qualifies for bonus #1, which would have it tied with the exec solution. If you're allowed to change recursion limit, then it also could calculate a square triangle number of any size, qualifying it for #2. However, I'm not sure if that qualifies (@Rodolvertice).

Pyth, 16 - 4 - 4 = 8 bytes
Uses the recursive formula from the OEIS article.
K1uhh-*34G~KGtQZ

It uses the post-assign command which is pretty new and seems really cool. Uses reduce to iterate n-1 times because of 1-based indexing.
K1            Set K=1
u       tQ    Reduce input()-1 times
         Z    With zero as base case
 hh            +2
  -           Subtract
   *34G       34 times iterating variable
   ~K         Assign to K and use old value
    G         Assign the iterating variable.

Seems to be polynomial because it loops n times and does math & assignment each iteration, but I'm not a computer scientist. Finishes n=10000 almost instantly.
Try it here online.

I think you can avoid subtracting 1 from the input if you start one iteration back at 0,1 rather than 1,0 -- see my Python answer.

@xnor: I think he already does that. However, the result returned by the loop is your b.

Oasis, 7 - 4 - 4 = -1
34*c-»T

Try it online!
Uses a(0) = 0, a(1) = 1; for n >= 2, a(n) = 34 * a(n-1) - a(n-2) + 2
Oasis supports arbitrary precision integers, so it should be able to go up to any number so long as no stack overflowing occurs. Let me know if this does not count for the bonus because of stack overflowing. It is also possible that this particular algorithm is non-polynomial, and let me know if that is the case.
Explanation:
34*c-»T -> 34*c-»10

a(0) = 0
a(1) = 1
a(n) = 34*c-»

34*c-»
34*    # 34*a(n-1)
   c-  # 34*a(n-1)-a(n-2)
     » # 34*a(n-1)-a(n-2)+2

Alternative solution:
-35*d+T

Instead uses a(n) = 35*(a(n-1)-a(n-2)) + a(n-3)

The question says For n=1 return 0, but this returns 1. This is fixable by adding the -O option.

JavaScript (ES6), 29-4 = 25 bytes
n=>n>1?34*f(n-1)-f(n-2)+2:n|0

Saved 5 bytes thanks to @IsmaelMiguel!
I've had to hardcode the 0, 1 and the negatives to avoid infinite recursion.
Console, I've named the function, f:
f(1);  // 0
f(13); // 73804512832419600
f(30); // 7.885505171090779e+42 or 7885505171090779000000000000000000000000000

EDIT: Turns out JavaScript will round the numbers to 16 (15) digits (Spec) because these numbers are too big causing an overflow. Put 714341252076979033 In your JavaScript console and see for yourself. It's more of a limitation of JavaScript

I don't think this qualifies for the bonus. f(15) should return 85170343853180456676, not 85170343853180450000.

@Dennis JavaScript must be truncating it.  .-. Yup, JavaScript rounds to 16 digits when

Try this one: n=>n?n<2?0:34*f(n-1)-f(n-2)+2:1 (31 bytes). I've tested till the 5th number.

Here you now have a 29-bytes long solution: n=>n>1?34*f(n-1)-f(n-2)+2:!!n. It returns false on 0, true on 1 and 36 on 2. If you want it to return a number, you can replace !!n with +!!n.

Fixed the problem. Use this: n=>n>1?34*f(n-1)-f(n-2)+2:n|0 (same byte count, now returns always numbers)

Excel VBA - 90 bytes
Using the recurrence relation from the Wikipedia page:
n = InputBox("n")
x = 0
y = 1
For i = 1 To n
Cells(i, 1) = x
r = 34 * y - x + 2
x = y
y = r
Next i

When executed you are prompted for n, then the sequence up to and including n is output to column A:

It can be run up to and including n = 202 before it gives an overflow error.

[Not Competing] Pyth (14 - 4 - 4 = 6 bytes)
K1u/^tG2~KGQ36

Used the first recurrence from OEIS, that after 0,1,36 you can find An = (An-1-1)2/An-2. A Not competing because this solution starts at 36, if you go lower you divide by zero (so input of 0 gives 36). Also had to hardcode 36.
Try it here

This is OK as input will be nonzero.

Java, 53 - 4 = 49 bytes
It's another simple recursion, but I don't often get to post Java with a <50 score, so...
long g(int n){return n<2?n<1?1:0:34*g(n-1)-g(n-2)+2;}

Now, for something non-recursive, it gets quite a bit longer. This one is both longer (112-4=108) -and- slower, so I'm not sure why I'm posting it except to have something iterative:
long f(int n){long a=0,b,c,d=0;for(;a<1l<<32&n>0;)if((c=(int)Math.sqrt(b=(a*a+a++)/2))*c==b){d=b;n--;}return d;}

Julia, 51 bytes - 4 - 4 = 43
f(n)=(a=b=big(1);b-=1;for i=1:n a,b=b,34b-a+2end;a)

This uses the first recurrence relation listed on the Wikipedia page for square triangular numbers. It computes n = 1000 in 0.006 seconds, and n = 100000 in 6.93 seconds. It's a few bytes longer than a recursive solution but it's way faster.
Ungolfed + explanation:
function f(n)
    # Set a and b to be big integers
    a = big(1)
    b = big(0)

    # Iterate n times
    for i = 1:n
        # Use the recurrence relation, Luke
        a, b = b, 34*b - a + 2
    end

    # Return a
    a
end

Examples:
julia> for i = 1:4 println(f(i)) end
0
1
36
1225

julia> @time for i = 1:1000 println(f(i)) end
0
... (further printing omitted here)
elapsed time: 1.137734341 seconds (403573226 bytes allocated, 38.75% gc time)

PHP, 65 59 56-4=52 bytes
while($argv[1]--)while((0|$r=sqrt($s+=$f++))-$r);echo$s;

repeat until square root of $s is ∈ℤ: add $f to sum $s, increment $f;
repeat $argv[1] times.
output sum.

Jelly, 13 - 8 = 5 bytes
This qualifies for both bonuses.
×8‘,µÆ²Ạ
0Ç#Ṫ

Try it online!
Done alongside caird coinheringaahing in chat.
Explanation

×8‘,µÆ²Ạ  ~ Helper link.

×8        ~ 8 times the number.
  ‘       ~ Increment.
   ,      ~ Paired with the current number.
    µ     ~ Starts a new monadic (1-arg) link.
     Æ²   ~ Vectorized "Is Square?".
       Ạ  ~ All. Return 1 only if both are truthy.

0Ç#Ṫ  ~ Main link.

0 #   ~ Starting from 0, collect the first N integers with truthy results, when applied:
 Ç    ~ The last link as a monad.
   Ṫ  ~ Last element. Output implicitly.

11 - 8 = 3 bytes

@cairdcoinheringaahing Hi, feel free to edit or post a different submission!

It's basically the same as yours (it doesn't even use any features that weren't available in 2017), so I don't reckon it warrants another answer

Perl 6, 25 - 8 = 17 bytes
{(0,1,2-*+34* *…*)[$_]}

Try it online!

05AB1E, 10 - 8 = 2 bytes
1ÎGDŠ34*Ìα

Try it online!

And I thought I was clever using λ...

APL (Dyalog Extended), 23-4-4 = 15 bytes
{⍵<2:⍵⋄2+-/34 1×∇¨⍵-⍳2}

Recursive dfn
⍵<2:⍵ is ⍵ less than 2, if so return ⍵
⋄ otherwise
∇¨⍵-⍳2 apply the function (∇) to the two previous values
34 1× multiply by the array 34 1
-/ subtract
2+ add 2
Try it online!

Prolog, 70 74 - 4 - 4 = 66
n(X,R):-n(X,0,1,R).
n(X,A,B,R):-X=0,R=A;Z is X-1,E is 34*B-A+2,n(Z,B,E,R).

Running n(100,R) outputs:
X = 40283218019606612026870715051828504163181534465162581625898684828251284020309760525686544840519804069618265491900426463694050293008018241080068813316496

Takes about 1 second to run n(10000,X) on my computer.
Edit: The 66 version is tail-recursive. The previous non-tail-recursive version is the following:
n(X,[Z|R]):-X>1,Y is X-1,n(Y,R),R=[A,B|_],Z is 34*A-B+2;X=1,Z=1,R=[0];Z=0.

They have the same length in bytes but the non-tail-recursive generates stack overflows past a certain point (on my computer, around 20500).

Javascript ES6, 77 75 71 chars
// 71 chars
f=n=>{for(q=t=w=0;n;++q)for(s=q*q;t<=s;t+=++w)s==t&&--n&console.log(s)}

// No multiplication, 75 chars
f=n=>{for(s=t=w=0,q=-1;n;s+=q+=2)for(;t<=s;t+=++w)s==t&&--n&console.log(s)}

// Old, 77 chars
f=n=>{for(s=t=w=0,q=-1;n;s+=q+=2){for(;t<s;t+=++w);s==t&&--n&console.log(s)}}

The solution is linear.
The solution can output all numbers less then 2^53 because of numbers type.
The algorithm itself can be used for unlimited numbers.

Test:
f(11)

0
1
36
1225
41616
1413721
48024900
1631432881
55420693056
1882672131025
63955431761796

C, 68 bytes
This was a fun challenge with C
main(o,k){o==1?k=0:0;k<9e9&&k>=0&&main(34*o-k+2,o,printf("%d,",k));}
Watch it run here: https://ideone.com/0ulGmM

APL(NARS), 67 chars, 134 bytes
r←f w;c;i;m
c←0⋄i←¯1⋄r←⍬
→2×⍳0≠1∣√1+8×m←i×i+←1⋄r←r,m⋄→2×⍳w>c+←1

test:
  f 10
0 1 36 1225 41616 1413721 48024900 1631432881 55420693056 1882672131025

f would search in quadratic sequence the elements that are triangulars number too, so they have to
follow the triangular check formula in APLs: 0=1∣√1+8×m with number m to check.

x86_64 machine code - 46 bytes
Borrowed code from Albert Renshaw C answer.
47 bytes using ret instruction.
0000000000400080 <triangular_square>:
  400080:   48 31 d2                xor    rdx,rdx      # rdx = 0
  400083:   6a 00                   push   0x0
  400085:   41 58                   pop    r8           # r8 = 0
  400087:   48 ff c3                inc    rbx          # rbx = 1
  40008a:   49 89 d8                mov    r8,rbx       # copy rbx value to r8

000000000040008d <triangular_square.loop>:
  40008d:   e3 1f                   jrcxz  4000ae <triangular_square.done>  # if rcx is zero go to .done
  40008f:   4d 6b c0 22             imul   r8,r8,0x22   # r8 * 0x22 (34)
  400093:   49 29 d0                sub    r8,rdx       # r8 - rdx
  400096:   49 83 c0 02             add    r8,0x2       # r8 + 2
  40009a:   4d 89 c1                mov    r9,r8        # copy r8 value to r9
  40009d:   48 ff c2                inc    rdx          # rdx + 1
  4000a0:   48 ff ca                dec    rdx          # rdx - 1
  4000a3:   48 87 da                xchg   rdx,rbx      # swap rbx value with rdx value
  4000a6:   4c 89 cb                mov    rbx,r9       # copy r9 value to rbx
  4000a9:   4c 89 c0                mov    rax,r8       # copy r8 value to rax (output)
  4000ac:   e2 df                   loop   40008d <triangular_square.loop>  # keep looping until rcx is zero

00000000004000ae <triangular_square.done>:

Input in rcx output in rax. You can use debugger to test it.
TODO: Make a tester program on TIO.

Husk, 14 20 - 8 = 12 bytes
→!¡otS:o+2§-←o*34→ḋ2

Try it online!
Uses the same recurrence relation as the CJam answer. There's probably a better way to do this.
Husk, 8 - 4 = 4 bytes
!Θf£∫Nİ□

Try it online!
it can theoretically output square triangular numbers of any size, but list intersection causes a stack overflow for anything above 3.
Instead of n uses f£, which is optimized for infinite lists.
Getting numbers takes a long, long, long time after 4.

The second program doesn't work even in theory. You need f£ in place of n to handle infinite lists.

I'll note that down. Thanks! @Zgarb

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


text:
Ionic Compound Golf
Challenge
Given two inputs, a positive ion and a negative ion, you must output the formula for the ionic compound which would be made from the two ions. This basically means balancing out the charges so they equal zero.
Do not bother with formatting the formula with subscript numbers, but you must have brackets for the multi-atom ions (such as NO3).
You do not have to account for any errors (for example, if someone inputs two negative ions, you can just let the program fail).
Note: Take Fe to have a charge of 3+
Ions
All of the ions which need to be accounted for are found along with their charges on the second part of the AQA GCSE Chemistry Data Sheet.
Positive ions

H+
Na+
Ag+
K+
Li+
NH4+
Ba2+
Ca2+
Cu2+
Mg2+
Zn2+
Pb2+
Fe3+
Al3+

Negative ions

Cl-
Br-
F-
I-
OH-
NO3-
O2-
S2-
SO42-
CO32-

Examples
Some examples:
H and O returns:- H2O
Ca and CO3 returns:- CaCO3
Al and SO4 returns:- Al2(SO4)3
Note the following case that you must account for:
H and OH returns:- H2O not H(OH)

Is the positive ion always listed first?

Does Fe have a charge of 2+ or 3+?

@xnor No, they can switch

This reminds me of my chemistry class I had one year ago. Balancing stuff...

I assume brackets must be used when necessary and only when necessary. Correct?

@steveverill Correct

You currently specify Fe3+, but list Fe2+

@trichplax Whoops!

This is very similar to the challenge Balance Chemical Equations although a bit easier.

CJam, 176 bytes
"O S SO4 CO3 ""Cl Br F I OH NO3 """"H Na Ag K Li NH4 ""Ba Ca Cu Mg Zn Pb ""Fe Al "]_2{r\1$S+f#Wf=0#((z@}*_2$*_4=2*-_@/\@/@\]2/{~_({1$1>_el={'(@@')\}|0}&;}/]s"HOHH"1$#){;"H2O"}&

Try it online
This was somewhat painful, particularly with all the special cases for parentheses, showing counts, the H2O, etc.
The data is not in a super compact format. It could be trimmed more, but the code needed to interpret it would probably compensate for the savings. So I went with an array of strings, where each string contains the atoms with the same charge, ordered from -2 to +3 (where the string for 0 is empty).
Explanation:
[..]  Data, as explained above.
_     Duplicate data, will need it for both inputs.
2{    Loop over two inputs.
  r     Get input.
  \     Swap data to top.
  1$    Copy input to top (keep original for later).
  S+    Add a space to avoid ambiguity when searching in data.
  f#    Search for name in all strings of data.
  Wf=   Convert search results to truth values by comparing them to -1.
  0#    Find the 0 entry, which gives the index of the matching string.
  ((    Subtract 2, to get charge in range [-2, 3] from index.
  z     Absolute value, we don't really care about sign of charge.
  @     Swap second copy of data table to proper position for next input.
}*    End loop over two inputs.
_2$*  Multiply the two charges.
_4=   We need the LCM. But for the values here, only product 4 is not the LCM.
2*-   So change it to 2.
_@/   Divide LCM by first charge to get first count.
\@/   Divide LCM by second charge to get second count.
@\]2/ Make pairs of name/count for both ions...
{     ... and loop over the pairs.
  ~     Unpack the pair.
  _(    Check if count is > 1.
  {       Handle count > 1.
    1$    Get copy of name to top of stack.
    1>    Slice off first character to check if rest contains upper case.
    _el   Create lower case copy.
    =     If they are different, there are upper case letters.
    {       Handle case where parentheses are needed.
      '(    Opening parentheses.
      @@    Some stack shuffling to get values in place.
      ')    Closing parentheses.
      \     And one more swap to place count after parentheses.
    }|    End parentheses handling.
    0     Push dummy value to match stack layout of other branch.
  }&    End count handling.
  ;     Pop unused count off stack.
}/    End loop over name/count pairs.
]s    Pack stack content into single string, for H2O handling.
"HOHH"  String that contains both HOH and OHH, which need to be H2O.
1$#)  Check if output is in that string.
{     If yes, replace with H2O.
  ;     Drop old value.
  "H2O" And make it H2O instead.
}&    End of H2O handling.

Lua, 174 242 bytes
I forgot the brackets '-_-, that got me up to 242. Oh well, it was a fun enough challenge at least.
i,c,a={Ba=2,Ca=2,Cu=2,Mg=2,Zn=2,Pb=2,Fe=3,Al=3,O=2,S=2,SO4=2,CO3=2},io.read(),io.read()
p,d=i[c]~=i[a],{SO4=1,NO3=1,OH=1,CO3=1}
k,m=p and i[c]or'',p and i[a]or''
a=k==m and a or (d[a]and'('..a..')'or a)
print(c..a=='HOH'and'H2O'or c..m..a..k)

Try it online!
Old version:
i,c,a={Ba=2,Ca=2,Cu=2,Mg=2,Zn=2,Pb=2,Fe=3,Al=3,O=2,S=2,SO4=2,CO3=2},io.read(),io.read()
p=i[c]~=i[a]
k,m=p and i[c]or'',p and i[a]or''
print(c..a=='HOH'and'H2O'or c..m..a..k)

Abusing Lua's tendency to initialize everything with a nil value we can cut down on storage costs. Still, Lua is still a bit clunky :(

Your output should support having parentheses in it. So Al and SO4 should output Al2(SO4)3, but you output Al2SO43. Try it online

Yeah, only realized that some 5 minutes after I hit send. '-_-. It should work now.

Now it outputs parens when it doesn't need to. Try Ca and CO3. Also, you should add the TIO link to your answer.

There! Sorry, I didn't know about the TIO thing. My bad.

It's just helpful for users wanting to run your code.

Java (619 647 667 bytes)
[Fixed] Update: H + OH returns HOH even though I hard coded it not to.... working on it
[Fixed] Update: Sometimes Parenthesis appear when they shouldn't
Code
String f(String[]a){if(Arrays.equals(a,new String[]{"H","OH"})|Arrays.equals(a,new String[]{"OH","H"}))return "H2O";List<String>b=Arrays.asList(new String[]{"H","Na","Ag","K","Li","NH4","Ba","Ca","Cu","Mg","Zn","Pb","Fe","Al","Cl","Br","F","I","OH","NO3","O","S","SO4","CO3"});Integer[]c={1,1,1,1,1,1,2,2,2,2,2,2,3,3,1,1,1,1,1,1,2,2,2,2},d={5,18,19,22,23};List<Integer>j=Arrays.asList(d);int e=b.indexOf(a[0]),f=b.indexOf(a[1]),g=c[e],h=c[f],i;if(f<e){String p=a[0];a[0]=a[1];a[1]=p;i=g;g=h;h=i;i=e;e=f;f=i;}boolean k=j.contains(e),l=j.contains(f),m=g==h,n=g==1,o=h==1;return (k&!m&!o?"("+a[0]+")":a[0])+(m?"":h==1?"":h)+(l&!m&!n?"("+a[1]+")":a[1])+(m?"":g==1?"":g);}

I wasn't sure how to do this without hard coding every ions charge, so it ended up being long. Lucky cause all the charges are 1, 2, or 3 so finding the amount of each ion is easy.
Expanded
import java.util.Arrays;
import java.util.List;
public class Compound {
    public static void main(String[]a){
        //System.out.println(f(a));
        String[] pos = new String[]{"H","Na","Ag","K","Li","NH4","Ba","Ca","Cu","Mg","Zn","Pb","Fe","Al"};
        String[] neg = new String[]{"Cl","Br","F","I","OH","NO3","O","S","SO4","CO3"};
        for(int i = 0; i < pos.length; i++){
            for(int j = 0; j < neg.length; j++){
                System.out.println(pos[i] + " + " + neg[j] + " = " + f(new String[]{pos[i],neg[j]}));
                System.out.println(neg[j] + " + " + pos[i] + " = " + f(new String[]{neg[j],pos[i]}));
            }
        }
    }
    static String f(String[]a){
        if(Arrays.equals(a,new String[]{"H","OH"})|Arrays.equals(a,new String[]{"OH","H"}))
            return "H2O";
        List<String>b=Arrays.asList(new String[]{"H","Na","Ag","K","Li","NH4","Ba","Ca","Cu","Mg","Zn","Pb","Fe","Al","Cl","Br","F","I","OH","NO3","O","S","SO4","CO3"});
        Integer[]c={1,1,1,1,1,1,2,2,2,2,2,2,3,3,1,1,1,1,1,1,2,2,2,2},d={5,18,19,22,23};
        List<Integer>j=Arrays.asList(d);
        int e=b.indexOf(a[0]),f=b.indexOf(a[1]),g=c[e],h=c[f],i;
        if(f<e){String p=a[0];a[0]=a[1];a[1]=p;i=g;g=h;h=i;i=e;e=f;f=i;}
        boolean k=j.contains(e),l=j.contains(f),m=g==h,n=g==1,o=h==1;
        return (k&!m&!o?"("+a[0]+")":a[0])+(m?"":o?"":h)+(l&!m&!n?"("+a[1]+")":a[1])+(m?"":n?"":g);
    }
}

Try it here
Data
Let me know if any of them are wrong
H + Cl = HCl
Cl + H = HCl
H + Br = HBr
Br + H = HBr
H + F = HF
F + H = HF
H + I = HI
I + H = HI
H + OH = H2O
OH + H = H2O
H + NO3 = HNO3
NO3 + H = HNO3
H + O = H2O
O + H = H2O
H + S = H2S
S + H = H2S
H + SO4 = H2SO4
SO4 + H = H2SO4
H + CO3 = H2CO3
CO3 + H = H2CO3
Na + Cl = NaCl
Cl + Na = NaCl
Na + Br = NaBr
Br + Na = NaBr
Na + F = NaF
F + Na = NaF
Na + I = NaI
I + Na = NaI
Na + OH = NaOH
OH + Na = NaOH
Na + NO3 = NaNO3
NO3 + Na = NaNO3
Na + O = Na2O
O + Na = Na2O
Na + S = Na2S
S + Na = Na2S
Na + SO4 = Na2SO4
SO4 + Na = Na2SO4
Na + CO3 = Na2CO3
CO3 + Na = Na2CO3
Ag + Cl = AgCl
Cl + Ag = AgCl
Ag + Br = AgBr
Br + Ag = AgBr
Ag + F = AgF
F + Ag = AgF
Ag + I = AgI
I + Ag = AgI
Ag + OH = AgOH
OH + Ag = AgOH
Ag + NO3 = AgNO3
NO3 + Ag = AgNO3
Ag + O = Ag2O
O + Ag = Ag2O
Ag + S = Ag2S
S + Ag = Ag2S
Ag + SO4 = Ag2SO4
SO4 + Ag = Ag2SO4
Ag + CO3 = Ag2CO3
CO3 + Ag = Ag2CO3
K + Cl = KCl
Cl + K = KCl
K + Br = KBr
Br + K = KBr
K + F = KF
F + K = KF
K + I = KI
I + K = KI
K + OH = KOH
OH + K = KOH
K + NO3 = KNO3
NO3 + K = KNO3
K + O = K2O
O + K = K2O
K + S = K2S
S + K = K2S
K + SO4 = K2SO4
SO4 + K = K2SO4
K + CO3 = K2CO3
CO3 + K = K2CO3
Li + Cl = LiCl
Cl + Li = LiCl
Li + Br = LiBr
Br + Li = LiBr
Li + F = LiF
F + Li = LiF
Li + I = LiI
I + Li = LiI
Li + OH = LiOH
OH + Li = LiOH
Li + NO3 = LiNO3
NO3 + Li = LiNO3
Li + O = Li2O
O + Li = Li2O
Li + S = Li2S
S + Li = Li2S
Li + SO4 = Li2SO4
SO4 + Li = Li2SO4
Li + CO3 = Li2CO3
CO3 + Li = Li2CO3
NH4 + Cl = NH4Cl
Cl + NH4 = NH4Cl
NH4 + Br = NH4Br
Br + NH4 = NH4Br
NH4 + F = NH4F
F + NH4 = NH4F
NH4 + I = NH4I
I + NH4 = NH4I
NH4 + OH = NH4OH
OH + NH4 = NH4OH
NH4 + NO3 = NH4NO3
NO3 + NH4 = NH4NO3
NH4 + O = (NH4)2O
O + NH4 = (NH4)2O
NH4 + S = (NH4)2S
S + NH4 = (NH4)2S
NH4 + SO4 = (NH4)2SO4
SO4 + NH4 = (NH4)2SO4
NH4 + CO3 = (NH4)2CO3
CO3 + NH4 = (NH4)2CO3
Ba + Cl = BaCl2
Cl + Ba = BaCl2
Ba + Br = BaBr2
Br + Ba = BaBr2
Ba + F = BaF2
F + Ba = BaF2
Ba + I = BaI2
I + Ba = BaI2
Ba + OH = Ba(OH)2
OH + Ba = Ba(OH)2
Ba + NO3 = Ba(NO3)2
NO3 + Ba = Ba(NO3)2
Ba + O = BaO
O + Ba = BaO
Ba + S = BaS
S + Ba = BaS
Ba + SO4 = BaSO4
SO4 + Ba = BaSO4
Ba + CO3 = BaCO3
CO3 + Ba = BaCO3
Ca + Cl = CaCl2
Cl + Ca = CaCl2
Ca + Br = CaBr2
Br + Ca = CaBr2
Ca + F = CaF2
F + Ca = CaF2
Ca + I = CaI2
I + Ca = CaI2
Ca + OH = Ca(OH)2
OH + Ca = Ca(OH)2
Ca + NO3 = Ca(NO3)2
NO3 + Ca = Ca(NO3)2
Ca + O = CaO
O + Ca = CaO
Ca + S = CaS
S + Ca = CaS
Ca + SO4 = CaSO4
SO4 + Ca = CaSO4
Ca + CO3 = CaCO3
CO3 + Ca = CaCO3
Cu + Cl = CuCl2
Cl + Cu = CuCl2
Cu + Br = CuBr2
Br + Cu = CuBr2
Cu + F = CuF2
F + Cu = CuF2
Cu + I = CuI2
I + Cu = CuI2
Cu + OH = Cu(OH)2
OH + Cu = Cu(OH)2
Cu + NO3 = Cu(NO3)2
NO3 + Cu = Cu(NO3)2
Cu + O = CuO
O + Cu = CuO
Cu + S = CuS
S + Cu = CuS
Cu + SO4 = CuSO4
SO4 + Cu = CuSO4
Cu + CO3 = CuCO3
CO3 + Cu = CuCO3
Mg + Cl = MgCl2
Cl + Mg = MgCl2
Mg + Br = MgBr2
Br + Mg = MgBr2
Mg + F = MgF2
F + Mg = MgF2
Mg + I = MgI2
I + Mg = MgI2
Mg + OH = Mg(OH)2
OH + Mg = Mg(OH)2
Mg + NO3 = Mg(NO3)2
NO3 + Mg = Mg(NO3)2
Mg + O = MgO
O + Mg = MgO
Mg + S = MgS
S + Mg = MgS
Mg + SO4 = MgSO4
SO4 + Mg = MgSO4
Mg + CO3 = MgCO3
CO3 + Mg = MgCO3
Zn + Cl = ZnCl2
Cl + Zn = ZnCl2
Zn + Br = ZnBr2
Br + Zn = ZnBr2
Zn + F = ZnF2
F + Zn = ZnF2
Zn + I = ZnI2
I + Zn = ZnI2
Zn + OH = Zn(OH)2
OH + Zn = Zn(OH)2
Zn + NO3 = Zn(NO3)2
NO3 + Zn = Zn(NO3)2
Zn + O = ZnO
O + Zn = ZnO
Zn + S = ZnS
S + Zn = ZnS
Zn + SO4 = ZnSO4
SO4 + Zn = ZnSO4
Zn + CO3 = ZnCO3
CO3 + Zn = ZnCO3
Pb + Cl = PbCl2
Cl + Pb = PbCl2
Pb + Br = PbBr2
Br + Pb = PbBr2
Pb + F = PbF2
F + Pb = PbF2
Pb + I = PbI2
I + Pb = PbI2
Pb + OH = Pb(OH)2
OH + Pb = Pb(OH)2
Pb + NO3 = Pb(NO3)2
NO3 + Pb = Pb(NO3)2
Pb + O = PbO
O + Pb = PbO
Pb + S = PbS
S + Pb = PbS
Pb + SO4 = PbSO4
SO4 + Pb = PbSO4
Pb + CO3 = PbCO3
CO3 + Pb = PbCO3
Fe + Cl = FeCl3
Cl + Fe = FeCl3
Fe + Br = FeBr3
Br + Fe = FeBr3
Fe + F = FeF3
F + Fe = FeF3
Fe + I = FeI3
I + Fe = FeI3
Fe + OH = Fe(OH)3
OH + Fe = Fe(OH)3
Fe + NO3 = Fe(NO3)3
NO3 + Fe = Fe(NO3)3
Fe + O = Fe2O3
O + Fe = Fe2O3
Fe + S = Fe2S3
S + Fe = Fe2S3
Fe + SO4 = Fe2(SO4)3
SO4 + Fe = Fe2(SO4)3
Fe + CO3 = Fe2(CO3)3
CO3 + Fe = Fe2(CO3)3
Al + Cl = AlCl3
Cl + Al = AlCl3
Al + Br = AlBr3
Br + Al = AlBr3
Al + F = AlF3
F + Al = AlF3
Al + I = AlI3
I + Al = AlI3
Al + OH = Al(OH)3
OH + Al = Al(OH)3
Al + NO3 = Al(NO3)3
NO3 + Al = Al(NO3)3
Al + O = Al2O3
O + Al = Al2O3
Al + S = Al2S3
S + Al = Al2S3
Al + SO4 = Al2(SO4)3
SO4 + Al = Al2(SO4)3
Al + CO3 = Al2(CO3)3
CO3 + Al = Al2(CO3)3

Note
I started in Pyth, but then I got annoyed with the order and the parenthesis, here is what I had if anyone wants to finish it.
=G["H" "Na" "Ag" "K" "Li" "NH4" "Ba" "Ca" "Cu" "Mg" "Zn" "Pb" "Fe" "Al" "Cl" "Br" "F" "I" "OH" "NO3" "O" "S" "SO4" "CO3" 1 1 1 1 1 1 2 2 2 2 2 2 3 3 1 1 1 1 1 1 2 2 2 2)J@G+24xG@QZK@G+24xG@Q1@QZ?kqJKK@Q1?kqJKJ

What was the problem with H and OH?

It's fixed, before it was returning H + OH = HOH not H2O

I mean what was it that was making it return HOH instead of H20?

Looks like there are some unneeded parentheses, at least the way I read the rules. For example, in H + SO4, I think the result should be H2SO4, without parentheses.

@RetoKoradi I noticed right before I read your comment, but it's been fixed now. Thanks.

@BetaDecay I had a==new String{"O","OH"} but that isn't correct it needs to be Arrays.equals(a,new String{"O","OH"})

CoffeeScript, 371 333 bytes
This count includes newlines (some newlines can be replaced with semicolons but that wouldn't affect character count)
f=(x,y)->(i='indexOf';d='~NH4KNaAgLiBa~CaCuMgZnPbFeAlSO4CO3ClBrFIOHNO3';k=d[i] x;r=-1+Math.ceil k/11;l=d[i] y;a=if k<28then x else y
b=if k<28then y else x
s=if b=='F'then 0else 32>l
r=s=0if r==s;a='(NH4)'if'NH4'==a&&s;b='('+b+')'if/[A-Z]{2}/.test(b)&&r;if'H'==a&&b=='OH'then'H2O'else a+(if!s then''else 1+s)+b+(if!r then''else 1+r))

# Original attempt, 371 bytes
p={H:1,Na:1,Ag:1,K:1,Li:1,NH4:1,Ba:2,Ca:2,Cu:2,Mg:2,Zn:2,Pb:2,Fe:3,Al:3}
n={Cl:1,Br:1,F:1,I:1,OH:1,NO3:1,O:2,S:2,SO4:2,CO3:2}
f=(x,y)->(a=if p[x]then x else y
b=if p[x]then y else x
z=p[a]==n[b]==2;r=+z||n[b];s=+z||p[a];if--r&&a=='NH4'then a='(NH4)'
if--s&&/[A-Z]{2}/.test(b)then b='('+b+')'
if'H'==a&&b=='OH'then'H2O'else a+(if!r then''else r+1)+b+(if!s then''else s+1))

JavaScript (ES6), 316 277 bytes
I've globalized the p and n variables (just like I did in CoffeeScript) for easier testing. Localizing the variables would not make a difference in character count.
f=(x,y)=>{i='indexOf',d='~NH4KNaAgLiBa~CaCuMgZnPbFeAlSO4CO3ClBrFIOHNO3',k=d[i](x),l=d[i](y),a=k<28?x:y,b=k<28?y:x,r=Math.ceil(k/11)-1,s=b=='F'?0:l<32;if(r==s)r=s=0;a=s&&a=='NH4'?'(NH4)':a;b=r&&/[A-Z]{2}/.test(b)?`(${b})`:b;return'H'==a&&b=='OH'?'H2O':a+(s?s+1:'')+b+(r?r+1:'')}

// Original attempt, 316 bytes
p={H:1,Na:1,Ag:1,K:1,Li:1,NH4:1,Ba:2,Ca:2,Cu:2,Mg:2,Zn:2,Pb:2,Fe:3,Al:3},n={Cl:1,Br:1,F:1,I:1,OH:1,NO3:1,O:2,S:2,SO4:2,CO3:2},f=(x,y)=>{a=p[x]?x:y,b=p[x]?y:x,z=p[a]==2&&n[b]==2,r=+z||n[b],s=+z||p[a];a=--r&&a=='NH4'?'(NH4)':a;b=--s&&/[A-Z]{2}/.test(b)?`(${b})`:b;return'H'==a&&b=='OH'?'H2O':a+(r?r+1:'')+b+(s?s+1:'')}

ES5 variant, 323 284 bytes
Not much changes apart from getting rid of the arrow function and template string:
f=function(x,y){i='indexOf',d='~NH4KNaAgLiBa~CaCuMgZnPbFeAlSO4CO3ClBrFIOHNO3',k=d[i](x),l=d[i](y),a=k<28?x:y,b=k<28?y:x,r=Math.ceil(k/11)-1,s=b=='F'?0:l<32;if(r==s)r=s=0;a=s&&a=='NH4'?'(NH4)':a;b=r&&/[A-Z]{2}/.test(b)?'('+b+')':b;return'H'==a&&b=='OH'?'H2O':a+(s?s+1:'')+b+(r?r+1:'')}

// Original attempt, 323 bytes
p={H:1,Na:1,Ag:1,K:1,Li:1,NH4:1,Ba:2,Ca:2,Cu:2,Mg:2,Zn:2,Pb:2,Fe:3,Al:3},n={Cl:1,Br:1,F:1,I:1,OH:1,NO3:1,O:2,S:2,SO4:2,CO3:2},f=function(x,y){a=p[x]?x:y,b=p[x]?y:x,z=p[a]==2&&n[b]==2,r=+z||n[b],s=+z||p[a];a=--r&&a=='NH4'?'(NH4)':a;b=--s&&/[A-Z]{2}/.test(b)?'('+b+')':b;return'H'==a&&b=='OH'?'H2O':a+(r?r+1:'')+b+(s?s+1:'')}

f=function(x,y){i='indexOf',d='~NH4KNaAgLiBa~CaCuMgZnPbFeAlSO4CO3ClBrFIOHNO3',k=d[i](x),l=d[i](y),a=k<28?x:y,b=k<28?y:x,r=Math.ceil(k/11)-1,s=b=='F'?0:l<32;if(r==s)r=s=0;a=s&&a=='NH4'?'(NH4)':a;b=r&&/[A-Z]{2}/.test(b)?'('+b+')':b;return'H'==a&&b =='OH'?'H2O':a+(s?s+1:'')+b+(r?r+1:'')}

;['H', 'Na', 'Ag', 'K', 'Li', 'NH4', 'Ba', 'Ca', 'Cu', 'Mg', 'Zn', 'Pb', 'Fe', 'Al'].forEach(function (q) {
    ['Cl', 'Br', 'F', 'I', 'OH', 'NO3', 'O', 'S', 'SO4', 'CO3'].forEach(function (w) {
        document.body.innerHTML += '<p>' + q + ' + ' + w + ' = ' + f(q, w);
    });
});

CJam (137 bytes)
{{"SO4CO3ClBrFINO3OHNaAgKLiNH4BaCaCuMgZnPbFeAl":I\#~}$_s"HOH"="HO"1/@?_{I\#G-_0<B*-B/_W>+z}%_~1$=\1?f/W%[.{:T1>{_{'a<},,1>{'(\')}*T}*}]s}

This is an anonymous block (function) which takes two ions as strings wrapped in a list, and returns a string.
Online demo.
Dissection
{                        e# Begin a block
  {                      e#   Sort the input list
    "SO4...Al"           e#     Ions in ascending order of charge
    :I                   e#     Stored as I for future reuse
    \#~                  e#     Index and bit-invert to sort descending
  }$

  _s"HOH"="HO"1/@?       e#   Special case for water: replace ["H" "OH"] with ["H" "O"]

  _{I\#G-_0<B*-B/_W>+z}% e#   Copy the list and hash index in I to find the charges
  _~1$=\1?f/             e#   Replace [2 2] by [1 1]
  W%                     e#   Reverse the charges
  [                      e#   Gather in an array
    .{                   e#   Pairwise for each ion and its opponent's reduced charge...
      :T1>{              e#     If the charge (copied to T) is greater than 1
        _{'a<},,         e#       Count the characters in the ion which are before 'a'
        1>{'(\')}*       e#       If there's more than one, add some parentheses
        T                e#       Append T
      }*
    }
  ]
  s                      e#   Flatten the list to a single string
}

Python 3, 364 bytes
Stores the ions by the absolute value of their charges as index+1 in a 2-D array (0-index elements have +- 1 charge, etc.). Uses string.split() to save a few characters there. Handles the special case of H + OH = H2O first, then it calculates how many ions are needed of each sort as the LCM of their two charges divided by its charge. Then adds in parentheses if needed as well as the actual number of ions.
from math import*
o=["NH4 NO3 H Na Ag K Li OH I F Br Cl".split(),"CO3 SO4 Ba Ca Cu Mg Zn Pb S O".split(),["Fe","Al"]]
p=["H","OH"]
def c(i):
 for h,k in enumerate(o):
  if i in k:return-~h
def b(x,y):
 if x in p and y in p:return"H20"
 i,j=c(x),c(y);g=gcd(i,j);i//=g;j//=g;return((x,"(%s)"%x)[x[-1]in"34"]+str(j),x)[j==1]+((y,"(%s)"%y)[y[-1]in"34"]+str(i),y)[i==1]

Try it online!