text:
Find the nth cross-alternate sum
Given an input of a single positive integer, output the "cross-alternate sum"
that corresponds to that integer.
Take the example of the input n=5. To find the cross-alternate sum, first
create a square grid of width and height n that, reading from left to right
and top to bottom, starts at 1 and increases by one each position:
 1  2  3  4  5
 6  7  8  9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

Then, take the sums from the grid that form a "cross" (that is, both diagonals
combined):
 1           5
    7     9
      13
   17    19
21          25

1 5 7 9 13 17 19 21 25

Finally, take the alternating sum of this sequence:
1+5-7+9-13+17-19+21-25

-11

Another example, for n=6 (just to show what the cross looks like for
even-numbered n):
 1  2  3  4  5  6
 7  8  9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36

 1              6
    8       11
      15 16
      21 22
   26       29
31             36

1+6-8+11-15+16-21+22-26+29-31+36

20

Since this is code-golf, the shortest code in bytes will win.
Here are the correct outputs for n=1 to n=100, which you can use as test
cases:
1
4
-3
10
-11
20
-23
34
-39
52
-59
74
-83
100
-111
130
-143
164
-179
202
-219
244
-263
290
-311
340
-363
394
-419
452
-479
514
-543
580
-611
650
-683
724
-759
802
-839
884
-923
970
-1011
1060
-1103
1154
-1199
1252
-1299
1354
-1403
1460
-1511
1570
-1623
1684
-1739
1802
-1859
1924
-1983
2050
-2111
2180
-2243
2314
-2379
2452
-2519
2594
-2663
2740
-2811
2890
-2963
3044
-3119
3202
-3279
3364
-3443
3530
-3611
3700
-3783
3874
-3959
4052
-4139
4234
-4323
4420
-4511
4610
-4703
4804
-4899
5002

Nit pick: That's not an alternating sum. You're adding the first two terms.

Jelly, 21 19 11 10 7 bytes
²~³¡H+2

Try it online!
Idea
Assume for a second that the first term of the final sum is subtracted rather than added.
Let n be a positive integer.
Even case
 1              6
    8       11
      15 16
      21 22
   26       29
31             36

The differences between the diagonal elements on the lower half of the rows are the first n ÷ 2 odd natural numbers. Since 1 + 3 + 5 + … + (2k + 1) = k2, they sum to (n ÷ 2)2 = n2 ÷ 4.
In this example
- 1 + 6 - 8 + 11 - 15 + 16 - 21 + 22 - 26 + 29 - 31 + 36  =
-(1 - 6)-(8 - 11)-(15 - 16)-(21 - 22)-(26 - 29)-(31 - 36) =
(    5   +   3    +    1  )+(   1    +    3    +    5   ) =
             9             +              9               = 18

Thus, the sum is 2 × n2 ÷ 4 = n2 ÷ 2.
Odd case
 1           5
    7     9
      13
   17    19
21          25

The differences between the diagonal elements on the corresponding rows from above and below (1 and 5, and 21 and 25; 7 and 9, and 17 and 19) is the same, so they will cancel out in the alternating sum.
In this example
- 1 + 5 - 7 + 9 - 13 + 17 - 19 + 21 - 25  =
-(1 - 5)-(7 - 9)- 13 +(17 - 19)+(21 - 25) =
    4   +   2   - 13 -    2    -    4     = -13

All that's left is the negative of the central element, which is the arithmetic mean of the first and last number, so it can be calculated as -(n2 + 1) ÷ 2.
General case
Since ~x = -(x + 1) for two's complement integers (~ denotes bitwise NOT), the formula for the odd case can be rewritten as ~n2 ÷ 2.
Also, since the first term (1) of the original sum is added instead of subtracted, the above formulas leave an error of 2, which has to be corrected.
Therefore, the nth cross-alternate sum is n2 ÷ 2 + 2 if n is even, and ~n2 ÷ 2 + 2 if it is odd.
Finally, bitwise NOT is an involution, i.e., ~~x = x for all x. This way ~~~x = ~x, ~~~~x = x, and, in general, ~nx (meaning that ~ is applied n times) is x if n is even and ~x if it is odd.
Thus, we can rewrite our general formula as ~nn2 ÷ 2 + 2 for all positive integers n.
Code
²~³¡H+2    Main link. Input: n

²          Yield n².
 ~         Apply bitwise NOT to n²...
  ³¡           n times.
    H      Halve the result.
     +2    Add 2.

I knew there was some sort of simple formula, but your explanation and execution is just amazing. +1

JavaScript, 40 38 22 bytes
Using that new-fangled, fancy closed form solution that's all the rage!
n=>(n%2?3-n*n:4+n*n)/2

Thanks to ThomasKwa, I can eliminate my costly recursive function.

You just need to bitwise NOT once if n%2. Actually, I think in JS it might be shorter to just do (n%2?3-n*n:4+n*n)/2

Jelly, 12 bytes
RṖµ²+‘×-*$SC

Try it here.

CJam, 13 15 bytes
ri2#_{~}*2/2+

Two bytes off thanks to Dennis.
Try it online!

My first CJam answer!

Replacing 2%{~}& with {~}* saves two bytes.

@Dennis Very good! Thanks!

Minkolang 0.15, 26 15 13 bytes
Using Dennis' insane algorithm, and golfed off another two bytes thanks to him. That guy is responsible for halving of byte count!
n2;d[~]4+2:N.

Try it here!
Explanation

@VoteToClose n^2, apply bitwise NOT n times, add four, halve. – Thomas Kwa 7 mins ago

See Dennis' answer for the explanation of why that works. In a comment on this answer, he suggested another improvement that works because : is integer division, so I can negate the top of stack and not worry about the +1 from doing the binary complement. Furthermore, n and n^2 have the same parity, which removes the need for a swap.
n                Take number from input - n
 2;              n**2
   d             Duplicates top of stack
    [~]          For loop that negates the top of stack n times
       4+        Add 4
         2:      Divide by 2
           N.    Output as number and stop.

Pure Bash, 28
Well now that @Dennis has showed us all how to do this, this needs updating:
echo $[-1**$1*($1*$1+1)/2+2]

Previous answer:
Bash + GNU utilities, 77
Here's a start:
a=$1
(seq 1 $[a+1] $[a*a]
seq $1 $[a>1?a-1:1] $[a*a])|sort -un|paste -sd+-|bc

N is passed as a command-line parameter.
paste is really handy here for producing the alternating sum.  The -d option allows a list of separator characters, which are used cyclically.

$[-1**$1*$1*$1+4>>1] is even shorter.

Julia, 41 40 25 19 16 bytes
n->-n%2$n^2÷2+2

This is an anonymous function that accepts an integer and returns an integer. To call it, assign it to a variable.
The approach here, devised by Dennis, is as follows. First we get the parity of n, i.e. n (mod 2), and negate it. This gives us 0 for even inputs and -1 for odd. We then bitwise XOR with n2. When n is even, this is just n2 because XOR with 0 is just the number. When n is odd, XOR with -1 is the same as bitwise negation. So at this point we either have n2 or the bitwise NOT of n2. We integer divide this by 2 and add 2 to get the result.
Saved a byte thanks to Sp3000 on a previous version, and saved 9 thanks to Dennis on this one!

MATL, 13 27 bytes
Using Dennis' amazing formulas:
2^t2\?Q_]2/2+

Try it online!
Direct approach (27 bytes):
2^:GtetXdwPXdhutn:-1w^!*s2+

GolfScript, 12 bytes
~2?.{~}*2/2+

This uses the algorithm from my Jelly answer. Try it online!
How it works
~            # Evaluate the input.
 2?          # Square it.
   .         # Push a copy of the square.
    {~}      # Push a code block that applies bitwise NOT.
       *     # Execute it n² times. Since n² and n have the same parity,
             # this is equivalent to executing in only n times.
        2/   # Halve the result.
          2+ # Add 2.

ES7, 17 bytes
n=>-1**n*n*n+4>>1

Simple port of @Dennis's Python 2 answer.
While writing this answer I managed to golf my ES6 port to 17 bytes too!
n=>(n*n^-n%2)/2+2

Jolf, 13 bytes
Try it here!
½?mρj-3Qj+4Qj
 ?mρj         if parity of j
     -3Qj     return 3 - j*j
         +4Qj else return 4 + j*j
½             (and halve the result)

Python 2, 24 bytes
lambda n:(-1)**n*n*n/2+2

This uses the algorithm from my Jelly answer, with a minor modification:
Instead of applying ~ n times, we apply - n times (by multiplying by (-1)n). This is equivalent because ~x = -x - 1 and integer division floors in Python, so ~x / 2 = (-x - 1) / 2 = -x / 2.

GS2, 9 bytes
V,@!α2+''

This uses the algorithm from my Jelly answer. Try it online!
V,@e 7+''

is equally short, but notably contains no non-ASCII characters.
How it works
V          Parse the input as an integer n.
 ,         Compute n².
  @        Push a copy of n².
   !       Bitwise NOT.
    α      Make a block of the previous instruction.
     2     Execute the block n² times. Since n² and n have the same parity,
           this is equivalent to executing in only n times.
      +    Halve the result.
       ''  Increment twice.

Pyth, 11 bytes
+2/u_GQ*QQ2

Try it online in the Pyth Compiler.
How it works
This uses the algorithm from my Jelly answer, with a minor modification:
Instead of applying ~ n times, we apply - n times (by multiplying by (-1)n). This is equivalent because ~x = -x - 1 and integer division floors in Pyth, so ~x / 2 = (-x - 1) / 2 = -x / 2.
+2/u_GQ*QQ2  Evaluated input: Q

       *QQ   Yield Q².
   u  Q      Set G = Q². For each non-negative integer below Q:
    _G         Set G = -G.
             Return G.
  /       2  Halve the result.
+2           Add 2.

dc, 17
Using the same tried and tested formula from Dennis:
?dd*1+r_1r^*2/2+p

Try it online Oh, why doesn't the Ideone bash sandbox include dc?
Command-line Test:
for i in {1..100}; do echo $i | dc -e '?dd*1+r_1r^*2/2+p'; done

?2^1+2~2*1-*2+p saves two bytes.

J, 16 bytes
[:<.2%~4+*:*_1^]

This uses the same algorithm as my Jelly answer. Test it with J.js.

Dyalog APL, 13 bytes
⌊2+.5××⍨×¯1*⊢

This uses the same algorithm as my Jelly answer. Test it on TryAPL.

Lua, 33 bytes (Try it online)
i=(...)print((-1)^i*i*i/2-.5*i%2)

How it works:
i=(...)print((-1)^i*i*i/2-.5*i%2)
i=(...)                           Take input and store to i
       print(
             (-1)^i               Raise (-1) to the i-th power: -1 if odd, 1 if even
                   *i*i/2         Multiply by i squared and halved.
                         -.5*i%2  i%2 is the remainder when i is divided by 2
                                  if i is odd, then i%2 will be 1, and this expression
                                  will evaluate to -0.5
                                  but if i is even, then i%2 will be 0, which makes
                                  this expression evaluate to 0
                                )


text:
Implement almost-equals for IEEE numbers
Isn't it annoying when you're working with floating point numbers and your code doesn't work because two numbers are not equal by the least significant bit? Now you can fix that!
Write some code that takes two floating point numbers in any IEEE 754 binary format and returns TRUE if:

the two numbers are exactly equal
for two positive numbers: adding the value of the least significant bit to the smaller number makes it exactly equal to the larger value
for two negative numbers: subtracting the value of the least significant bit from the larger number makes it exactly equal to the smaller value

Return FALSE if:

any other case

IEEE 754 allows both positive and negative zero. Treat all zeros as the sign of the other non-zero number. IEEE 754 defines 0 === -0. You can enter the numbers as text only if the binary representation in memory is accurate to the least significant bit.
Test Data
The test data will vary slightly, depending on exactly which format your language uses. The table below shows the bit representation, followed by how to calculate the value, since most values will be impractical to directly input. A value such as -1.5b-3 means -1.5 x 2-3.
Your code must be able to handle every format your language supports:

binary16 (Half precision)
binary32 (Single precision)
binary64 (Double precision)
binary128 (Quadruple precision)

If you are supporting any format other than binary64, expand or contract the bit patterns from the test data to their equivalents.
If your language doesn't natively support IEEE 754 at all, you may import an external library at no cost that fully implements at least one IEEE 754 binary format, but with no extra functions, i.e. you can't put your own function in the included library.
IEEE 754 binary64 (Double precision):
Zero and Subnormals:
0 00000000000 0000000000000000000000000000000000000000000000000000 (0)
0 00000000000 0000000000000000000000000000000000000000000000000001 (1b-1074)
TRUE

0 00000000000 0000000000000000000000000000000000000000000000000001 (1b-1074)
0 00000000000 0000000000000000000000000000000000000000000000000010 (1b-1073)
TRUE

0 00000000000 0000000000000000000000000000000000000000000000000000 (0)
0 00000000000 0000000000000000000000000000000000000000000000000010 (1b-1073)
FALSE

0 00000000000 0000000000000000000000000000000000000000000000000111 (1.75b-1072)
0 00000000000 0000000000000000000000000000000000000000000000001000 (1b-1071)
TRUE

0 00000000000 0000000000000000000000000000000000000000000000000000 (0)
1 00000000000 0000000000000000000000000000000000000000000000000001 (-1b-1074)
TRUE

1 00000000000 0000000000000000000000000000000000000000000000000001 (-1b-1074)
1 00000000000 0000000000000000000000000000000000000000000000000010 (-1b-1073)
TRUE

0 00000000000 0000000000000000000000000000000000000000000000000000 (0)
1 00000000000 0000000000000000000000000000000000000000000000000010 (-1b-1073)
FALSE

0 00000000000 0000000000000000000000000000000000000000000000000001 (1b-1074)
1 00000000000 0000000000000000000000000000000000000000000000000001 (-1b-1074)
FALSE

Normalised numbers:
0 01111111111 0000000000000000000000000000000000000000000000000000 (1)
0 01111111111 0000000000000000000000000000000000000000000000000010 (1 + 1b-51)
FALSE

0 01111111111 0000000000000000000000000000000000000000000000000000 (1)
0 01111111111 0000000000000000000000000000000000000000000000000001 (1 + 1b-52)
TRUE

0 01111111111 0000000000000000000000000000000000000000000000000000 (1)
0 01111111111 0000000000000000000000000000000000000000000000000000 (1)
TRUE

0 01111111111 0000000000000000000000000000000000000000000000000000 (1)
0 01111111110 1111111111111111111111111111111111111111111111111111 (1 - 1b-53)
TRUE

0 01111111111 0000000000000000000000000000000000000000000000000000 (1)
0 01111111110 1111111111111111111111111111111111111111111111111110 (1 - 1b-52)
FALSE

0 01111111111 0000000000000000000000000000000000000000000000000000 (1)
0 01111111110 0000000000000000000000000000000000000000000000000000 (0.5)
FALSE

0 10000010101 1111111111111111111111111111111111111111111111111110 (16777216 - 1b-28)
0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216)
FALSE

0 10000010101 1111111111111111111111111111111111111111111111111111 (16777216 - 1b-29)
0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216)
TRUE

0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216)
0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216)
TRUE

0 10000010110 0000000000000000000000000000000000000000000000000001 (16777216 + 1b-28)
0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216)
TRUE

0 10000010110 0000000000000000000000000000000000000000000000000010 (16777216 + 1b-27)
0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216)
FALSE

1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3)
1 01111111101 0101010101010101010101010101010101010101010101010111 (-1 / 3 - 1b-53)
FALSE

1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3)
1 01111111101 0101010101010101010101010101010101010101010101010110 (-1 / 3 - 1b-54)
TRUE

1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3)
1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3)
TRUE

1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3)
1 01111111101 0101010101010101010101010101010101010101010101010100 (-1 / 3 + 1b-54)
TRUE

1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3)
1 01111111101 0101010101010101010101010101010101010101010101010011 (-1 / 3 + 1b-53)
FALSE

1 11111111110 1111111111111111111111111111111111111111111111111111 (-1b1024 + 1b971)
1 11111111110 1111111111111111111111111111111111111111111111111111 (-1b1024 + 1b971)
TRUE

1 11111111110 1111111111111111111111111111111111111111111111111111 (-1b1024 + 1b971)
1 11111111110 1111111111111111111111111111111111111111111111111110 (-1b1024 + 1b970)
TRUE

1 11111111110 1111111111111111111111111111111111111111111111111111 (-1b1024 + 1b971)
1 11111111110 1111111111111111111111111111111111111111111111111101 (-1b1024 + 1.5b970)
FALSE

Infinity and Not A Number:
X 11111111111 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

INF
INF
TRUE

INF
Any other value
FALSE

-INF
-INF
TRUE

-INF
Any other value
FALSE

NAN
Any value, including NAN
FALSE

Scoring
Number of bytes - (number of bytes needed for IEEE 754 library include, if an external library is used)

you can't put your own function in the included library. Isn't that already banned by standard loopholes?

@ThomasKwa I certainly hope so! I just wanted to make it explicit in case someone thought that was allowed, since I specifically said that adding an IEEE library would not count towards your score..

C++14 using IEEE754 platform, 17 + 49 = 66 bytes
Includes, 17 bytes:
#include <cmath>

Lambda expression, 49 bytes:
[](auto a,auto b){return b==std::nextafter(a,b);}

Wow so the modern C++ has lambdas, nice!

@busukxuan Even better, the auto means that this is a templated lambda :)

source: Stack Exchange

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

sort: votes


text:
Efficient Scientific Notation
The other day my chemistry teacher was explaining to us about scientific notation (using a small number and multiplying it by powers of ten to express large numbers more easily), which brought me back a few years to when I first learnt it. After learning the basics, we had done a bunch of typical maths questions, some of which were like the following:

Represent the following in scientific notation:
  a) 50000000
  b) 120000000000000
  c) 90000000000000000000000000000000000000
  d) pi^e^i^j^k^std::vector
  ...
  z) 200
  ...

And I thought, "What? We were told that scientific notation was used to make writing large numbers more efficient, but some cases aren't more efficient at all!"
Consider the number
300

and its representation in scientific notation:
3x10^2

What, the scientifically notated version actually takes up more space? We can't have that now can we? (Screen space is precious.)
We could determine ourselves if it's more space efficient to write a number in scientific notation or not, or...
Task
Your program or function should take as input a single positive number n of arbitrary size (up to what your language supports) and output the scientifically notated version of the number.
However, if the original number n, after removal of trailing zeroes and trailing decimal place, takes less or the same amount of characters to display than its scientifically notated version, you must output that original number n instead.
Your code needs to be as short as possible because the output also has to be as short as possible.
Specifications
Efficient Scientific Notation is defined as follows:
bx10^e

b is the input number appropriately divided by powers of 10 such that 1 <= b < 10.  This number must have all trailing zeroes (and decimal point if required) removed, but must have the precision of the original number (up to the decimal point limit in your language, of course). Ie 90000 becomes 9, 13.500 becomes 1.35, 0.000675 becomes 6.75 etc. If this number ends up containing more decimal places than your language can handle, it should be rounded to that maximum number of decimal places.
e is the exponent to which ten is raised such that n = b x 10^e (remember that this number needs to be negative if n is smaller than 1). This number should not have any trailing zeros or a decimal place (mainly because if it's not an integer something is wrong...).
The characters x10^ must remain as is in the string between b and e.
Test cases
Input -> output
1 -> 1
20 -> 20
3000000 -> 3x10^6
400000 -> 400000
0.008093 -> 0.008093
0.007835000000000 -> 0.007835
0.000003000000 -> 3x10^-6
0.00000065 -> 6.5x10^-7
0 -> 0

Scoring
This is code-golf, so shortest code in bytes wins.
Other rules and clarification

Trailing zeros (and/or trailing decimal place) are not counted towards the character count of the original input number n. Keep that in mind for cases such as test case 6
You may assume that if the input number is less than 1, it will always start with a 0 in place for the ones digit (as in test cases 5-8).
Input number will never be negative
Built-ins that make this challenge trivial and standard loopholes are disallowed
A trailing newline in the output is OK

EDIT
Thanks to user81655 for pointing out test cases 7 and 8 had incorrect powers of ten. I have now fixed those so make sure your code evaluates them correctly.

So, uh, should I ask what the output for input pi^e^i^j^k^std::vector would be?

@Geobits Hmm, well if you can assign a numerical value to std::vector then maybe... No, only numbers will be present in the input (except a decimal place for floating point input).

This would be far easier and we would take up less of your "precious screen space" if it  used e: 9000 -> 9e3 (almost over 9,000!)

@Cyoce I thought about that, but I really based this challenge on the way it is generally written (as in physically written), which seems to be with x10^. And it would be a fair bit of rework on the question, which I don't think is that appropriate now that it's posted

@indeed please note that in scientific notation, trailing zeroes DO count after the decimal place.... so while "0.4" = "410^-1", "0.40" = "4.010^-1"
this distinction is kind of important

also, this creates the distinction that 40 = 410^1 and 40. = 4.010^1

@sig_seg_v I (sort of) understand what you are saying, but I thought I had defined a pretty solid explanation of how scientific notation will work with this challenge - OK it turned out to not be exactly like it should be. (ugh I thought all this would get sorted in the Sandbox...)

@indeed it's not that your definition in the challenge isn't clear, it just rubs me the wrong way as a mathematician/scientist that, in this problem, 40.0 = 40 = 4*10^1... pay me no mind if you don't want to adopt my suggested change ;), it's just that there is no such thing as a "trailing decimal place" in scientific notation.......

@sig_seg_v So you are suggesting that b under Specifications should contain the same amount of digits after the decimal place as the input? I'm just trying to figure out how I can implement your suggestion but still make it clear what is going on.

Let us continue this discussion in chat.

0.008093 -> 0.008098 I think you has a typo.

@KyleKanos Thanks, fixed now

Why would a chemistry teacher be the first one to teach students scientific notation?

@ghosts_in_the_code She wasn't, hence "brought me back a few years to when I first learnt it [in maths class]"

BF: ,[.,], although it's Abusing native number types to trivialize a problem.

ES6, 83 81 bytes
x=>(e=s=>s.replace(/e\+?/,'x10^'),z=e(x.toExponential()),y=e(''+x))[z.length]?z:y

Probably fails for some edge cases where toString insists on exponential format.
Edit: Saved 2 bytes thanks to @user81655.

Nice idea. By the way, it looks like you forgot the / at the end of the regex.

Also you could rearrange this slightly to save 2 bytes: x=>(e=s=>s.replace(/e\+?/,'x10^'),z=e(x.toExponential()),y=e(''+x))[z.length]?z:y

@user81655 Ah, what happened there is that my browser confused me by wrapping the long line in such a way as I thought that a new line had crept in there by mistake.

Python 3, 346 342 319 302 bytes
L=len;N=str(float(input()))
if N.endswith('.0'):N=N[:-2]
if'e'in N:C,P=N.split('e');N=N.replace('e','x10^')
else:
 C=N.strip('.0').replace('.','');F=N.find('.')
 if L(C)>1:C=C[0]+'.'+C[1:]
 P=((L(N) if F==-1 else F)-1-N.lstrip('0').find(C[0]))
print(min([N,'{0}x10^{1}'.format(C,int(P))],key=L))

Probably horribly golfed, but hey, this is my first try at something like this. It's hard to read, so it must be good.
As far as I'm aware, it should work on every case, even with Python's tendency to automatically convert numbers past whatever threshold into scientific notation (except with that cool and fancy 'e'). I don't remember exactly how I made that be able to return standard form numbers, but it does that.

Perl 6, 96 90 bytes

I feel like this could be shorter, but this is my best for now
{my \s=($_,*×(1>$_??10!!.1)…10>*>=1);min(s[*-1]~"x10^"~(1>$_??1-s!!s-1),$_,by=>&chars)}

usage: Assign this to a variable
Here it is ungolfed a bit with some bad commentary:
my &f = -> $n {
    my $a = 1 > $n ?? 10 !! .1;             # If $n < 1, we will multiply by 10
                                            # in the sequence below, else by 0.1

    my @seq = ($n, * × $a ... 10 > * >= 1); # Sequence starting at $n,
                                            # multiply the previous value by $a
                                            # until we reach a number 1 <= x < 10

    # Join the last element in @seq, "x10^", and the length of @seq,
    # with an extra subtraction for numbers less than 1.
    # this gets us our scientific notation.
    my $science = @seq[*-1] ~ "x10^" ~ @seq - (1 > $n ?? @seq*2 !! 1);

    min($science, $n, by => &chars) # Uses the &chars function to
                                    # choose a min value and return it.
}

Swap $_ <1 with 1>$_ and 1 <=* <10 with 10>*>=1

I actually meant to do that last night but I forgot. I'll update it when I get home

TI BASIC (nspire): 112 bytes
Define f(x)=
Prgm
string(x)➝a
If x≥1 Then
format(x,"s")➝a
EndIf
instring(a,"ᴇ")➝b
left(a,b-1)&"x10^"&mid(a,b+1)➝a
If dim(a)<dim(string(n)) or x<1 Then
Disp a
Else
Disp x
Endif
EndPrgm

Explanation
If x≥1 Then
format(x,"s")➝a
EndIf

Converts the input to scientific notation with the format function if it already isn't in that format- as small decimals are automatically converted.
instring(a,"ᴇ")➝b
left(a,b-1)&"x10^"&mid(a,b+1)➝a

Finds the position of the fancy E that denotates exponents and replaces it with "x10^".
If dim(a)<dim(string(x)) or x<1 Then
Disp a
Else
Disp x
Endif

Checks which output is larger and returns the optimal one. Unless it is a small decimal, which are smaller by default.

Python (3.5) 177 bytes
A solution using regular expression
import re
g=lambda s:re.sub(r"e\+?(-?)0?","x10^\\1",s)
def f(i):
 t=g(re.sub(r"\.[0]*e","e","%e"%i))
 u=g(re.sub(r"(\..*)[0]*$","\\1",str(i)))
 return t if len(u)>len(t) else u

Explanation
Importation of regexp module
import re

Définition of the lambda function to replace e by x10^
g=lambda s:re.sub("e\+?(-?)0?","x10^\\1",s)
def f(i):

Convertion of the string in scientific notation
 t=g(re.sub(r"\.[0]*e","e","%e"%i))

Remove 0 padding in the orginal string
 u=g(re.sub(r"(\..*)[0]*$","\\1",str(i)))

compare length
 return t if len(u)>len(t) else u

Results
>>> [f(i) for i in [1, 20, 3000000, 400000, 0.008093, 0.007835000000000, 0.000003000000, 0.00000065, 0]]
['1', '20', '3x10^6', '400000', '0.008093', '0.007835', '3x10^-6', '6.5x10^-7', '0']

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


text:
Inverse function
Wouldn't it be neat if programming functions could be inverted, just like the mathematical function they implement?
Write a function (or program) that takes one input x in any form, that outputs ln(x).
When the bytes of the program are reordered/reversed so that the first byte now is the last byte, it should take one input x in any form and output e^x instead.

Your answer must have at least 3 correct significant figures.
Approximations are fine, as long as they have at least 3 correct significant figures.
Your code must be in the same programming language both forwards and backwards.

Let's say this program implements ln(x):
abc你好

Then this program has to implement e^x:
\xBD\xA5\xE5\xA0\xBD\xE4cba

Gold star if you use a language without float support.
This is a weird form of code-golf, so the shortest program wins.

"Wouldn't it be neat if programming functions could be inverted, just like the mathematical function they implement?" Some languages (e.g. J and Mathematica) can actually do this for some functions.

Additionally, K2 could approximate an inverse for an arbitrary monadic  pure function via its "function inverse" overload of dyadic and triadic ?, which used the secant method.

"at least 3 correct significant figures" - over what range?

I realize it's far too late now, but I think this would have been a really nice challenge had comments been disallowed.

I actually thought of that when I came up with this challenge @AlexA. but forgot about it while writing the post :P Also that would've made "normal" languages like java, c++ etc basically impossible.

@TLW a big enough range, say up to 10k? I want you to have to handle printing floats, and a 32bit int should be enough for storage.

Haskell, 11 bytes
f=log
pxe=f

and in reverse order:
f=exp
gol=f

This works without the "comment" trick. Instead each version defines an additional, but unused function (pxe/ gol).

+1 for gol=f.

This is also a valid solution in Julia.

APL, 3 bytes
*⊣⍟

This is a function train. Monadic *  returns e^x, monadic ⍟ returns ln(x). ⊣ is a dyadic function that returns its left argument. Thus, *⊣⍟ is equivalent to just *, and the reverse ⍟⊣* is equivalent to just ⍟.

Jelly, 5 4 bytes
Yay, my first Jelly answer. :) Input is via command-line argument.
Jelly has its own code page so each character is one byte.
eÆÆl

Try it online!
Reversed:
lÆÆe

Try it online!
Explanation
The Æ on its own is an unrecognised token, so it acts the same as a linefeed. That means in either case the main link is only Æl or Æe which is the 2-character built-in for exp() or ln() and is by default performed on the first command-line argument.

Javascript, 18 bytes
Math.log//pxe.htaM

Don't you need a return() or console.log() around it?

@OldBunny2800 It evaluates to a function, which should be permissible.

Math.ln||pxe.htaM will probably also work.

@SuperJedi224 Thanks, that helped me spot the error in my answer!

@Neil I hadn't even noticed that

@EᴀsᴛᴇʀʟʏIʀᴋ That's not how it works. Try assigning it to a function f: f=Math.log//pxe.htaM, then calling it with input.

Seriously, 5 bytes
,_.e,

Input, ln, output, then exp on an empty stack (does nothing), and input (does nothing since input is exhausted). Try it online!
Reversed:
,e._,

Try it online!

The language name is hilarious

Mathematica, 19 bytes
1&#@pxE+0&0+Log@#&1

Reversed:
1&#@goL+0&0+Exp@#&1

This was interesting to golf! Mathematica has no line comments / implicit string endings, so I couldn't take the simple route. Instead, I used the fact that 0 + x == x, 0 x == 0, and that 1 x == x, no matter what x is! Testing:
In[1]:= (1&#@pxE+0&0+Log@#&1)[x]

Out[1]= Log[x]

In[2]:= (1&#@goL+0&0+Exp@#&1)[x]

         x
Out[2]= E

Julia, 7 bytes
log#pxe

This is an anonymous function. Assign it to a variable to call it. Evaluates to builtins log or exp plus a comment.

Same answer works for R

Python2, 73 bytes
io: stdin/stdout
from math import*;print log(input())#))(tupni(pxe tnirp;*tropmi htam morf

inverse:
from math import*;print exp(input())#))(tupni(gol tnirp;*tropmi htam morf

You can shave 10 characters off by using __import__("math"). instead of

CJam, 11 bytes
rdmle#eemdr

Test it here.
Reversed:
rdmee#elmdr

Test it here.
Basically the same comment-trick as the OP's Python answer. e# starts a comment. rd reads the input and ml or me computes the logarithm or exponential.

Brachylog, 3 bytes
*₁≡

Try it online!
Initially, I had hoped to use ~*, but although *~ computes e^x and successfully ignores the trailing tilde, ~* fails for all integer inputs and hits a float overflow on most non-integer inputs.
Forwards:
       The output
  ≡    is
*₁     the natural logarithm of
       the input.

Backwards:
       The output is
  *    Euler's number to the power of
       the input
≡      passed through the identity predicate
 ₁     with an extraneous subscript.

This uses the identity predicate because, although trailing tildes are tolerated, leading subscripts are not. (If they were, the Brachylog answer would be *₁ alone, which is just the normal builtin for natural log.)

Vitsy, 5 bytes
This is a program that exits on an error.
EL^rE
E   E  Push java.lang.Math.E
 L     Push log_(top) (input) (ln(input))
  ^    Push (top)^(input)  (e^(input))
   r   Reverse the stack
This program exits on an error with ln(input) on the stack.
Try it online! (note that I have put N to have visible output)
Then it's inverse:
Er^LE
This program exits on an error with e^(input) on the stack.
Try it online!

Fuzzy Octo Guacamole, 7 bytes
non-competing, FOG is newer than the challenge
EZO@pZE

This is the equivalent of a function in FOG.  It assumes the input is on the stack. This can be assigned to a function by the code "EZO@pZE""f"o, where f is any single-char name you want to assign.  Then use it like any other command. Example: "EZO@pZE"'f'o^f.
Explanation:
EZO@pZE
E       # Push E (2.718....)
 Z      # Reverse stack (it is now [e, input])
  O     # log(x, y) which is ln(input)
   @    # Exit. (implicit output) Nothing after this gets run.
    p   # x^y (power function)
     Z  # Reverse stack
      E # Push E.

Reversed:
EZp@OZE
E       # Push E (2.718....)
 Z      # Reverse stack (it is now [e, input])
  O     # x^y (power function)
   @    # Exit. (implicit output) Nothing after this gets run.
    p   # log(x, y) which is ln(input)
     Z  # Reverse stack
      E # Push E.

Matl, 5 bytes
Yl%eZ

Yl: log
Ze: exp
%: comment

Thanks to Dennis, there's an online compiler for MATL

Pyth, 12 bytes
Finds ln(input())
.lQ) " Q1n.^

Finds e^input()
^.n1Q " )Ql.

Spaces stop implicit printing of strings, each version calculates it then creates a string with the remaining characters.
ln(x) mode here
e^x mode here

, 8 chars / 10 bytes
МŬï//ïŦМ

Try it here (Firefox only).Try reverse here (Firefox only).
Just 2 builtins separated by a comment.

Jolf, 9 bytes
Program 1: exp of input
amoj"jOma
a         print
 moj      e^j
    "jOma  the rest of the line is captured as a string; implicit printing is restricted.

Program 2: ln of input
amOj"joma
a         print
 mOj      ln(j)
    "joma  the rest of the line is captured as a string; implicit printing is restricted.

Bonus points for being a case-insensitive palindrome? Try it here!

J, 8 bytes
The natural logarithm is ^., and exponential ^. The problem is, . can only modify a valid verb, otherwise, a spelling error will occur. Thus, we can't use the left argument trick in the APL answer, becuase ^.[^ would cause an error when reversed, as ^[.^ creates an invalid verb. So, we must use comments; but NB. is so long :( Fortunately, they both end with ., so&ldots there's that.
Logarithm:
^.NB.BN^

Exponential:
^NB.BN.^

You can enter them for yourself online!

Runic Enchantments, 9 bytes
i'lA@Ae'i

Try it online!
An ungodly uninteresting program. @ insures termination of the implied entry point at the left, everything after is unexecuted. I tried really hard to re-use the ' or A instructions, but to no avail, even at larger program sizes. The required explicit entry point for multi-line programs essentially precludes it.

Java 8, 198 182 30 bytes
d->Math.log(d)//)d(pxe.htaM<-d

Try it online.
and reversed:
d->Math.exp(d)//)d(gol.htaM<-d

Try it online.
Uses the comment trick (//) with built-ins for Math.log and Math.exp.

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


text:
Convert string to time
This challenge is inspired by this other.
The challenge
Write a program or a function in any programming language that given as input a string representing a time in English (see below, for further details) it outputs or prints the equivalent in the 24 hours "digital" format HH:MM.
Shortest code in bytes wins, standard loopholes are forbidden.
Input format
Your program should be able to handle all this kind of inputs:
one minute past 'HOUR'
'MINUTES' minutes past 'HOUR'
quarter past 'HOUR'
half past 'HOUR'
one minute to 'HOUR'
'MINUTES' minutes to 'HOUR'
quarter to 'HOUR'
'HOUR'
'HOUR12' 'MINUTES' AM
'HOUR12' 'MINUTES' PM

where: MINUTES is a number from 1 to 59 written in English with hyphen; HOUR is the name of an hour in one of the formats:
midnight
noon
midday
'HOUR24' o'clock
'HOUR12' o'clock AM
'HOUR12' o'clock PM

HOUR12 is a number from 1 to 12 written in English with hyphen; and HOUR24 is a number from 1 to 23 written in English with hyphen.
Some examples
midnight                                  ->   00:00
midday                                    ->   12:00
twelve o'clock                            ->   12:00
quarter to midnight                       ->   23:45
twenty-two minutes past eight o'clock PM  ->   20:22
thirty-four minutes to fifteen o'clock    ->   14:26
six o'clock AM                            ->   06:00
one minute to twenty-one o'clock          ->   20:59
seven thirteen AM                         ->   07:13
nine fourteen PM                          ->   21:14

Good luck!

So is 'MINUTES' minutes past 'HOUR24' o'clock a valid time?

@muddyfish Yes, it is.

Should HOUR24 be a number from 0 to 23?

@ETHproductions No, from 1 to 23. "zero o'clock" doesn't sound well.

@Bob neither does "24 o-clock" or "23-oclock"

Ruby, 653 597 Bytes
P=/ past | to /;T=%w{q twen thirty fourty fifty sixty el twe thi fourte fifte sixt sevent eighte ninet o tw th fo fi si s e n t}.zip([15,*(2..6).map{|i|i*10},*11..19,*1..10]).to_h;D={'middnight'=>0,'midday'=>12,'noon'=>12};n=->s{s.split('-').reduce(0){|p,v|(Array(T.find{|k,_|v.start_with? k}).last||0)+p}};i=->s{m=0;s=s.gsub(/^\s+|\s+$/,'');c=s.split(P);(c.reverse! if s.match(P));h=D[c[0]]||n.(c[0].gsub(/ o\'clock (A|P)m/,''));h+=(s.end_with?('PM') ? 12 : 0);m=n.(c[1]||c[0].split(' ')[1]) if c[1]||c[0].match(/^\w+ (?!o'clock)/);(m=60-m;h=(h-1)%24)if s.match(/ to /);(sprintf '%02d:%02d',h,m)}

Ungolfed:
P=/ past | to /
# configuration for translating english words to numbers
T=%w{q twen thirty fourty fifty sixty el twe thi fourte fifte sixt sevent eighte ninet o tw th fo fi si s e n t}.zip([15,*(2..6).map{|i|i*10},*11..19,*1..10]).to_h
D={'middnight'=>0,'midday'=>12,'noon'=>12}

# proc for translating english word groups to a number
n=-> s {
  s.split('-').reduce(0) { |p,v|
    (Array(T.find {|k,_| v.start_with? k}).last || 0) + p
  }
}

i=-> s {
  m=0
  s=s.gsub(/^\s+|\s+$/,'')
  c=s.split(P)
  (c.reverse! if s.match(P))

  # set the hour
  h=D[c[0]]||n.(c[0].gsub(/ o\'clock (A|P)m/,''))
  h+=(s.end_with?('PM') ? 12 : 0)

  # set the minute
  m=n.(c[1]||c[0].split(' ')[1]) if c[1]||c[0].match(/^\w+ (?!o'clock)/)

  # adjust for 'past'
  (m=60-m;h=(h-1)%24)if s.match(/ to /)

  sprintf '%02d:%02d',h,m
}

Verification script used:
examples = <<EXAMPLES
midnight                                  ->   00:00
midday                                    ->   12:00
twelve o'clock                            ->   12:00
quarter to midnight                       ->   23:45
twenty-two minutes past eight o'clock PM  ->   20:22
thirty-four minutes to fifteen o'clock    ->   14:26
six o'clock AM                            ->   06:00
one minute to twenty-one o'clock          ->   20:59
seven thirteen AM                         ->   07:13
nine fourteen PM                          ->   21:14
EXAMPLES

examples.split("\n").each do |example|
  text, expected = example.split(/\s+->\s+/)
  r = i.(text)
  raise "Unexpected result for \"#{text}\". Got \"#{r}\", expected \"#{expected}\"" unless r == expected
  print "."
end

Thank you to Kevin Lau for 47 bytes of optimization

[15,*(2..6).map{|i|i*10},*11..19,*1..10] is a much more concise representation of the numbers you are using to construct your hash. Also, there's a lot of whitespace you can remove between brackets, and using Ruby interpolation within regex patterns allows you to replace v.start_with? k with v=~/^#{k}/

I should have thought of the ranges and splats, thanks! Also removed some unnecessary whitespace.


text:
Eat the Chocolate Bar
I have a chocolate bar and I need help eating it so you'll be writing a program just to do that.
Explanation
The first line is the input. Examples are separated by an empty line.
7
   ____
 __|__|
|__|__|
|__|__|
|__|__|

6
_______
|__|__|
|__|__|
|__|__|

5
   ____
 __|__|
|__|__|
|__|__|

0

1
   ____
   |__|

Spec
Hopefully the examples clearly specify this challenge but to avoid any possible confusion, here's a spec:
You can have a single optional trailing/leading whitespace
An input of 0 is an empty output.
If the input is even, the top rows looks like:
_______
|__|__|

If it's odd, the top row is:
   ____
   |__|

If it's odd and greater than 1, the top rows are:
  ____
__|__|

The following rows are:
|__|__|

until the number of instances of |__| is the same as the input

What's the output for input 1? Does input of 0 need to be supported?

@Doorknob yes, I've updated the challenge

Can we submit a function? 2. Can we take input from STDIN/function arguments? 3. Do we have to output ONE or ALL itterations?

@YoYoYonnY yes, by default you can (this link answers your second question too). I'm not sure what you mean by iterations. Take a look at the examples, that's all you have to output

Are leading blank lines allowed?

@Neil Check second line of spec ;) "You can have a single optional trailing/leading whitespace"

@Downgoat Oh, with itterations I ment if you should output all chocolate bars from 1 to n or only chocolate bar n.

@YoYoYonnY just chocolate bar n

Pyth, 55 bytes
K"|__|"IQ>7<*3%Q2r"3 7_"9?tQjb+XW%Q2J+KtKZd*/tQ2]J+*3dK

Try it online. Test suite.
This is really quick and dirty, written on my phone. Will get to more golfing later.

Haskell, 101 bytes
Haskell has never been great for code golfing...
b="\n|__|__|"
h="   ____\n "
f 1=h++"  |__|"
f 2="_______"++b
f 3=h++"__|__|"++b
f n=f(n-2)++b
f _=""

It depends on how you look at it. Java > Python > Haskell > GolfLang. I use python ;)

@JAtkin Well look at my PHP answer, then you see what's like worst

JavaScript ES6, 80 bytes
x=>(x%2?`   ____
 ${x<2?"  ":"__"}|__|`:x?"_______":"")+`
|__|__|`.repeat(x/2)

Uses the same technique as my Japt answer, and is surprisingly not much longer...

Japt, 60 57 bytes
U%2?[S³'_²²RSU¥1?S²:'_²"|__|"]¬:U?'_p7 :P +"
|__|__|"pU/2

Just a basic answer. Can probably be improved. Test it online!

C, 104 102 bytes
f(x){x?x%2?printf("   ____\n%3s|__|\n",x<2?"":"__"):puts("_______"):0;for(x/=2;x>0;x--)puts("|__|__|");}

Maybe I can use some printf trickery to improve this...
Apparently I can

PHP, 134 chars
<?$i=$argv[1];if($i>0){echo($i%2===0?"_______\n|__":"   ____\n".($i>1?"___":"   "))."|__|\n";echo str_repeat("|__|__|\n",($i-1)/2);}?>

Notes:

PHP was not built for code golfing
I sure had FUN making this snippet
It throws an error if argv is undefined
Any help to short it is appreciated.

, 53 chars / 67 bytes
ï%2?`   ⟮__⟯Ⅰ
 ⦃ï<2?⍞  :⍞Ⅰ⦄|Ⅰ|`:ï?⍘_ď7:⬯⦄
|Ⅰ|Ⅰ|`ď ï/2

Try it here (Firefox only).
This is quite similar to the Javascript ES6 answer, even though I found it independently. Explanation to come when I finish golfing.

Retina, 69 bytes
r`(1?)1
$1__|__|¶
^__(?=\D{5}$)

^.
$0____¶ $0
^\D

^1
___
 ?1
|

Takes input in unary.
Try it online here.


text:
Print sin, cos, and tan of special angles
In trigonometry, there are certain angles known as "special angles". This is because when you take sin, cos or tan of one of these angles, you get a result that is easy to remember because it is a square root of a rational number. These special angles are always multiples of either pi/6, or pi/4. Here is a visualization of all the special angles, and their corresponding trig values.

As you can see, for each angle their is a corresponding pair of numbers. The first number is cosine of that angle, and the second is sine of that angle. To find tangent of one of these angles, just divide sin by cos. For example, tan(pi/6) is  equal to
sin(pi/6) / cos(pi/6) ==
(1/2) / (√3/2) ==
1/√3 ==
√3/3

The Challenge
You must write a full program that takes 3 inputs.

A single char representing the trig function you're supposed to calculate. This will be either 's' (sin), 'c' (cos), or 't' (tan).
The numerator of the input angle. This can be any positive integer. Note that an input of 5 means the numerator is 5 * pi.
The denominator of the input angle. This will always be one of the following: 1, 2, 3, 4, 6

Then print out the exact value the trig function of that angle. Here is a list of sin, cos, and tan of all angles up to 2 * pi:
sin(0pi):    0
sin(pi/6):   1/2
sin(pi/4):   root(2)/2
sin(pi/3):   root(3)/2
sin(pi/2):   1
sin(2pi/3):  root(3)/2
sin(3pi/4):  root(2)/2
sin(5pi/6):  1/2
sin(1pi):    0
sin(7pi/6):  -1/2
sin(5pi/4):  -root(2)/2
sin(4pi/3):  -root(3)/2
sin(3pi/2):  -1
sin(5pi/3):  -root(3)/2
sin(7pi/4):  -root(2)/2
sin(11pi/6): -1/2
sin(2pi):    0

cos(0pi):    1
cos(pi/6):   root(3)/2
cos(pi/4):   root(2)/2
cos(pi/3):   1/2
cos(pi/2):   0
cos(2pi/3):  -1/2
cos(3pi/4):  -root(2)/2
cos(5pi/6):  -root(3)/2
cos(1pi):    -1
cos(7pi/6):  -root(3)/2
cos(5pi/4):  -root(2)/2
cos(4pi/3):  -1/2
cos(3pi/2):  0
cos(5pi/3):  1/2
cos(7pi/4):  root(2)/2
cos(11pi/6): root(3)/2
cos(2pi):    1

tan(0pi):    0
tan(pi/6):   root(3)/3
tan(pi/4):   1
tan(pi/3):   root(3)
tan(pi/2):   nan
tan(2pi/3):  -root(3)
tan(3pi/4):  -1
tan(5pi/6):  -root(3)/3
tan(1pi):    0
tan(7pi/6):  root(3)/3
tan(5pi/4):  1
tan(4pi/3):  root(3)
tan(3pi/2):  nan
tan(5pi/3):  -root(3)
tan(7pi/4):  -1
tan(11pi/6): -root(3)/3
tan(2pi):    0

If you get a number larger than 2pi, subtract 2pi from it until you get a number that is in range. For example, sin(17pi/6) is the same as sin(5pi/6) == 1/2. Your program is expected to do basic simplification, for example, if your input is cos(2pi/4) this is the same as cos(pi/2) == 0. Builtin trigonometry functions are disallowed.
Shortest answer in bytes wins!

Must the output format be exactly as specified?

@ThomasKwa yes.

http://intmstat.com/blog/2011/06/exact-values-sin-degrees.pdf

@DigitalTrauma Haha, that will be the next challenge! Jk...

Pyth, 125 122 bytes
Uses the formula n = 4 - |floor(4.5-9k)|, where kπ = θ i.e. k is the quotient of the second and third inputs, to determine which special angle is in question: the angles 0, 30, 45, 60 and 90 degrees are numbered 0 to 4 respectively, and the 90~180 degrees angles go in reverse; this formula works for θ∈[0,π]. The values of corresponding sines would be sqrt(n)/2 and existent, non-zero tangents would be 3^(n/2-1). However, my implementation uses lists with hard-coded compressed strings for higher control of output format, and it seems the code is shorter that way too.
A,c." t8¾Îzp³9ÓÍÕ¬$ ·Íb³°ü"dc." t@a'óè©ê¶oyÑáîwÀ(";J+cEE?qz\c.5ZK-4.as-4.5*3*3%J1?qz\t+?>%J1 .5\-k@GK+?>%J2 1\-k@HK

Let's turn it into pythonic pseudocode:
                                   z = input()
                                   k = ""
                                   d = " "
                                   Z = 0
A,c." t8¾Îzp³9ÓÍÕ¬$ ·Íb³°ü"d       G = "0 sqrt(3)/3 1 sqrt(3) nan".split(d)
  c." t@a'óè©ê¶oyÑáîwÀ(";          H = "0 1/2 sqrt(2)/2 sqrt(3)/2 1".split()
J+cEE                              J = eval(input())/eval(input()) +
  ?qz\c.5Z                             0.5 if z == "c" else Z
                                   # the second term converts sin to cos
K-4.as-4.5*3*3%J1                  K = 4 - abs(int(4.5 - 3*3*(J%1)))
                                   # 9* would lose precision so 3*3* instead
?qz\t                              if z == "t"
  +?>%J1 .5\-k                         print(("-" if J%1 > 0.5 else k) +
   @GK                                     G[K])
                                   else:
  +?>%J2 1\-k                          print(("-" if J%2 > 1 else k) +
   @HK                                     H[K])

Test online.


text:
Approximate ∫((e^x)/(x^x))dx
You are to approximate the value of:
$$\int^I_0 \frac {e^x} {x^x} dx$$
Where your input is \$I\$.
Rules

You may not use any built-in integral functions.
You may not use any built-in infinite summation functions.
Your code must execute in a reasonable amount of time ( < 20 seconds on my machine)
You may assume that input is greater than 0 but less than your language's upper limit.
It may be any form of standard return/output.

You can verify your results at Wolfram | Alpha (you can verify by concatenating your intended input to the linked query).
Examples
(let's call the function f)
f(1) -> 2.18273
f(50) -> 6.39981
f(10000) -> 6.39981
f(2.71828) -> 5.58040
f(3.14159) -> 5.92228
Your answer should be accurate to ±.0001.

@ThomasKwa Maximum for your language. I'll add it to the question.

Wolfram Alpha says the last one rounds to 5.92228

@Neil o-o Alrighty then, must've mistyped. Thanks!

I'll award 200 rep to the shortest valid answer in TI-BASIC that executes in <20 seconds on WabbitEmu at 100% speed.

@lirtosiast If you are still intent on following up on this bounty, you should post it here instead.

@VoteToClose Done.

Julia, 79 77 38 bytes
I->sum(x->(e/x)^x,0:1e-5:min(I,9))/1e5

This is an anonymous function that accepts a numeric value and returns a float. To call it, assign it to a variable.
The approach here is to use a right Riemann sum to approximate the integral, which is given by the following formula:
$$\int_a^b f(x) dx \approx \sum f(x) \Delta x$$
In our case, \$a = 0\$ and \$b = I\$, the input. We divide the region of integration into \$n = 10^5\$ discrete portions, so \$∆x = \frac 1 n = 10^{-5}\$. Since this is a constant relative to the sum, we can pull this outside of the sum and simply sum the function evaluations at each point and divide by \$n\$.
The function is surprisingly well-behaved (plot from Mathematica):

Since the function evaluates nearly to 0 for inputs greater than about 9, we truncate the input to be \$I\$ if \$I\$ is less than 9, or 9 otherwise. This simplifies the calculations we have to do significantly.
Ungolfed code:
function g(I)
    # Define the range over which to sum. We truncate the input
    # at 9 and subdivide the region into 1e5 pieces.
    range = 0:1e-5:min(I,9)

    # Evaluate the function at each of the 1e5 points, sum the
    # results, and divide by the number of points.
    return sum(x -> (e / x)^x, range) / 1e5
end

Saved 39 bytes thanks to Dennis!

Isn't this also equivalent to: $\frac{t\sum_{k=0}^{n}(f(a+kt)+f(a+(k+1)t))}{2}$? That seems slightly simpler of an algorithm to use.

10^4 can be written as 1e4.

@VoteToClose Ended up taking a different approach

@RainerP. Heh, right. Thanks.

The asymptotic value of the integral is $6.39981...$.  The value $6.39981... - 10^{-4}$ is first attained at $I = 7.91399...$, so you can truncate at $8$ instead of $9$ to save a little time.

Jelly, 20 19 17 bytes
ð«9×R÷øȷ5µØe÷*×ḢS

This borrows the clever truncate at 9 trick from @AlexA.'s answer, and uses a right Riemann sum to estimate the corresponding integral.
Truncated test cases take a while, but are fast enough on Try it online!
How it works
ð«9×R÷øȷ5µØe÷*×ḢS  Main link. Input: I

      øȷ5          Niladic chain. Yields 1e5 = 100,000.

ð                  Dyadic chain. Left argument: I. Right argument: 1e5.
 «9                Compute min(I, 9).
   ×               Multiply the minimum with 1e5.
    R              Range; yield [1, 2, ..., min(I, 9) * 1e5] or [0] if I < 1e-5.
     ÷             Divide the range's items by 1e5.
                   This yields r := [1e-5, 2e-5, ... min(I, 9)] or [0] if I < 1e-5.

         µ         Monadic chain. Argument: r
          Øe÷      Divide e by each element of r.
             *     Elevate the resulting quotients to the corresponding elements,
                   mapping t -> (e/t) ** t over r.
                   For the special case of r = [0], this yields [1], since
                   (e/0) ** 0 = inf ** 0 = 1 in Jelly.
              ×Ḣ   Multiply each power by the first element of r, i.e., 1e-5 or 0.
                S  Add the resulting products.

Oh, alright. Left-hand rule is how it's referred to in AP Calculus classes. :P Coolio.

I'm not familiar with that name, but the left-hand rule probably uses the left endpoints. My code uses the right ones.

(~-.-)~ It's some form of handed rule. xD

ES7, 78 bytes
i=>[...Array(n=2e3)].reduce(r=>r+Math.exp(j+=i)/j**j,0,i>9?i=9:0,i/=n,j=-i/2)*i

This uses the rectangle rule with 2000 rectangles, which (at least for the examples) seem to produce a sufficiently accurate answer, but the accuracy could easily be increased if necessary. It has to use the 9 trick otherwise the accuracy drops off for large values.
73 byte version that uses rectangles of width ~0.001 so it doesn't work above ~700 because Math.exp hits Infinity:
i=>[...Array(n=i*1e3|0)].reduce(r=>r+Math.exp(j+=i)/j**j,0,i/=n,j=-i/2)*i

MATL, 26 bytes
9hX<t1e6XK:K/*ttZebb^/sK/*

This approximates the integral as a Riemann sum. As argued by Alex, we can truncate the integration interval at approximately 9 because the function values are very small beyond that.
The maximum value of the function is less than 3, so a step of about 1e-5 should be enough to obtain the desired accuracy. So for the maximum input 9 we need about 1e6 points.
This takes about 1.5 seconds in the online compiler, for any input value.
Try it online!
9hX<         % input number, and limit to 9
t            % duplicate
1e6XK:       % generate vector [1,2,...,1e6]. Copy 1e6 to clipboard K
K/*          % divide by 1e6 and multiply by truncated input. This gives
             % a vector with 1e6 values of x from 0 to truncated input
ttZe         % duplicate twice. Compute exp(x)
bb^          % rotate top three elements of stack twice. Compute x^x
/            % divide to compute exp(x)/x^x
s            % sum function values
K/*          % multiply by the step, which is the truncated input divided
             % by 1e6

golflua, 83 chars
I'll admit it: it took my a while to figure out the min(I,9) trick Alex presented allowed computing arbitrarily high numbers because the integral converged by then.
\f(x)~M.e(x)/x^x$b=M.mn(I.r(),9)n=1e6t=b/n g=0.5+f(b/2)~@k=1,n-1g=g+f(k*t)$I.w(t*g)

An ungolfed Lua equivalent would be
function f(x)
   return math.exp(x)/x^x
end

b=math.min(io.read("*n"),9)
n=1e6
t=b/n
g=0.5+f(b/2)

for k=1,n-1 do
   g=g+f(k*t)
end
io.write(t*g)

And by "a while" I mean about 10 minutes. And that was entirely because I didn't actually read Alex's comment that explains it, just saw it in the code.

Perl 6, 90 55 bytes
{my \x=1e5;sum ((e/$_*x)**($_/x)/x for 1..min($_,9)*x)}

usage
my &f = {my \x=1e5;sum ((e/$_*x)**($_/x)/x for 1..min($_,9)*x)}

f(1).say;       # 2.1827350239231
f(50).say;      # 6.39979602775846
f(10000).say;   # 6.39979602775846
f(2.71828).say; # 5.58039854392816
f(3.14159).say; # 5.92227602782184

It's late and I need to sleep, I'll see if I can get this any shorter tomorrow.
EDIT: Managed to get it quite a bit shorter after seeing @DenkerAffe 's method.

I like how it says $h*t in there. :D

Python 2, 94 76 bytes
Thanks to @Dennis for saving me 18 bytes!
lambda I,x=1e5:sum((2.71828/i*x)**(i/x)/x for i in range(1,int(min(I,9)*x)))

Try it online with testcases!
Using the rectangle method for the approximation. Using a rectangle width of 0.0001 which gives me the demanded precision. Also truncating inputs greater 9 to prevent memory errors with very big inputs.

Pyth, 34 29 bytes
Saved 5 Bytes with some help from @Dennis!
J^T5smcc^.n1d^ddJmcdJU*hS,Q9J

Try it online!
Explanation
Same algorithm as in my Python answer.

J^T5smcc^.n1d^ddJmcdJU*hS,Q9J        # Q=input
J^T5                                 # set J so rectangle width *10^5
                       hS,Q9         # truncate inputs greater 9
                 mcdJU/     J        # range from zero to Input in J steps
     mcc^.n1d^ddJ                    # calculate area for each element in the list
    s                                # Sum all areas and output result

You can save a few bytes by assigning J to ^T5 and swapping multiplication with division by J. Also, the truncation can be done with hS,Q9.

@Dennis Thanks, did not think about that. Also the sorting trick is nice, I was just searching for min ^^

Vitsy, 39 bytes
Thought I might as well give my own contribution. ¯\_(ツ)_/¯ This uses the Left-Hand Riemann Sum estimation of integrals.
D9/([X9]1a5^D{/V}*0v1{\[EvV+DDv{/}^+]V*

D9/([X9]               Truncation trick from Alex A.'s answer.
D                      Duplicate input.
 9/                    Divide it by 9.
   ([  ]               If the result is greater than 0
     X9                Remove the top item of the stack, and push 9.

1a5^D{/V}*0v0{         Setting up for the summation.
1                      Push 1.
 a5^                   Push 100000.
    D                  Duplicate the top item of the stack.
     {                 Push the top item of the stack to the back.
      /                Divide the top two items of the stack. (1/100000)
       V               Save it as a global variable.
                       Our global variable is ∆x.
        }              Push the bottom item of the stack to the top.
         *             Multiply the top two items.
                       input*100000 is now on the stack.
          0v           Save 0 as a temporary variable.
            0          Push 1.
             {         Push the bottom item of the stack to the top.
                       input*100000 is now the top of the stack.

\[EvV+DDv{/}^+]        Summation.
\[            ]        Loop over this top item of the stack times.
                       input*100000 times, to be exact.
  E                    Push Math.E to the stack.
   v                   Push the temporary variable to the stack.
                       This is the current value of x.
    V+                 Add ∆x.
      DD               Duplicate twice.
        v              Save the temporary variable again.
         {             Push the top item of the stack to the back.
          /            Divide the top two items.
                       e/x
           }           Push the top item back to the top of the stack.
            ^          Put the second to top item of the stack to the power of the top item.
                       (e/x)^x
             +         Add that to the current sum.

V*                     Multiply by ∆x
This leaves the sum on the top of the stack. The try it online link below has N on the end to show you the result.
Try it Online!

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


text:
Difference of three input integers
Implement a function diff that takes as input three integers x, y, and z. It should return whether subtracting one of these numbers from another gives the third.
Test cases:
diff(5, 3, 2) yields True because 5 - 3 = 2
diff(2, 3, 5) yields True because 5 - 3 = 2
diff(2, 5, 3) yields True because 5 - 3 = 2
diff(-2, 3, 5) yields True because 3 - 5 is -2
diff(-5, -3, -2) # -5 - -2 is -3
diff(2, 3, -5) yields False
diff(10, 6, 4) yields True because 10 - 6 = 4
diff(10, 6, 3) yields False

You don't have to name the function, you may implement default input methods the examples above are not a strict guideline.

This is a reasonable challenge, but there's no need to restrict it to Python or functions. In general, such restrictions are frowned upon because they limit participation. Also, you should include some test cases.

Hey I fixed it a little. Hope this suffices!

Looks better! I still strongly recommend allowing the default input methods, in particular programs, because some languages don't have functions. And, allowing functions to have another name or no name.

The first and last paragraphs are now conflicting, so just to double check - do we have to write a function or are full programs okay?

full programs are fine, I want to impose as few restrictions as possible except that the default input methods are followed. ef the python3 examples is neat!

Hmm k... just another question sorry - does input have to be True and False exactly or is any kind of truthy/falsy output allowed?

(note that not all languages have a concept of True or False, or might have different names for them)

This looks familiar, but I can't find the one I'm thinking of.  I think it might've been in Code Review SE, so not a golfing challenge.  I'm also pretty sure I've seen it given as a job interview question more than once, though they probably wouldn't appreciate you giving them any of the answers below in response...

@Geobits Well I screwed that up

It is a classic homework question in introductory programming classes so you may have seen it there.
@Sp3000 Anything Truthy or Falsy in the output might make this a little too easy. I leave it up to those with more experience to decide

Jelly, 5 3 bytes
Thanks to @Sp3000 for saving two bytes!
Code, uses quite the same algorithm as @xnor's great answer:
SfḤ

Explanation:
S     # Sum of the argument list
  Ḥ   # Double the list
 f    # Filter, remove everything that isn't equal to the sum of the list

This gives [] as falsy, and anything else as truthy.
Try it online!

An alternative 3 byter that outputs 1/0 instead of []/a different list

Python 3, 21 bytes
lambda*l:sum(l)/2in l

If two numbers add to the other, the sum of all three will be double that other number, so half the sum will be an element of the list. Python 3 is needed to avoid floor-division, unless the numbers are given like 3.0 rather than 3.

ES6, 31 bytes
(a,b,c)=>a+b==c|b+c==a|c+a==b

Add 5 bytes if you need to name the function diff.
Edit: Saved 2 bytes thanks to @Alex L.

You can save two bytes by replacing || with | (I think)

@AlexL. Ah right I was too hung up on having to return Booleans.

JavaScript ES6, 38 34 33 bytes
x=>x.some(a=>2*a==x[0]+x[1]+x[2])

Very simple anonymous function, and borrows from the Python answer. Takes input x as an array; returns true or false. Bytes shaved to Molarmanful and jrich
A 38-byte program, taking each number as an argument:
(a,b,c)=>[a,b,c].some(t=>t==(a+b+c)/2)

Try x=>x.some(a=>a==eval(x.join\+`)/2)`, which saves 4 bytes.

@ӍѲꝆΛҐӍΛПҒЦꝆ Thanks! Nice trick.

x=>x.some(a=>2*a==x[0]+x[1]+x[2]) seems to work.

@jrich Thanks! Nice trick!

Oracle SQL 11.2, 49 bytes
SELECT 1 FROM DUAL WHERE(:1+:2+:3)/2IN(:1,:2,:3);

Rewrite of @xnor solution, kudos to him.

Perl 6, 20 19 bytes

I have two functions equal in byte count, so I'll put both. Appreciate whichever tickles your fancy.
{@_∋@_.sum div 2}
{@_∋+~(@_.sum/2)}

Usage: assign either one to a variable from which you can call it.
EDIT: Thanks @b2gills for the byte reduction

{@_∋@_.sum div 2} and {@_∋+~(@_.sum/2)} are both shorter

Oh thanks, I always forget you can call sum as a dotty method

What does ∋ do ?

"∋" is the 'contains' infix operator, which says that the left contains the right. It's the sister to the "∈" 'element' op which say that the left is an element of the right. They're both set ops and perl 6 actually supports many others too! http://docs.perl6.org/language/unicode_texas#Other_acceptable_codepoints

J, 6 bytes
+/e.+:

Try it with J.js.
How it works
+/e.+:    Monadic verb. Argument: A
    +:    Double the elements of A.
+/        Compute the sum of the elements of A.
  e.      Test for membership.

APL, 8 5 bytes
+/∊+⍨

This is a monadic function train that accepts an array and returns a boolean (0/1 in APL). It uses the same algorithm as xnor's Python 3 answer.
Explanation:
   +⍨  ⍝ Double the input (+⍨x is the same as x+x)
  ∊    ⍝ Test the membership of
+/     ⍝ The sum of the input

Try it online
Saved 3 bytes thanks to Dennis!

DUP, 31 chars / 39 bytes
[2ø2ø2ø++2/\%3ø^=3ø2ø=3ø3ø=||.]

Try it here!
My first DUP submission ever! Unicode is your oyster.
It's an anonymous function/lambda. Usage:
5 3 2[2ø2ø2ø++2/\%3ø^=3ø2ø=3ø3ø=||.]!

Explanation
[                               {start lambda}
 2ø2ø2ø                         {duplicate 3 inputnums}
       ++                       {push sum(3 popped stack items)}
         2/\%                   {push (popped stack item)/2}
             3ø^=3ø2ø=3ø3ø=     {for all 3 inputs, -1 if inputnum=sum/2; else 0}
                           ||   {check if any of the 3 resulting values are truthy}
                             .  {output top of stack (boolean value)}
                              ] {end lambda}

I don't think that's how an encoding works...

ø has code point 248, so it is one byte if encoded as ISO 8859-1.

... which is fine as long as the interpreter can actually work with an ISO 8859-1 encoded source file.

@MartinBüttner I don't think it's possible to test that.

Java 7, 81
boolean d(int[]a){int s=0,t=1;for(int b:a)s+=b;for(int b:a)t*=2*b-s;return t==0;}

Java 8 (lambda function), 29 bytes
// Lambda Signature: (int, int, int) -> boolean

(a,b,c)->a+b==c|a+c==b|b+c==a

Java code golf solutions are usually only short when the program does not have to be a fully functional program. (*cough cough* class declaration, main method)

Pyth, 6 bytes
/Q/sQ2

Try it online!
Expects input as a list of integers. Outputs 0 if no number can be built by subtracting the other two and >0 if at least one can.
Explanation:
Same algorithm as the answer of @xnor

/Q/sQ2

   sQ     # Sum all elements in the list
  /  2    # Divide the sum by 2
/Q        # Count Occurences of above number in the list

Perl, 24 + 4 = 28 bytes
$^+=$_/2 for@F;$_=$^~~@F

Requires -paX flags to run, prints 1 as True and nothing as False:
-X disables all warnings.
$ perl -paXe'$^+=$_/2 for@F;$_=$^~~@F' <<< '5 3 7'
$ perl -paXe'$^+=$_/2 for@F;$_=$^~~@F' <<< '5 3 8'
1

Inspiring one. Inspired this: $_=eval(y/ /+/r)/2~~@F (uses same command-line options).

@manatwork Interesting way to use tr :)

You could leave that -X out by specifying some Perl version [5.10 .. 5.18). (Smart match was introduced in 5.10 and experimental warnings were introduced in 5.18. Any version between those two will work fine with ~~ without -X.)

MATL, 5 bytes
Using @xnor's great approach:
s2/Gm

Try it online!
s    % implicitly input array of three numbers. Compute their sum
2/   % divide by 2
G    % push input again
m    % ismember function: true if sum divided by 2 equals some element of the input

Brute-force approach, 12 bytes:
Y@TT-1h*!s~a

Try it online!
Y@       % input array of three numbers. Matrix with all
         % permutations, each one on a different row
TT-1h    % vector [1,1,-1]
*        % multiply with broadcast
!s       % transpose, sum of each column (former row)
~a       % true if any value is 0

05AB1E, 4 bytes
DO;¢

Using 0 as falsy and > 0 as truthy. Uses CP-1252 encoding.

What's the "stupid" thing that makes this non-competing?

@KyleKanos I already have written in Info.txt that ; halves the top of the stack. But guess what, I've never implemented it -_-.

Ah. I can see how that'd do it

Kona 16 chars
{((+/x)%2)_in x}

Takes a vector from the stack, sums them, divides by 2 and determines if it's in the vector. Returns 1 as truthy and 0 as falsey.
Called via
> {((+/x)%2)_in x} [(2;3;5)]
1
> {((+/x)%2)_in x} [(2;3;4)]
0

CJam, 10 12 bytes
l~:d_:+2/&

2 bytes removed thanks to @MartinBüttner.
This displays a number as truthy result, and no output as falsy result.
Try it here
l~     e# read line and evaluate. Pushes the array
:d     e# convert array to double
_      e# duplicate
:+     e# fold addition on the array. Computes sum of the array
2/     e# divide sum by 2
&      e# setwise and (intersection)

jq, 17 characters
(Yet another rewrite of xnor's Python 3 answer. Upvotes should go to that one.)
contains([add/2])

Input: array of 3 integers.
Sample run:
bash-4.3$ jq 'contains([add/2])' <<< '[5, 3, 2]'
true

bash-4.3$ jq 'contains([add/2])' <<< '[2, 3, -5]'
false

On-line test:

[5, 3, 2]
[2, 3, -5]

jq, 18 characters
(17 characters code + 1 character command line option.)
contains([add/2])

Input: list of 3 integers.
Sample run:
bash-4.3$ jq -s 'contains([add/2])' <<< '5 3 2'
true

bash-4.3$ jq -s 'contains([add/2])' <<< '2 3 -5'
false

, 7 chars / 9 bytes
ï⒮≔⨭ï/2

Try it here (Firefox only).
Meh. I'm still finding better ways. It's just @xnor's awesome algorithm.

Seriously, 6 bytes
,;Σ½íu

Outputs 0 if false and a positive integer otherwise.

Mathematica, 20 19 bytes
MemberQ[2{##},+##]&

Works similarly to most of the other answers.

How about MemberQ[2{##},+##]&? (and you forgot your byte count)

Haskell, 20 bytes
(\l->sum l/2`elem`l)

Using xnor's solution.

Since (/) doesn't work for integers and the challenge asks for integers, I'm not sure that this is actually a valid solution.

I did not see that. Should the type conversion be part of the code? Like this: (\l->sum l/2\elem`l).map fromIntegerand it can be used like this:((\l->sum l/2`elem`l).map fromInteger) ([2,3,5] :: [Integer])`. I guess what threw me off was xnor mentioning the use of python 3 so the input didn't have to be 3.0 instead of 3. I thought the input type wasn't specified, just the way they were written...

If the type is a really a problem shouldn't the fact that I'm taking a list as input be more of an issue?

Good point. I would ask OP about that. But given that all the other answers also use a list, I guess it's OK (also, now I get why your function didn't type check when using tuples).

Yes if the input was a tuple instead of a list neither sum nor elem would work, I should probably have specified it was a list but since this answer is literally what xnor submitted (in Haskell) I didn't think it was necessary. :)

R, 23 bytes
sum(x<-scan())%in%(2*x)

Try it online!
Shameless port of xnor's answer.

Prolog (SWI), 35 bytes
\A:-permutation([X,Y,E],A),X-Y=:=E.

Try it online!

Jolf, 6 bytes
Try it here!
 hx½ux
_hx    the input array
   ½ux  has half the sum of the array

This is xnor's awesome solution to the problem, but in Jolf.

Pylons, 8
Yet another implementation of xnor's algorithm.
i:As2A/_

How it works:
i    # Get command line input.
:A   # Initialize a constant A.
  s  # Set A to the sum of the stack.
2    # Push 2 to the stack.
A    # Push A to the stack.
/    # Divide A/2
_    # Check if the top of the stack is in the previous elements.
     # Print the stack on quit.

SpecBAS - 36 bytes
Uses xnors formula
1 INPUT a,b,c: ?(a+b+c)/2 IN [a,b,c]

outputs 1 if true and 0 if false

05AB1E, 6 5 bytes
;Oм_O

-1 byte by creating a port of @xnor's Python 3 algorithm.
Try it online or verify all test cases.
Explanation:
·        # Halve every item in the input-array
         #  i.e. [10,6,4] → [5.0,3.0,2.0]
 O       # Sum this array
         #  i.e. [5.0,3.0,2.0] → 10.0
  м_O    # Output 1 if the input-array contain this sum, 0 otherwise
         #  i.e. [10,6,4] and 10.0 → 1

I'm pretty sure м_O can be shortened, but I'm not sure which command(s) I have to use for it..


text:
Apply Kirchhoff's law
Kirchhoff's law says that when you sum up all the currents (positive for the currents going to a junction, and negative for current leaving a junction), you will always get as result 0.
Look at the following diagram:

Using Kirchhoff's law, you can see that i1 + i4 - i2 - i3 = 0, so i1 + i4 = i2 + i3.
Given two lists, one with all the currents entering the junction and one with all the currents leaving the junction except one, output the last one.
Testcases:
[1, 2, 3], [1, 2] = 3
[4, 5, 6], [7, 8] = 0
[5, 7, 3, 4, 5, 2], [8, 4, 5, 2, 1] = 6

The second list always has one item less than the first list. The output cannot be negative. Smallest program wins.

The puzzle would have been better if you actual gave resistor and current values. This Q seems like you have introduced the law just as a namesake. (The Q could have easily been stated without the law)

Kirchoff's current law

Related.

Can you specify is we can just create a function that returns the result or actually print/return the result.

Jelly, 2 bytes
_S

Try it here!
Takes the entering currents in the first argument, and the leaving currents in the second argument. _ subtracts them pairwise, leaving the single element from the longer list as-is, and S sums the result.

Haskell, 14 bytes
(.sum).(-).sum

Usage example: ( (.sum).(-).sum ) [5,7,3,4,5,2] [8,4,5,2,1] -> 6.
Sum each list and take the difference.

CJam, 8 6 bytes
q~.-:+

Input uses two CJam-style arrays.
Run all test cases. (This reads multiple test cases at once and includes a framework to process each line individually, discarding the expected result from the input.)
Explanation
q~  e# Read and evaluate input.
.-  e# Elementwise difference.
:+  e# Get sum.

.- works reliably because we're guaranteed that the first list is always longer than the second. (Otherwise, the extraneous elements of the second list would be appended to the result which would add them to the sum instead of subtracting them.)

Congrats on exactly 80k!

MATL, 3 4.0 bytes
_hs

Inputs are: leaving currents first, then entering currents.
Try it online!
_     % implicitly input array with leaving currents (except one). Negate
h     % implicitly input array with entering currents. Concatenate
s     % sum of all elements in concatenated array

The exact same solution as mine, but with different letters haha, +1

@Adnan I saw! (+1 already)

@Adnan I've reduced to 3 bytes changing input order and concatenating both arrays. Maybe that can be applied to your answer as well?

Ahhh, I should really implement a concatenate function :p. Very nice answer! :)

05AB1E, 4 bytes
Code:
OEO-

Explanation:
O     # Take the sum of the input list
 E    # Evaluate input
  O   # Take the sum of the input list
   -  # Substract from each other

Thanks to Luis Mendo for reminding me that I need to implement a concatenate function. If I've had implemented it sooner, it would have been 3 bytes:
Non-competing version (3 bytes):
The first list is the leaving current list, the second is the entering current list. Code:
(«O

Explanation:
(    # Negate the list, e.g. [3, 4, 5] would become [-3, -4, -5]
 «   # Concatenate the second list to the first
  O  # Take the sum and implicitly output it

Uses CP-1252 encoding.

Javascript, 36 bytes
(a,b)=>eval(a.join`+`+'-'+b.join`-`)

f=
(a,b)=>
    eval(
        a.join`+`
        +'-'+
        b.join`-`
    )

document.body.innerHTML = '<pre>' +
  'f([1,2,3],[1,2]) = ' + f([1,2,3],[1,2]) + '\n' +
  'f([4,5,6],[7,8]) = ' + f([4,5,6],[7,8]) + '\n' +
  'f([5,7,3,4,5,2],[8,4,5,2,1]) = ' + f([5,7,3,4,5,2],[8,4,5,2,1]) + '\n' +
'</pre>'

Mathematica, 17 11 bytes
Tr@#-Tr@#2&

Quite simple.

Common Lisp, 40
(lambda(x y)(-(reduce'+ x)(reduce'+ y)))

Perl 6, 11 bytes
*.sum-*.sum

Usage:
# give it a lexical name
my &code = *.sum-*.sum;

say code [1, 2, 3], [1, 2]; # 3
say code [4, 5, 6], [7, 8]; # 0
say code [5, 7, 3, 4, 5, 2], [8, 4, 5, 2, 1]; # 6

Python 3, 24 bytes
lambda a,b:sum(a)-sum(b)

or
Python 2, 19 bytes
print sum(a)-sum(b)

depending if I am required to print the result or just create a function that returns it.

ES6, 39 bytes
(i,o)=>i.reduceRight((r,a,j)=>r+a-o[j])

Because I wanted to use reduceRight.

Python 2, 30 bytes
a,b=map(sum,input());print a-b

Pyth, 6 bytes
-.*sRQ

Explanation
       - autoassign Q = eval(input())
   sRQ - map(sum, Q)
-.*    - imp_print(minus(*^))

Try it here

K5, 5 bytes
-/+/'

Difference over (-/) sum over (+/) each (').
In action:
  (-/+/')'((1 2 3;1 2);(4 5 6;7 8);(5 7 3 4 5 2;8 4 5 2 1))
3 0 6

Pyth, 5 bytes
-FsMQ

Try it online. Test suite.
Map sum on both input lists, then Fold subtraction (-).
This could also be written as -sQsE, which takes the lists on two lines.

, 5 chars / 7 bytes
⨭î-⨭í

Try it here (Firefox only).
Wut.
Explanation
sum(input1) - sum(input2)

Common Lisp REPL, SBCL 28 24 bytes
write this into REPL:
#.`(-(+ #1=,@(read))#1#)

then write input lists like this:
(2 3 4)
(2 3)

I hope it's okay to use such list format (instead of e.g. '(2 3 4))
I used coredump's answer as formula for my solution and then achieved his calculation effect in a different way.
Explanation
Let e_1,...,e_n be elements of the first list and f_1,...,f_{n-1} be elements of second list.
We want to evaluate expression (-(+ e_1 e_2 ... e_n)f_1 f_2 ...f_{n-1})
It would mean subtracting elements of second list from sum of elements of first list.
The needed expression is constructed like so:
backqoute stops evaluation
#1= saves a bit of writting, remembering ,@(read)
,@ stops effects of backquote (so that (read) will be evaluated) and takes elements out of a list.
(read) asks for input
#1# "loads" Lisp object saved by #1=
#. does evaluation of printed representation of an Lisp object


text:
Dank Meme Generator
I like making dank memes out of my own images. But all those so called "quick meme" sites just have too much code. I realized that the only way to make the dankest meme generator is to ask you guys at PPCG to golf one for me. So let me give you the low down on what you have to do.
Specs

Take an image as input as a file name, image object, etc. to make a meme out of.
Then take two strings for top text and bottom text (with no line breaks).
Render the text on the image in size 22pt Impact white font with 5px black outline (You can assume Impact is installed.
The text should be centered horizontally.
You can assume the text fits horizontally.
The respective texts should be 10px from the top and 8px from the bottom.
Then output the image by saving in a file, displaying, etc.
This is code-golf, so shortest code in bytes wins!

Happy Memeing!

Can we assume the Impact font is installed?

@Downgoat yeah.

...advice animals? Is this what you call a dank meme?

These memes aren't dank at all. This is like, entry-level memeology.

@Pyritie Not everyone should be allowed to wield meme magic just yet.

Can we assume we have impact font including the black border installed?

HTML/JS/CSS, 341 329 300 bytes
<input onblur=i.src=this.value>

@dev-null Well, I can get rid of the first  at least (the second is needed to prevent you from pressing Ctrl+A, Del to delete the style element).

@Neil I guess you can change left:0;right:0 to width:100% and onchange to onblur

When I tested it you can swap the 0 0 5px #000, 0 0 5px #000, 0 0 5px #000, 0 0 5px #000 for "0 0 5px #000,"*5

@Neil If you only targer webkit browsers then you can use: -webkit-text-stroke:5px#000 expect it seems to be inline and not outline.

@dev-null Fortunately I don't use webkit/blink browsers.

@Neil Now that I think about it, cant  you use window.MY_ID.src=... and , eg: I.src,

Jelly, 141 bytes
⁴;@€“¢ÇẎȧsẊỊ>ɼẈAẋ®ŀȮĠq⁼ṫṁḢĠZỴċƊ£²ÆṗÑḊ°>oÆl{(¢ɗpḅ]µṖÑb¹ƁịṾ¦Ç\ṭO4»“1kịXḥɗ"Ụɦḷ©Ƈ&Ṭ19“£ŀ³³.Ṗ<ṂqṬỵ.ṣȦƇƈ2ƭḂXƊ»ż³;“ßƑ_!]²Rȧ⁵⁴°ṁD⁽a{⁼!z¿ıṾƇDẇḤḶṡÇẈg»;

Try it online!
Takes command line arguments as in the example, and returns a HTML file. The result looks like this in Chrome:

Nice answer, but I'm not counting this as an image. Its not really graphical output.

Upgoated, nice golf.

Guess @Downgoat needs a sibling named Upgoat now.

bash+imagemagick+gs 690 575 456 440 bytes
See earlier revisions for "ungolfed" code.
#!/bin/bash
d=`identify $1|cut -d' ' -f3`
x=`echo $d|cut -d'x' -f1`
y=`echo $d|cut -d'x' -f2`
convert $1 $1.eps
gs -g"$d" -o $1.png -sDEVICE=png48 -c "
/s/showpage load def/showpage{}def($1.eps)run
matrix defaultmatrix setmatrix/Helvetica-Bold 22
selectfont/c{dup stringwidth pop neg 2 div 0 rmoveto dup
gsave 1 setgray show grestore 0 setgray false charpath stroke}def
$x 2 div $y 42 sub moveto($2)c $x 2 div 8 moveto($3)c s"
echo :$1.png

eg.
./meme.sh Superman1.jpg "I AM CORNHOLIO" "Are you threatening me??!"
GPL Ghostscript 9.15 (2014-09-22)
Copyright (C) 2014 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Loading NimbusRomNo9L-Regu font from /usr/share/ghostscript/9.15/Resource/Font/NimbusRomNo9L-Regu... 4186304 2700982 3995248 2685490 2 done.
Loading NimbusSanL-Bold font from /usr/share/ghostscript/9.15/Resource/Font/NimbusSanL-Bold... 4203248 2760390 3833712 2536130 1 done.
:Superman1.jpg.png

That's not impact font!

True. It appears I don't have it installed. fc-list can't find it.

I could specify Impact anyway, but then it'd render with Courier.


text:
Who's gonna win the football game?
The American football championship, Super Bowl 50, is happening today at 11:30pm UTC (and you can watch it live online). This challenge was made to celebrate it.

In an American football game, two teams compete to get the most points and there are six ways to score these points. We'll give each an abbreviation:

Field goal - FG: 3 points
Touchdown - TD: 6 points
Extra point - XP: 1 point - Can only be scored directly after a touchdown.
Two-point conversion - XD (like an extra point but happier): 2 points - Can only be scored directly after a touchdown.
Safety - S: 2 points
Fair catch kick - FCK: 3 points (a very rare play)

Write a program or function that takes in a single line string containing only these six abbreviations, in both uppercase and lowercase.
This string represents all the scoring events in a game (or portion of a game) of football, with the uppercase terms belonging to one team and the lowercase belonging to the other.
Your job is to report the final scores of the game and indicate who won with output of the form
[score 1] [to] [score 2]

where:

[score 1] is always the larger of the two scores (if not equal), regardless of if uppercase or lowercase won.
[score 2] is the smaller of the two scores (if not equal).
[to] is TO if the uppercase team won, to if the lowercase team won, and To if it's a tie.

Example: All the scoring events in Super Bowl XLIX
  could be summarized by the string
TDXPtdxpTDXPtdxpfgtdxpTDXPTDXP

where uppercase is the New England Patriots and lowercase is the
  Seattle Seahawks. The Patriots scored 28 and the Hawks 24, so
  the output would be:
28 TO 24

Notes

Your program/function must support any arbitrary input, including the empty string.
XP and XD will only occur right after TD. xp and xd will only occur right after td.
You may not assume the input string starts or ends in a certain case.
A single trailing newline is optionally allowed in both the input and output

Scoring
The shortest code in bytes wins. Answers that are posted before the kickoff (too late now!) of Super Bowl 50 may predict the winning team (either Panthers or Broncos), and if they are correct, get a -10% byte bonus!
(I will check revision history to ensure predictions have not changed and really were made before kickoff.)
Test Cases
[empty string] -> 0 To 0
TDXPtdxpTDXPtdxpfgtdxpTDXPTDXP -> 28 TO 24
FG -> 3 TO 0
fg -> 3 to 0
TD -> 6 TO 0
td -> 6 to 0
TDXP -> 7 TO 0
tdxp -> 7 to 0
TDXD -> 8 TO 0
tdxd -> 8 to 0
S -> 2 TO 0
s -> 2 to 0
FCK -> 3 TO 0
fck -> 3 to 0
TDTDXDSssFCKfgfckFGtd -> 22 TO 16
fcksFCKS -> 5 To 5
tdtdtdtdxp -> 25 to 0
SSSSSSSTD -> 20 TO 0
fgSfckFGfgtdxptdxdTDs -> 26 to 11
FGTDXPtdxdtdsStdxpfgTDfckTDXDFCK -> 29 To 29

I believe it's stylized as "Superb Owl", not "Superbowl"

Does the bonus still apply if you edit your post after the Super Bowl has finished?

@Doorknob How about this: If you make the prediction before kickoff and don't change it with any edits, you can edit your code as much as you want. (But your prediction must be in your answer, not in some comment. so you need working code to start.)

Can I just make a prediction and not answer? :P

Two questions: 1) is there an extra bonus for correctly predicting the scores? 2) is there an extra extra bonus for correctly predicting the scoring events? ;)

@ETHproductions No. Just the bonus for picking the team that wins.

Remind me to do a new version of this for International Rules Football when that's next played.

I'm not a big fan of the scoring bonus. It's unfair to those who first saw this challenge after the superb owl, it's biased towards those that pay attention to the NFL, and it's totally unrelated to programming ability.

Pyth, 49 46 43 42 bytes (37.8 bytes with bonus)
jr" to "xh._-FJmsmhx"PSFT"kXd\D\S,rz2z2_SJ

Thanks to @Maltysen for helping me save 4 bytes!
Try it in the Pyth Compiler.
I like covering all bases, so I'll bet on the Broncos.
How it works
jr" to "xh._-FJmsmhx"PSFT"kXd\D\S,rz2z2_SJ Input: z

                                  rz2      Swap the case of z.
                                 ,   z     Pair the result with z.
               m                           Map; for each d in the pair:
                           Xd\D\S            Replace each D with an S.
                 m                           Map; for each character k:
                   x"PSFT"k                    Compute k's first index on "PSFT".
                  h                            Increment the index.
                s                            Compute the sum of the incr. indices.
                                               "FG"  -> [3, 0]     -> 3
                                               "TD"  -> [4, 2]     -> 6
                                               "XP"  -> [0, 1]     -> 1
                                               "XD"  -> [0, 2]     -> 2
                                               "S"   -> [2]        -> 2
                                               "FCK" -> [3, 0, 0]  -> 3
                                               (lowercase letters) -> 0
              J                            Save the resulting list of scores in J.
            -F                             Reduce J by subtraction.
          ._                               Compute the sign of the difference.
         h                                 Add 1.
        x                             2    XOR the result with 2.
 r" to "                                   Pick‡ a function and apply it to " to ".
                                       _SJ Sort and reverse the list of scores.
j                                          Join, separating by the modified string.

‡ r is a family of functions that operate on strings.

If the first score in J (corresponding to swapped case z, i.e., the original lowercase letters) is lower than the second score, the sign function will return -1, (-1 + 1) ^ 2 == 2 and r" to "2 is swapcase, so it returns " TO ".
If the first score is higher than the second score, the sign function will return 1, (1 + 1) ^ 2 == 0 and r" to "0 is lowercase, so it returns " to ".
If the scores are equal, the sign function will return 0, (0 + 1) ^ 2 == 3 and r" to "3 is title, so it returns " To ".

I didn't try it, but you can probably save by making the various tos through different values to r

@Maltysen That worked nicely. Thanks!

MATL, 51*0.9 = 45.9 54 57 58 63 bytes
Thanks to Dennis for removing 3 bytes!
'%i To %i'j0h!3'PDFTS'tkXc=s4:Hh*sSPYD3MdXK?kK0<?Xk

An empty input string is represented in the online compiler as a single newline character.
EDIT (June 8, 2016): The link below includes a modification as per release 18.1.0 of the language (move he first 3 right before Xc)
Try it online!
I bet on the Broncos.
Explanation
The scores are detected using a single letter, either upper or lowercase (uppercase is shown in the following):

P for XP (1 point)
D for XD (2 points)
F for FG (3 points) and for FCK (3 points)
T for TD (6 points)
S for S (2 points)

Each of these five letters corresponds uniquely to a score event except that

F is reused for FG and FCK, which have the same score. Thanks to @Dennis for this!
D will detect both TD and XD. So T will be assigned 4 points instead of 6 to compensate.

The ordering PDFTS, saves a few bytes when defining the number array that specifies the points: [1,2,3,4,2].
Each event is detected by the presence of one of the above letters in uppercase or lowercase. The comparison is done in three dimensions: input string length (N) × number of teams (2) × number of detected score events (5). Extensive use is made of broadcasting, which is the automatic expansion of an array along a singleton dimension to match the size of a larger array.
'%i To %i'  % string with format specifiers for two integers
j0h         % input string. Attach 0 so it's never empty. Gives string of length N>0
!           % transpose into char array of size N×1
3           % number literal
'PDFTS'     % characters to detect the five combined types of score
tk          % duplicate and convert to lowercase
Xc          % concatenate along the third dimension to produce a 1×5×2 array
=           % test for equality with broadcast. Gives N×5×2 array
s           % sum along 1st dim. Gives 1×5×2 array
4:Hh        % array [1,2,3,4,2] to compute the total score. Size 1×5(×1)
*           % multiply with broadcast. Gives 1×5×2 array
s           % sum along 2nd dim. Gives 1×1×2 array with the two scores
SP          % sort in reverse order along 3rd dim
YD          % sprintf. Gives output string with "To"
3M          % push array with the two scores again
dXK         % difference along 3rd dim. Gives a number. Copy to clipboard K
?           % is it non-zero? If so we need to make either lowercase or uppercase
  k         %   make (tentatively) lowercase
  K0<       %   did the uppercase team win?
  ?         %   if so...
    Xk      %     make uppercase
            % implicitly end the two if's and display string

No win prediction?

@Calvin'sHobbies I was consulting the Wikipedia... my knowledge of American football is close to nil :-)

Reusing the F in FG and FCK should save three bytes.

CJam, 57 55 54 53 50 49 bytes
q_32f^]{"PSFTD"f#:)5Yer1b}%_$(@:-g"ToTOto"2/=\]S*

Try it online!
I have no idea what a Bronco is, so I'll bet on the Panthers.
How it works
q                              Read all input from STDIN.
 _                             Push a copy.
  32f^                         XOR all characters with 32. This swaps case.
      ]                        Wrap both strings in an array.
       {                 }%    Map; push the string S, then:
        "PSFTD"                    Push that string (T).
               f#                  Compute the index of each character of S in T.
                 :)                Increment each index.
                   5Yer            Replace 5's with 2's.
                       1b          Add the resulting integers.
                                       "FG"  -> [3 0]      -> 3
                                       "TD"  -> [4 2]      -> 6
                                       "XP"  -> [0 1]      -> 1
                                       "XD"  -> [0 2]      -> 2
                                       "S"   -> [2]        -> 2
                                       "FCK" -> [3 0 0]    -> 3
                                       (lowercase letters) -> 0

                               We've now computed the scores of the first (input)
                               and second (swapped case) team.

_$                             Push a copy of the array of scores and sort it.
  (                            Shift out the first (lower) score.
   @                           Rotate the array of scores on top.
    :-                         Reduce it by subtraction.
      g                        Compute the sign (1, 0 or -1) of the difference.
       "ToTOto"2/              Push ["To" "TO" "to"].
                 =             Select the string that corresponds to the sign.
                  \            Swap it with the lower score.
                   ]           Wrap the entire stack in an array.
                    S*         Join the resulting array, separating by spaces.

There ya go

:-g never seen that emoticon before

@ETHproductions snail-mouth?

@ETHproductions It's someone whose glasses have fallen down over their mouth.

This is a Bronco.

JavaScript (ES6), 128 130 bytes
Edit 2 bytes saved applying @Neil's tip

s=>(l=u=0,s.replace(/fck|s|../gi,x=>(z=+' 231  362'[parseInt(x,36)%10],x>'a'?l+=z:u+=z)),l>u?l+' to '+u:u+(u>l?' TO ':' To ')+l

TEST

f=s=>(
  l=u=0,
  s.replace(/fck|s|../gi,x=>(
    z=+' 231  362'[parseInt(x,36)%10],
    x>'a'?l+=z:u+=z
  )),
  l>u?l+' to '+u:u+(u>l?' TO ':' To ')+l
)

//TEST
console.log=x=>O.textContent+=x+'\n'

;[
["","0 To 0"],
["TDXPtdxpTDXPtdxpfgtdxpTDXPTDXP", "28 TO 24"],
["FG", "3 TO 0"],
["fg", "3 to 0"],
["TD", "6 TO 0"],
["td", "6 to 0"],
["TDXP", "7 TO 0"],
["tdxp", "7 to 0"],
["TDXD", "8 TO 0"],
["tdxd", "8 to 0"],
["S", "2 TO 0"],
["s", "2 to 0"],
["FCK", "3 TO 0"],
["fck", "3 to 0"],
["TDTDXDSssFCKfgfckFGtd", "22 TO 16"],
["fcksFCKS", "5 To 5"],
["tdtdtdtdxp", "25 to 0"],
["SSSSSSSTD", "20 TO 0"],
["fgSfckFGfgtdxptdxdTDs", "26 to 11"],
["FGTDXPtdxdtdsStdxpfgTDfckTDXDFCK", "29 To 29"]
].forEach(t=>{
  var i=t[0],x=t[1],r=f(i)
  console.log(i+' -> '+r+(r==x?' OK':' FAIL expected '+x))
})

Wow, that trick with parseInt is really clever! Using @Neil's tip of l>u?l+" to "+u:u+(u>l?" TO ":" To ")+l for the output would save 2 bytes as well.

@user81655 well I consider parseInt each time I need to operate on some small group of letters in case insensitive way ... 99% of times it's useless. Thanks for pointing out Neil's tip

Perl, 144 140 + 2 = 142 bytes
%a=qw(fg 3 td 6 xp 1 xd 2 s 2 fck 3);@a=(0,0);$^=lc,$a[$^eq$_]+=$a{$^}for/fck|s|../gi;$,=$".(To,TO,to)[$a[1]-$a[0]<=>0].$";say sort{$b-$a}@a

Requires the -n flag and -E:
$ echo "
TDXPtdxpTDXPtdxpfgtdxpTDXPTDXP
FG
fg
SSSSSSSTD
FGTDXPtdxdtdsStdxpfgTDfckTDXDFCK" | \
perl -nE'%a=qw(fg 3 td 6 xp 1 xd 2 s 2 fck 3);@a=(0,0);$^=lc,$a[$^eq$_]+=$a{$^}for/fck|s|../gi;$,=$".(To,TO,to)[$a[1]-$a[0]<=>0].$";say sort{$b-$a}@a'
0 To 0
28 TO 24
3 TO 0
3 to 0
20 TO 0
29 To 29

Edit: Forgot to support to, To and TO.

Nice. But %a=qw(fg 3 td 6 xp 1 xd 2 s 2 fck 3) is briefer as %a=(fg,3,td,6,xp,1,xd,2,s,2,fck,3). And " " (in your definition of $,) is briefer as $". But I haven't tested either of those.

@msh210, I can use $" and I can remove qw on the to To TO array, thanks!

JavaScript (ES6), 165 156 151 149 bytes
s=>(a=b=0,s.match(/S|FCK|../gi)||[]).map(m=>(u=m.toUpperCase(),p=u>"XO"?1:u=="TD"?6:u>"R"?2:3,u<m?a+=p:b+=p))&&a>b?a+" to "+b:b+(b>a?" TO ":" To ")+a

9 bytes saved thanks to @dev-null, 5 thanks to @Not that Charles and 2 thanks to @Neil!
Explanation

var solution =

s=>(
    a=b=0,                // scores for teams A and B
    s.match(/S|FCK|../gi) // get an array of each abbreviation
      ||[]                // if it returns null, default to an empty array
  ).map(m=>(              // for each abbreviation m
    u=m.toUpperCase(),    // u = abbreviation in upper-case
    p=                    // p = number of points for the abbreviation
      u>"XO"?1            // case "XP"
      :u=="TD"?6          // case "TD"
      :u>"R"?2            // case "XD" or "S"
      :3,                 // case "FG" or "FCK"
    u<m?a+=p:b+=p         // add the points to the appropriate team
  ))

  // Output the scores
  &&a>b?a+" to "+b
  :b+(b>a?" TO ":" To ")+a
<input type="text" id="input" value="FGTDXPtdxdtdsStdxpfgTDfckTDXDFCK" />
<button onclick="result.textContent=solution(input.value)">Go</button>

Cant you use /s|fck|../gi and map(..),a>b instead of map(..)&&a>b

I think you'd save some if you did ...:u=="T"?6:u>"R"?2:3...

@NotthatCharles True. Thanks for the tip!

I think you might save 2 bytes using b+(b>a?" TO ":" To ")+a

Lua, 231 200 Bytes
It was a lot of fun, even if I don't really know the rules of american football (We have Rugby here :)). I had to test a lot of things to make it as short as possible, I don't think there's a lot of things to improve, maybe there isn't.
Edit: I'm a total retard. The first solution I've worked on revolved around using array expansion, then I changed it and the array containing the scores for both the lowercase and the uppercase team wasn't useful anymore. Removing it and using plain variable makes a beautiful -31 bytes.
a={F=3,D=2,T=4,P=1,S=2}l,u=0,0 io.read():gsub(".",function(c)x=a[c:upper()]if a[c]then u=u+a[c]elseif x then l=l+x end end)w=l>u and" to "or l<u and" TO "or" To "print(math.max(l,u)..w..math.min(l,u))

Ungolfed and explanations
a={F=3,D=2,T=4,P=1,S=2}        -- define the table a with our scoring values
l,u=0,0                        -- scores for the upper and lowercase teams
io.read():gsub(".",function(c) -- iterate over each character in the input
  x=a[c:upper()]               -- x contains the score for a lowercase character
  if a[c]                      -- if a contains c (would evaluate to nil otherwise)
  then
    u=u+a[c]                   -- increment the score of the uppercase team
  elseif x                     -- if x isn't nil
  then                         -- same as "a contains c:upper()"
    l=l+x                      -- increment the score of the lowercase team
  end
end)                           -- exit the anonyme function
w=l>u and" to "               -- nested ternary, lower > upper, we will use "to"
    or l<u and" TO "       -- lower < uppercase, use "TO"
    or" To "                   -- else (draw), use "To"
print(math.max(l,u)        -- output the concatenated string using
      ..b.w..math.min(l,u))-- min/max to put the winner in the first position

Python, 167 bytes
The superb owl is long past, but since there isn't a Python solution yet:
def f(s):g=lambda s:0if s==""else{68:1,70:3,83:2,84:5,88:1}.get(ord(s[0]),0)+g(s[1:]);a=g(s);b=g(s.upper())-a;return"%i %s %i"%((a,("To","TO")[a>b],b),(b,"to",a))[a<b]

Works in Python 2 or 3.