text:
Output a string's cumulative slope
Challenge
Given a string such as Hello World!, break it down into its character values: 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33.
Then calculate the difference between each consecutive pair of characters: 29, 7, 0, 3, -79, 55, 24, 3, -6, -8, -67.
Finally, sum them and print the final result: -39.
Rules

Standard loopholes apply
No using pre-made functions that perform this exact task
Creative solutions encouraged
Have fun
This is marked as code-golf, the shortest answer in bytes wins but will not be selected.

Dennis's observation shows that this task is phrased in a more complicated way than necessary.

Can a language accept input as a character array even if it supports string types?

@Poke sorry, has to be a string

@GregMartin I actually did not realize that until later. The challenge should stay this way though.

@DJMcMayhem Good to know, all other forms of output are hereby allowed.

Python, 29 bytes
lambda s:ord(s[-1])-ord(s[0])

The sum of the differences forms a telescopic series, so most summands cancel out and
(s1 - s0) + (s2 - s1) + … + (sn-1 - sn-2) + (sn - sn-1) = sn - s0.
If taking a byte string as input is allowed
lambda s:s[-1]-s[0]

will work as well for 19 bytes.
Test both on Ideone.

Does this print the result?

In a REPL, I guess it does. The intended form of output is a return value though, which is one of our default methods of output. If that's not allowed, most of the answers in production languages are invalid.

MATL, 2 bytes
ds

Try it online!
Explanation:
d gets the difference between consecutive characters and s sums the resulting array. Then, the value on top of the stack is implicitly printed. Not much else to say about that.
Interestingly enough, even though Dennis discovered an awesome shortcut, using it would be significantly longer in MATL.

Jelly, 3 bytes
OIS

Try it online!
Take the Ordinals of the input string’s characters, then the Increments of that list, then the Sum of that list.

Yeah, printing the result (and taking input in the first place) happens implicitly in Jelly.

MATLAB, 16 bytes
@(x)sum(diff(x))

This creates an anonymous function named ans which can be called like: ans('Hello world!').
Here is an online demo in Octave which requires an additional byte + to explicitly convert the input string to a numeric array prior to computing the element-to-element difference

Python, 63 bytes
x=map(ord,input())
print sum(map(lambda(a,b):b-a,zip(x,x[1:])))

Ideone it!

Cubix, 13 bytes
Cubix is a 2-dimensional language wrapped around a cube.
i?u//O-t#;/.@

Test it online! This maps to the following cube net:
    i ?
    u /
/ O - t # ; / .
@ . . . . . . .
    . .
    . .

Where the IP (instruction pointer) starts at the top-left of the far-left face.
How it works
First, the IP hits the mirror / which redirects it onto the i on the top face. The top face is a loop which continually inputs charcodes until EOF is reached. When the input is empty, the result of i is -1; the IP turns left from the ?, hitting the / on the far right face and going through the following commands:

; - Pop the top item (-1).
# - Push the length of the stack.
t - Pop the top item and get the item at that index in the stack. This pulls up the bottom item.
- - Subtract.
O - Output as an integer.
/ - Deflects the IP to the @, which ends the program.

Ruby, 23 bytes
->s{s[-1].ord-s[0].ord}

Assign to a variable like f=->s{s[-1].ord-s[0].ord} and call like f["Hello World!"]
Uses Dennis's observation about telescopic series.

You don't need to print the output, only return it, so you can get rid of $><<.

Yes, I read the question also. Luckily, there is broad consensus on the definition of "output" (see also: the many answers on this page which return rather than print a value). But hey, it's your code.

C#, 22 bytes
s=>s[s.Length-1]-s[0];

Full source code with test case:
using System;

namespace StringCumulativeSlope
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string,int>f= s=>s[s.Length-1]-s[0];
            Console.WriteLine(f("Hello World!"));
        }
    }
}

C# with LINQ, 17 bytes
A shorter version, using LINQ, thanks to hstde:
s=>s.Last()-s[0];

However, an extra import is necessary:
using System.Linq;

s=>s.Last()-s[0]; would be only 17 bytes

JavaScript ES6, 42 39 Bytes

f=
     s=>s[x='charCodeAt'](s.length-1)-s[x]();
;

console.log(f.toString().length);      // 39
console.log(f('Hello World!'))         // -39

Using @Dennis observation about telescope sums.
I think in this case the trivial solution is the shortest.
Saved 3 bytes by getting rid of th the charCodeAt repetition as suggested by @Neil.

Best I could do was s=>s.slice(-1).charCodeAt()-s.charCodeAt() which turns out to be the same length.

Actually charCodeAt is quite long, there's probably a way to save bytes by avoiding the repetition.

@Neil Thanks for the suggestion, that saved me 3 bytes.

A slightly recursive approach is a few bytes longer: f=s=>(s[1]?-f(s.slice(-1)):0)-s.charCodeAt()

reticular, 12 bytes
idVc~@qVc-o;

Try it online!
Using Dennis's observation, we can shorten an iterative process into a simpler one.
idVc~@qVc-o;
i             take input
 d            duplicate
  V           pop input copy, push last character
   c          get its char code
    ~         put it under the input in the stack
     @q       reverse the item at the top of the stack
       V      get the last item of that (first item of input)
        c     convert to char
         -    subtract
          o   output
           ;  and terminate

Brain-Flak, 51 bytes
48 bytes of code plus three bytes for the -a flag, which enables ASCII input (but decimal output. How convenient. :D)
{([{}]({})<>)<>}<>{}([]<>){({}[()])<>({}{})<>}<>

Try it online!
This ones a little bit harder than my other answer, haha. Lets walk through it.
{           While the top of the stack is nonzero:
 (            Push:
  [{}]          The top of the stack times negative one. Pop this off.
  ({})          Plus the value on top of the stack, which is duplicated to save for later.
  <>          On to the other stack
 )
 <>         Move back to the first stack
}
<>          After the loop, move back again.
{}          We have one extra element on the stack, so pop it
([]<>)      Push the height of the alternate stack back onto the first stack
{           While the top of the stack is nonzero:
 ({}[()])     Decrement this stack
 <>           Move back to the alternate stack
 ({}{})       Sum the top two elements
 <>           Move back tothe first stack
}
<>          Switch back to the stack holding the sum

05AB1E, 3 bytes
Ç¥O

Try it Online!
Uses CP-1252 encoding.
Explanation
Ç       Converts input string to ASCII
¥       Compute difference between successive elements
O       Sum the result

OK, cool. Sorry.

NodeJS, 82 bytes
x=process.argv[2],a=[],t=0;for(y in x)a[y]=x.charCodeAt(y),t+=y!=0?a[y]-a[y-1]:0

Explanation:
x = process.argv[2] // Get the input
a=[], // Initializes an array to store the differences' values.
t=0;  // Initializes a variable to store the total of the differences
for(y in x) // Iterates over the string as an array of characters
    a[y]=x.charCodeAt(y) // Transforms the input into an array of integers
    t+=y!=0?a[y]-a[y-1]:0 // Add the difference of the last two characters, except at the first iteration

JavaScript, 79 bytes
f=x=>{a=[],t=0;for(y in x)a[y]=x.charCodeAt(y),t+=y!=0?a[y]-a[y-1]:0;return t}

Same idea as above with a function input instead of an argument.

Sorry, but you can't assume x is the input. You need to actually get input.

Does that work this way ?

Yes, that works great!

Another acceptable way to get input is to create a function. For example f=x=>{...;return t} to save 2 bytes ;)

Brachylog, 7 bytes
@c$)@[-

Try it online!
Explanation
@c        Convert "Hello World!" to [72,101,108,108,111,32,87,111,114,108,100,33]
  $)      Circular permute right: [33,72,101,108,108,111,32,87,111,114,108,100]
    @[    Take a prefix of the list
      -   Subtract

Since subtract only works for an input of two integers, it will succeed once the selected prefix is [33, 72].

R, 69 43 32 bytes
A very non-competing answer although I thought it'd be fun to showcase a possible solution in R.
sum(diff(strtoi(sapply(strsplit(readline(),"")[[1]],charToRaw),16L)))

The only interesting aspect of this answer is the use of sapplyand charToRaw. First I split the string into a vector of characters that I want to convert into its ASCII integer representations. The charToRaw function is not vectorized in R and instead of looping over each value in aforementioned vector I use sapply which effectively vectorizes the function. Subsequently take 1st difference and then sum.

Edit: Turns out charToRaw transform a string into a vector where each element is the raw representation of each character, hence no need to use strsplit and sapply
sum(diff(strtoi(charToRaw(readline()),16)))

Edit2: Turns out there is an even better way, the function utf8ToInt(x) does exactly what strtoi(charToRaw(x),16) which means we can save a few more bytes (Idea taken from @rturnbull's answer to another question):
sum(diff(utf8ToInt(readline())))

Haskell, 32 bytes
g=fromEnum
f t=g(last t)-g(t!!0)

@nimi It's the same.

PHP 7.1, 33 31 bytes
Uses negative string offsets implemented in PHP 7.1.
echo ord($argn[-1])-ord($argn);

Run like this:
echo 'Hello World!' | php -nR 'echo ord($argn[-1])-ord($argn);';echo

Tweaks

Saved 2 bytes by using $argn

Perl, 19 bytes
Includes +1 for -p
Give input on STDIN without final newline
echo -n "Hello World!" | slope.pl; echo

slope.pl:
#!/usr/bin/perl -p
$_=-ord()+ord chop

If you are sure the input string has at least 2 characters this 17 byte version works too:
#!/usr/bin/perl -p
$_=ord(chop)-ord

Forth, 28 bytes
: f depth 1- roll swap - . ;

Takes a list of characters on the stack (Forth's standard method of taking parameters.) The characters are taken such that the top of the stack is the first character of the string. I move the bottom of the stack to the top, swap, then subtract and print. Garbage is left on the stack, and output is printed to stdout.
If each character were pushed to the stack in order instead of reverse order, the program would be 2 bytes shorter. Not sure if that's allowed, though, because normally you push arguments in reverse order.
Try it online
Called like this:
33 100 108 114 111 87 32 111 108 108 101 72 f

Java, 42
int f(char[]c){return c[c.length-1]-c[0];}

Ungolfed:
  int f(char[] c) {
    return c[c.length - 1] - c[0];
  }

Explanation:
This uses the same principle as telescoping:
sum =
  c[4] - c[3]
+        c[3] - c[2]
+               c[2] - c[1]
+                      c[1] - c[0]
= c[4]                      - c[0]

Generalized for any sequence of characters of length n, the answer is c[n-1] - c[0] because all the stuff in the middle cancels out.

RProgN, 142 Bytes, Non-competing
function tostack 'b' asoc stack 'a' asoc 0 'v' asoc b pop byte 'o' asoc b len while [ v o b pop byte ] 'o' asoc - + 'v' asoc b len end [ v end

Non-competing, as the 'tostack' command was added after the discovery of this challenge (even though it has a terrible byte count)
Test Cases
Hello, World!
-39

Cool, huh?
-4

Explanation
function                        # Push the function between this and end to the stack
    tostack 'b' asoc            # Convert the implicit input to a stack, associate it with 'b'
    0 'v' asoc                  # Push 0 to the stack, associate it with 'v'
    b pop byte 'o' asoc         # Pop the top value of b (The end of the input), get the byte value, associate it with 'o'.
    b len                       # Push the size of b to the stack
    while [                     # While the top of the stack is truthy, pop the top of the stack
        v                       # Push v to the stack
            o                   # Push o to the stack
            b pop byte          # Pop the top value of b, push the byte value of that to the stack
            ] 'o' asoc          # Push a copy of the top of the stack, associate it with 'o'
            -                   # Subtract the top of the stack from one underneith that, In this case, the old value of o and the byte.
        +                       # Sum the top of the stack and underneith that, that is, the difference of the old value and new, and the total value
        'v' asoc                # Associate it with 'v'
        b len                   # Push the size of b to the stack (which acts as the conditional for the next itteration)
    end [                       # Pop the top of the stack, which will likely be the left over size of b
    v                           # Push the value of v to the top of the stack
end                             # Implicitely returned / printed

RProgN is an esoteric language I've been working on with Reverse Polish Notation in mind. It's currently pretty verbose, with it's variable assignment being 4 characters, and such, however I plan to in future add a bit of syntatic sugar.
Also, RProgN implicitly accesses arguments from the stack, and returns them the same way. Any string data left in the stack after the program has finished, is implicitly printed.

"A bit of Sugar" really changed form in the few months this took. This entire thing is now ~{bid☼[+ and that's a bit adorable.

Haskell, 36 bytes
sum.(tail>>=zipWith(-)).map fromEnum

usage:
Prelude> (sum.(tail>>=zipWith(-)).map fromEnum)"Hello World!"
-39

Haskell (Lambdabot), 31 bytes
sum.(tail>>=zipWith(-)).map ord

I'm afraid this isn't a proper function. It's just a snippet. sum.(tail>>=zipWith(-)).map fromEnum for example is a function.

@nimi The question didn't ask for a proper function

The question asked for nothing, so the defaults jump in, which are full programs or functions, but not snippets.

PHP, 36 bytes
<?=ord(strrev($s=$argv[1]))-ord($s);

Every character but the first and the last are added and substracted once each.
→ sum of differences == difference between first and last character
ord() in PHP operates on the first character of a string
→ no need to explicitly reduce it to a single character

Brain-Flak, 34 32 + 3 = 35 bytes
+3 because of the -a flag required for ascii mode.
Try it online
(([][()]){[{}{}]({})([][()])}<>)

Strangely it is more efficient to actually use the definition used in the specs rather than the "trick" of subtracting first from last.
This works by doing exactly that.
(                           )  Push
 ([][()]){[{}]...([][()])}     While the stack has more than one item
  [{}]({})                     Subtract the top from a copy of the second
                          <>   Switch

CJam, 8 5 bytes
Big thanks to Dennis for two suggestions that removed 3 bytes
l)\c-

Try it online!
Explanation
Computes last value minus first value.
l        e# Read line as a string
 )       e# Push original string except last char, then last char
  \      e# Swap
   c     e# Convert to char: gives the first element of the string
    -    e# Subtract. Implicitly display

If you use ) instead of W=, you don't need the _. Also, c as a shortcut for 0=.

@Dennis Thanks a lot!

Haskell, 30 bytes
(-).x.last<*>x.head
x=fromEnum

Try it online!
Subtracts the ordinal value of the last character from the first one.

Zsh, 22 bytes
c=${1[-1]}
<<<$[#1-#c]

Try it online!
In arithmetic mode, #name gets the character code of the first character in name.
We set c to the last character, and take the difference between the first and last codes.

Seed, 4039 bytes
Doesn't seem to work on TIO, but it works when coupled with FBBI.
14 8414852681982816833433372790810698364813132893898716362540459584022688625798264387975418828592568753770315758610479370948681922136495546332842108359182479433966535765905179459065388440010157609978582001324769124099052737381611149373840917627724397208407089028643895012022628742573222012294052825237085324348444982290123104121122461666554733775475271788467486276475996175601885295303147702452726755226593471202120020410091199743017659208335573154423152801819978230729474715612051171341032334263365083856632777830962888838362419197925323841920453373876672857133617794914410360730116004434899654147180698957725800385129472017678272345459812820971385979547803648176092646145140068284050765640658811309016564056046407942182022651820035228362009982528504039804533767866420627382353719046483891910293375462106828387996245797761671261225013254207748981048605554765186147388853719963818083208243777244635745476307692488230092953697945832727395511335923455041158708566455516940361128710445734129517551071425980383868245384850414606859858328386070419359939079803074746512275418226197202836571384766956166619631171689844438573861785835116965466345655300077072895442275382922411155969198031415738356480027632734767683173461182290664943587642194391696717872166867654883153215102039820352237331385538370736495673578435286268786644516575547497324796824104315134626042330000705635177425450889072765711268672415205890660238315815153396544582388726425393852710118827047025185722269256146833775842006903080438150231695467021895363092529052520574194449676863598714517983262264357148485564703497878252076796987453939376614487678998151538038216932183036887648867146010916400020167219699363649810398529289241805610816901261682694481335373706251300527833925871180538483186233363575543039834652936143724765476480508305310882619200753413549214001157046401271519191156669194718305689324989237259136640434177325764364988116134945176126598820243998840443809752937520515344100617592630708925293861813249878688056870983944233809329996471811576900931997780578487934118491491633897231317094843722600453017152923803380210221974284736694358834261070630538144378201331181295164165912573101108878664104307565822507660429342648076645023021168927208404041863975881061432156693032967007545907712594685762148986214769140105389660472663019317931289961882347209090166368043206503779209112395539888113389407785335974662862517349671898791744588250308875572231759349870386015999899867730850506155358755663748614960022707399194198125201119524711715917827843321904976384404399309909866117302648386221353990707105795689319200425475186294089244622996442050731852097029817043141662937032584233928974737956370762054769055740438112740398572042024506348722650458410985546474473013737717240921600206923559721606463255613663371594880700597771926022187507689847687858240678832570285874435337075457716552831708888345356267662827783367565953777183820536859644451652595212270478985957060226344344006615328799484309837681549308387846900027966717655132797273586137694817492623636158543337389070780557382062590460928510862319381296648463287607060777913950944590945611345871683722732511843519102329506670894902511012732849359818448234315652916582556004294329878892425996281732479821424288647852769164824964729074599862314905063617436396577181901208863286669417671633028568895553965730176671535168886849416991134495839198428309058778632557423424054558897220151969306175456749531391645847260474651558039451142732356612220356880561099668248940964860594234916534549758712951241624081205523001565783316244873255420507329913573024484261568206576447347928383571365849256478051564364025715977517184173481323212119208578654500149740498811223293108994963782665818483798181705998628126622874671206108670316343107440206697310762264893261199201322114098489434319045842881613392743422024262546473060171303072727645787087619741180752610519691334159796822881314093039453830533166310770923481605656257998247400453809665413874039582375952009490304856930435790676573549004040517995168920956454944956745597460627149165715

-1917 bytes

@awi i will chip in another -58 bytes.

Vyxal s, 3 bytes
C¯N

Try it Online!
Charcodes, deltas, negate.

Thunno, \$4\log_{256}(96)\approx\$ 3.29 bytes
Oz[S

Attempt This Online!
Takes the challenge literally, as that's the shortest way.
Oz[S # Implicit input
O    # Ordinals
 z[  # Deltas
   S # Sum
     # Implicit output

APL (Dyalog Extended), 9 bytes
⊢/-⍥⎕UCS⊃

Try it online!
-13 thanks to @Adám
Explanation
    ⎕UCS     Codepoints of input
        ⊃    Last item
  -⍥         Minus
⊢/           First item

Old:
{                    }    Define a function
  (⍴⍵)                    Length of argument
       ⎕UCS⍵              Codepoints of input
 (    ⌷     )             Index in (1-indexed)
                          i.e. get the last item
             -            Minus
              1⌷          First item of
                ⎕UCS⍵     Codepoints of input

Doesn't ⊢/-⍥⎕UCS⊃ do the trick?

No you give it a name and call it as a function with the string as argument. This is a template I use to exclude the assignment from the byte count.

@Adám thanks. I'm still a bit new to APL.

@Adám I've looked through APL wiki and I'm still a bit unsure on how that's working. I've added an attempt at an explanation but it probably contains a lot of mistakes. Can you point out any corrections?

It is a fork: ⊢/(-⍥⎕UCS )⊃ subtracting - the first ⊃ from the last ⊢/ but preprocessing ⍥ both arguments to - using ⎕UCS.

… equivalent dfn.

@Adám thanks for your help!

Trilangle, 19 bytes
i2|<_!..>iL.,<@-\S/

Try it in the online interpreter!
Unfolds to this:
     i
    2 |
   < _ !
  . . > i
 L . , < @
- \ S / . .

Roughly equivalent to this C code:
#include <stdio.h>

int main() {
    // RED PATH
    int a, b;
    a = b = getchar();
    while (1) {
        int c = getchar();
        if (c == EOF) {
            // BLUE PATH
            printf("%d\n", b - a);
            return 0;
        } else {
            // GREEN PATH
            b = c;
        }
    }
}

Thunno 2 SB, 1 byte
Ṣ

Try it online!
Explanation
   # Implicit input
   # Convert to ordinals
Ṣ  # Take the deltas
   # Sum the list
   # Implicit output

Raku, 18 bytes
{[-] .ords[*-1,0]}

Try it online!
.ords returns a list of the ordinal values of the characters in the input string, [* - 1, 0] slices into it to return the last and first values, and [-] reduces that two-element list using subtraction.

Haskell, 61 bytes
import Data.Char
f s=sum$g$ord<$>s
g(a:b:r)=b-a:g(b:r)
g _=[]

Java 7, 100 96 bytes
int c(String s){char[]a=s.toCharArray();int r=0,i=a.length-1;for(;i>0;r+=a[i]-a[--i]);return r;}

Ungolfed & test code:
Try it here.
class M{
  static int c(String s){
    char[] a = s.toCharArray();
    int r = 0,
        i = a.length-1;
    for(; i > 0; r += a[i] - a[--i]);
    return r;
  }

  public static void main(String[] a){
    System.out.println(c("Hello World!"));
  }
}

Output: -39

PHP, 39 Bytes
<?=ord(substr($s=$argv[1],-1))-ord($s);

Clojure, 31 bytes
#(-(int(last %))(int(first %)))

Someone reduced the task already to a single operation.

Mathematica, 30 bytes
Tr@Differences@ToCharacterCode

Befunge-93, 16 bytes
~:v_$-.@
~\<^`0:

Befunge-98, 14 bytes
~v >-.@
\>#^~

Reads (~) the first character, and then loops reading (~) a character and swaping (\) the top 2 items in the stack (so the first character keeps being raised to the top of the stack) until EOF, then substracts (-) the top 2 items, outputs (.) the result and ends (@).

C, 69 bytes
main(i,e,z){while(EOF!=(i =getc(stdin))){z+=e-i;e=i;}putc(z,stdout);}

Useless whitespace at i =getc.

Pyth (fork), 5 bytes
s.+CM

Does not work on the online interpreter, as current online interpreters are based only on the main repo.
Explanation:
   CM  Map ordinals over input
 .+    Deltas, calculates differences between consecutive numbers
s      Sums the result

Haskell, 27 bytes
\x->(ord.last)x-(ord.head)x

Unfortunately, Haskell has no knowledge of character codes until you import Data.Char. Fortunately, Haskell already treats strings as character arrays.
\x->                             --Syntax for anonymous function of 'x'
    (ord                         --Character code of...
        .last)                     --last element in the array
              x                  --Apply to argument
               -
                (ord             --Character code of...
                    .head)         --first element in the array
                          x      --Apply to argument

Don't you have to import ord?

Pyke, 5 bytes
m.o$s

Try it here!
m.o   -   map(ord, input)
   $  -  delta(^)
    s - sum(^)

Racket 121 bytes
(λ(s)(let((l(map char->integer(string->list s))))(for/sum((i(range 1(length l))))(-(list-ref l i)(list-ref l(- i 1))))))

Ungolfed version
(define f
  (λ(s)
    (let ((l (map char->integer
                   (string->list s))))
      (for/sum ((i (range 1 (length l))))
        (- (list-ref l i)
           (list-ref l (- i 1)))))))

Testing
(f "Hello World!")

-39

Groovy (80 Bytes)
f={n->s=[];n.eachWithIndex{x,i->s<<(i+1<n.size()?(int)n[i+1]-(int)x:0)};s.sum()}

C# .NET, 156 bytes
public class P{public static void Main(string[]a){int q=0;for(int i=0;i<a[0].Length;i++){q+=i!=a[0].Length-1?a[0][i+1]-a[0][i]:0;}System.Console.Write(q);}}

Try online

brainfuck, 31 bytes
Probably easy to outgolf, any ideas about this code will be appreciated.
>+[>,>,[-<->]<]<<[>[-<+>]<<]>-.

Try it online!

How does this print negative numbers? Also, I don't think this works?

Jelly, 3 bytes
OIS

Try it online!
A monadic link, I think.
Charcodes, deltas, sum.

Factor, 25 bytes
[ dup last swap first - ]

Try it online!

JavaScript, 36 bytes
s=>s.at(-1)[x='charCodeAt']()-s[x]()

Try it:

f=s=>s.at(-1)[x='charCodeAt']()-s[x]()

input.addEventListener('input', e => result.innerHTML = f(input.value))
result.innerHTML = f(input.value)
<input id="input" value="Hello world!"/>
<div id="result"></div>

J, 12 bytes
1#.2-~/\3&u:

Attempt This Online!
1#.2-~/\3&u:
        3&u:  NB. convert to codepoints
   2   \      NB. for each consecutive pair
    -~/       NB. minus reduce the first from the second
1#.           NB. sum reduce

Alternative 12 bytes
3({:-{.)@u:]

Attempt This Online!
3({:-{.)@u:]
3        u:]   NB. convert input to codepoints
        @      NB. then
 ({:-{.)       NB. monadic fork
     {.        NB. head
  {:           NB. tail
    -          NB. subtract

C (gcc), 64 bytes
Takes input from command line: ./a.out "<input>"
main(c,v)char**v;{for(v++;1[*v];)c-=**v-*++*v;printf("%d",c-2);}

Try it online!


text:
Number Triangles
Credit
My thanks to Rand Al'Thor's letter-based question for the inspiration for this code-golf challenge.
Background
The nature of this challenge is based off the algorithm mentioned by Rand in his "A Triangle Formed of Three Letters":

Start with a sequence of 10 letters each of which is X, Y, or Z.
Under each row, construct the next row as follows. If two adjacent letters are the same, write the same letter beneath them; if they're different, write the third letter beneath them.

You would then repeat the previous step until you have one letter in your tenth row.
Challenge
We're going to put a mathematical spin on the above algorithm:

Let's start with a sequences of 10 digits, each separated by a space, and each of which is either 1, 2 or 3.
Under each row, construct the next row as follows. If two adjacent digits are the same, write the same digit beneath them; if they're different, write the third digit beneath them.
Repeat the previous step until you have one final number.

So, following this algorithm, if starting with the row 1 2 3 3 1 3 1 3 1 2, for example, the following triangle is generated:
Input: 1 2 3 3 1 3 1 3 1 2

Output:

1 2 3 3 1 3 1 3 1 2
 3 1 3 2 2 2 2 2 3
  2 2 1 2 2 2 2 1
   2 3 3 2 2 2 3
    1 3 1 2 2 1
     2 2 3 2 3
      2 1 1 1
       3 1 1
        2 1
         3

I'm also curious to know the sum of all the digits in the number triangle, so add all these digits, and put this total in an eleventh row, right-justified to the last digit in the first row. So, our number triangle will look something like the following (spaces in my example are represented below by the . character to show formatting.)
Input: 1 2 3 3 1 3 1 3 1 2

Output:

1.2.3.3.1.3.1.3.1.2
.3.1.3.2.2.2.2.2.3.
..2.2.1.2.2.2.2.1..
...2.3.3.2.2.2.3...
....1.3.1.2.2.1....
.....2.2.3.2.3.....
......2.1.1.1......
.......3.1.1.......
........2.1........
.........3.........
................109

Your challenge is to write code that can start with an inputted string/array/etc. of ten digits, as per my example, and then apply the algorithm to generate the ten rows that would create the number triangle, followed by an 11th row that would display the total of all digits with right-justification.
Testing
Testing of this string can be performed with a randomly generated string of ten digits of your choosing, or one generated from the snippet below...

c1=()=>('1331123221'+(Math.random()*(1<<24)|0).toString(4)).replace(/0/g, "").slice(-10).split("").join(" ");

$("#btn").click(function(){
  $("#str").val(c1());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="str"><button id="btn">Get numbers</button>
<br>
Please use this snippet to generate a starting row for testing your code. Alternatively, you can also use a string of your choice, so long as it's ten digits (ranging from 1 to 3), separated by single spaces.

Rules

Code-golf rules apply, so lowest number of bytes wins the challenge. In the event that there are two entries with the same low score, the winner will be awarded based on the number of up-votes.
What we're basically after is 11 rows, 19 characters long... How you render your final output is entirely up to you: array, console, file output, STDOUT, etc., so please use whatever output method you like that will work to your advantage. The only rule in the output is that we have 11 rows with 19 characters in each row in a similar format to above...
If it helps your code, use whatever separator for the digits... Just remember that legibility may be a contributing factor.
No silly loopholes.
Hard-coding of the input is not allowed. The purposes of this code is such that it can be used to produce different results each time with varying input. Hard-coding of 1 1 1 1 1 1 1 1 1 1 for example, completely negates the whole point of the algorithm.

Look forward to seeing what you all can come up with!

Sorta related

@DJMcMayhem Not related, the triangle in your referenced question has differences used to populating the next row. There's nothing like that in this question. The next row is populated through two specifc rules (A: if the two parents are the same, the child is the same; and B: if the two parents are different, the child is the third from the set)

Do I need a separator if my triangle is center-aligned (which is thus legible)?

@JHM... It sounds like in your case it may be optional... Let's take a look

It looks like this without the space (my answer has space, which takes 10 bytes).

So is it okay if I remove the spaces?

Permission granted

Note that for a string of 10 (or any number 1 greater than a power of 3) digits, the final digit is trivially calculated from the first and last digit in the string; the other digits make no difference.

05AB1E, 32 26 bytes
DvÐOˆðýðN×.ø,ü+3%3^}\¯O19j

Explanation
D                 # duplicate input
v                 # for y,N in input,len(input): (10 times do)
 Ð                # triplicate current list
 Oˆ               # sum one copy and add it to global array
 ðý               # merge one copy on spaces
   ðN×.ø          # surround it with N spaces
        ,         # and print it
 ü+               # reduce one copy by addition
   3%             # modulus 3
     3^           # XOR 3
                  # this is the list sent to the next iteration
}                 # end loop
\                 # drop empty list left over from last iteration of loop
 ¯O               # sum the global array giving the triangles total sum
   19j            # join with spaces up to 19 chars

Try it online!

Mathematica, 104 97 90 94 bytes
{Grid[List@*Row/@#],#~Total~2}~Column~Right&[NestList[3-Mod[+##,3]&@@@Partition[#,2,1]&,#,9]]&

Explanation
Partition[#,2,1]

Partitions the input into length 2, offset 1 partitions.
3-Mod[+##,3]&@@@

Takes each partition, and calculates the corresponding output.
A trick involved here. I added up the two numbers, took mod 3, and subtracted that result from 3. That gives the desired number. (e.g. 3 - ((2 + 1) mod 3) = 3)
NestList[ ... ,9]

Repeats the above process nine times, giving all iterations as the output.
Grid[List@*Row/@#]

Format each iteration into rows, and put the entire thing in one column (center aligned), creating a triangle.
#~Total~2

Take the total of all numbers.
{...}~Column~Right

Combine the triangle and the total, and right align the entire thing (triangle is already aligned, so its alignment is not affected).

Inspired approach with a single function that takes care of both the identical and different parent types... I like it!

JavaScript (ES6), 143 142 bytes
Saved 1 byte thanks to @Neil
a=>a.map((_,i)=>(q=" ".repeat(i))+(a=a.map(c=>(x+=r=i&&p^(p=c)||c,r),p=i&&a.shift())).join` `+q,x=0).join`
`+`
`+(" ".repeat(18)+x).slice(-19)

I tried combining various parts, but it ended up 5 bytes longer:
a=>[...a.map((_,i)=>(a=a.map(c=>(x+=r=i&&p^(p=c)||c,r),p=i&&a.shift())).join` `+" ".repeat(i),x=0),x].map(q=>(" ".repeat(18)+q).slice(-19)).join`
`

Great work! Could JHM's trick of 3-((x+y)%3) be of any help reducing this code?

Nope. p^c||p is already quite a bit shorter :-)

Now, how the hell did I miss that? Of course! XOR functions work well here!

XOR?! I couldn't have thought of that. That being said, sadly, using XOR makes my code longer :P

For i?p^(p=c)||p:c can you use i&&p^(p=c)||c?

@Neil Thanks, I think that will work!

Ruby, 134 101 bytes
Using JHM's modulo trick.
->a{b=*a
(0..8).map{|i|[" "*i,a=a.each_cons(2).map{|x,y|b<<n=3-(x+y)%3
n}]*" "}<<"%19d"%b.reduce(:+)}

See it on eval.in: https://eval.in/649993

CJam,  44  40 bytes
l~{S*\_S*\2ew{:+3%3^}%2$N@}A%_s:~:+sJSe[

Try it online!
Explanation
l~       e# Read and evaluate input.
{        e# Map this block over i in the range [0 1 ... 9].
  S*     e#   Get a string of i spaces (the indentation).
  \_     e#   Swap with the current line of trits and duplicate it.
  S*     e#   Join the trits with spaces.
  \2ew   e#   Swap with the other copy of the trits and get all consecutive pairs.
  {      e#   Map this block over the pairs...
    :+   e#     Sum the pair.
    3%   e#     Modulo 3.
    3^   e#     XOR 3.
         e#     This expression (x+y)%3 ^ 3 computes the required mapping.
  }%     e#   Now this is the next line.
  2$     e#   Copy the indentation (to pad the lines to equal length).
  N      e#   Push a linefeed.
  @      e#   Pull up the next line.
}A%      e# The result of this is a nested array whose string representation is
         e# the required triangle.
_s       e# Duplicate and flatten into a string.
:~       e# Eval each character which gives a list of all the trits.
:+       e# Sum that.
s        e# Turn the sum into a string.
JSe[     e# Left-pad it with spaces to width 19.

As always, very impressive! You're in the lead so far!

@WallyWest Thanks. :) Just wait Pyth, Jelly and MATL. ;)

Actually, I'm curious to know what the GolfScript solution will look like... ;)

Oh, anyone up to posting an SQL solution? ;)

JavaScript (ES6), 112 100 96 bytes
Takes an array as input and recursively builds a comma-separated triangle.

f=(s,p=`
`,S=0)=>p+(s[0]?s+f(s.map((v,i)=>(S+=v,v^s[i-1]||v)).slice(1),p+' ',S):(p+S).slice(-9))

console.log(f([1,2,3,3,1,3,1,3,1,2])); // reference example
console.log(f([3,3,2,1,3,1,2,1,2,1])); // random example
console.log(f([1,1,1,1,1,1,1,1,1,1])); // all ones (test case for sum < 100)

Python 2, 164 bytes
A relatively simple iterative solution.
L=input()
s=0
for i in range(len(L)):
    print" "*-~i+" ".join(`L`[1::3]);s+=sum(L);N=L;L=[]
    for a,b in zip(N,N[1:]):L+=[list({1,2,3}-{a,b}),[a]][a==b]
print"%19s"%s

Try it online

PHP, 143 Bytes
<?for($t=$_GET[t];$i<181;$s+=$v,$i+=2)$t[$i+20]=($v=$t[$i])*($z=$t[$i+2])>0&$i!=18?($v+$z)%3^3:" ";echo chunk_split($t.str_pad($s,8," ",0),19);

source: Stack Exchange

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

sort: votes


text:
Progruzzle & Colf
Ever fancied creating cool twitter hashtags such as #brexit or #brangelina? this golf is for you.

Write a program that accepts two strings A & B as input and merges them according to the following algorithm:

let n be the number of vowels groups in A (e.g. britain has 2 vowels groups : i in position 3 and ai in position 5).

if n = 1 : truncate A starting at its first vowel group position (example: bill => b)
if n > 1 : truncate A starting at its n-1th vowel group position (example: programming => progr, britain => br)

remove all consonants at the beginning of B (jennifer =>
ennifer)
concatenate the modified A & B

Vowels are aeiou; consonants are bcdfghjklmnpqrstvwxyz.
Input
You can assume the input strings are lowercase and contain at least one vowel and one consonant.
Examples
brad + angelina      => brangelina
britain + exit       => brexit
ben + jennifer       => bennifer
brangelina + exit    => brangelexit
bill + hillary       => billary
angelina + brad      => angelad
programming + puzzle => progruzzle
code + golf          => colf
out + go             => o

New test case? donald trump.

These are essentially portmanteaus.

Related

@ETHproductions this seems to produce much different combinations, such as Django + Angular = Djular

What's "n-1th vowel group position"

@l4m2 Simple, the vowel group at the n-1th position. I'm not sure how to explain this better... how about this, it's the second to last vowel group.

@LyricLy Why br[itain while brangel[ina

@l4m2 in britain there are 2 vowels groups (i and ai), so you cut at the first one; in brangelina, there are 4 vowels groups (a, e, i, a) so you cut at the third one.

well so that's "remove the last two"

I've got a friend named Brittany Elizabeth ..., guess I'll call her brelizabeth! Edit: she does not appreciate such operation... exiting.

Ruby, 44 43 40 + 1 = 41 bytes
+1 byte for -p flag. Takes space-separated input on STDIN.
-1 byte thanks to Martin Ender
-2 bytes thanks to histocrat
sub /([aeiou]+([^aeiou]*)){,2} \g<2>/,""

Try it online!
GNU sed, 39 37 + 1 = 38 bytes
+1 byte for -E flag. Takes space-separated input on STDIN.
-1 byte thanks to Martin Ender
s/([aeiou]+[^aeiou]*){,2} [^aeiou]*//

Try it online!
Not posting this as a separate answer because it is literally the same solution.

Nice regex! Mind if I use part of it in my JS answer?

Sure, go crazy.

You can golf the regex a bit more by capturing the [^aeiou] as a subexpression: /([aeiou]+([^aeiou]*)){,2} \g<2>/

@histocrat Thanks! I forgot you can do that with numbered groups (i.e. you don't need to name the group).

Crossed out 44 is still regular 44 ;(

Does the p flag essentially add ARGV.join(" "). to the beginning of the code?

@QPaysTaxes No, it doesn't do anything with ARGV. Per man ruby, the -n flag "Causes Ruby to assume the following loop around your script, which makes it iterate over file name arguments somewhat like sed -n or awk. while gets; ... end," and the -p flag "Acts mostly same as -n switch, but print the value of variable $_ at the each end of the loop." Here's a good blog post on the topic: https://robm.me.uk/ruby/2013/11/20/ruby-enp.html

I did, I just misread the last bit. Hence why I deleted my comment. Thanks for the response! (Also, I just looked up how that works -- Kernel#sub operates on $_, which was what I was trying to figure out)

Doesn't -p add 3 characters—the space after the command itself, the - and the p? Do we have some sort of ruling on how flags needed to run the thing are counted?

@Anko See "Special invocations" in this answer. TL;DR: Only count bytes in addition to the default invocation. The default invocation for Ruby is ruby -e "...". For this it's ruby -pe "...", so it only adds one byte.

MATL, 31 30 bytes
t13Y2XJmFwhdl=fql_):)itJmYsg)h

Try it Online
Explanation
t       % Implicitly grab the input and duplicate it
13Y2    % Push the string literal 'aeiouAEIOU'
XJ      % Store this in clipboard J for later use
m       % Check which characters from the input are vowels (true for vowel)
Fwh     % Prepend FALSE to this logical array
dl=     % Compute the difference and find where we went from not-vowel to vowel
f       % Find the indices of these transitions
q       % Subtract 1 to get the location of the last consonant in each transition
l_)     % Get the next-to-last one of these
:)      % Grab the first string up to this location

% Now for the second component!

it      % Explicitly grab the input and duplicate
J       % Retrieve the string literal 'aeiouAEIOU' from clipboard J
m       % Find where the vowels are (true for vowel)
Ys      % Compute the cumulative sum along the array. The result will be 0
        % for all characters before the first vowel and non-zero after
g)      % Convert to logical and use this as an index so any characters
        % after the first value are retrieved

% Now to combine them

h       % Horizontally concatenate the first and second pieces together
        % Implicitly display the result

I always upvote happy code

JavaScript (ES6), 81 73 72 bytes
Saved 8 bytes thanks to @Jordan, 1 thanks to @DavidConrad
a=>b=>a.match(/.*?(?=(?:[aeiou]+[^aeiou]*){1,2}$)/)+b.match(/[aeiou].*/)

Even though .match returns an array, array+array returns a string with the contents of the arrays concatenated (i.e. [0]+[1] returns "01").
Test snippet

f=a=>b=>console.log(a,"+",b,"=",a.match(/.*?(?=(?:[aeiou]+[^aeiou]*){1,2}$)/)+b.match(/[aeiou].*/))
f("brad")("angelina")
f("britain")("exit")
f("ben")("jennifer")
f("brangelina")("exit")
f("bill")("hillary")
f("angelina")("brad")
f("programming")("puzzle")
f("code")("golf")
f("progruzzle")("colf")
f("out")("go")
<input id=A value="super">
<input id=B value="chafouin">
<button onclick="f(A.value)(B.value)">Run</button>

Jordan's excellent Ruby solution would be 53 bytes in JS:
x=>x.replace(/([aeiou]+[^aeiou]*){1,2} [^aeiou]*/,"")

Maybe could just throw out the match bit and use a replace?

@ConorO'Brien That kinda feels like stealing Jordan's answer :/

You quite literally read my mind. And yeah, that's true

Currying (a,b)=> to a=>b=> saves 1 byte.

Jelly, 23 22 bytes
e€ØcT
Çµḟ‘-ị’
Ç⁸ḣ⁹ÑḢ⁹ṫ

TryItOnline
How?
e€ØcT    - Link 1, vowel indexes: s   e.g. "colouring"
  Øc     - yield vowels, "AEIOUaeiou"
e€       - in for each                     [0,1,0,1,1,0,1,0,0]
    T    - truthy indexes (1-based)        [2,4,5,7]

Çµḟ‘-ị’  - Link 2, n-1th or only vowel group index start - 1: s
 µ       - monadic chain separation
Ç        - call last link (1) as a monad   [2,4,5,7]
   ‘     - increment                       [3,5,6,8]
  ḟ      - filter out                      [2,4,7]
    -    - -1
     ị   - index value                     [4]
               (Jelly is 1-based and has modular indexing,
                so the last but one item is at index -1,
                and when there is only 1 item in the list it is also at index -1)
      ’  - decrement                       [3]

Ç⁸ḣ⁹ÑḢ⁹ṫ - Main link: a, b                      e.g. "colouring", "pencils"
Ç        - call last link (2) as a monad with a      [3]
 ⁸       - link's left argument, a
  ḣ      - head a[:y]                                "col"
   ⁹  ⁹  - link's right argument, b
    Ñ    - call next link (1) as a monad                          [2,5]
     Ḣ   - pop head                                               [2]
       ṫ - tail b[y-1:]                                           "encils"
         - implicit print                            "colencils"

Beautifully explained!

PowerShell v2+, 76 bytes
param($n,$m)($n-replace'([aeiou]+[^aeiou]*){1,2}$')+($m-replace'^[^aeiou]*')

Apparently this is a popular regex ... ;-)
Uses the -replace operator to pull off the appropriate pieces, then string-concatenates the results together. Adds on a $ to the first to ensure we pull the end of the string, and adds a ^ to the second to ensure we pull off the front of the string.

Retina, 35 bytes
([aeiou]+[^aeiou]*){1,2} [^aeiou]*

Try it online! (The first line enables a linefeed-separated test suite.)
Simply removes all matches of the regex on the first line.

Any plans to add vowel and non-vowel classes? ;-)

@ETHproductions If I can ever be bothered to implement my own regex flavour (or at least tokenise it so that it can be transpiled to .NET regex), sure! :P

Ruby can do pattern backreferences (same pattern that can match a different sequence of characters). These would be useful here. For example, matching parentheses are matched by /^((\(\g<1>\))*)$/ in Ruby.

@JanDvorak Too bad Retina is written in .NET, huh? ;) I did consider bundling it with https://github.com/ltrzesniewski/pcre-net so that you can switch flavours, but didn't get around to that yet, and some other features are increasingly relying on .NET-specific match behaviour.

Time to drop the .net specific behavior and rewrite everything in Ruby? Ruby is better anyways :-)

@JanDvorak And give up balancing groups? No way. :P I guess one day I'll have to write my own flavour that can do both balancing groups and pattern reuse. ;)

Cinnamon Gum, 23 bytes
0000000: 64d3 884e 4ccd cc2f 8dd5 8e8e 8330 b434  d..NL../.....0.4
0000010: b108 d92b c0d9 00                        ...+...

Try it online.
Explanation
This decompresses to d([aeiou]+[^aeiou]*)([aeiou]+[^aeiou]*)? [^aeiou]*, which deletes anything matching that regex. (Note that Jordan's golfier d([aeiou]+[^aeiou]*){,2} [^aeiou]* compresses to 24 bytes due to the lack of repeated elements to compress.)

Would d[aeiou]+[^aeiou]*[aeiou]*[^aeiou]* [^aeiou]* be any shorter?

@ETHproductions I tried that, it was the same byte count :(

PHP, 95 Bytes
$t="aeiou]";echo($p=preg_filter)("#([$t+[^$t*){1,2}$#","",$argv[1]).$p("#^[^$t*#","",$argv[2]);

with preg_match instead of preg_filter 110 Bytes
$t="aeiou]";($p=preg_match)("#(.*?)([$t+[^$t*){1,2}$#",$argv[1],$m);$p("#[$t.*#",$argv[2],$n);echo$m[1].$n[0];

You can use + instead of {1,2}.

@Titus more important was to eliminate the bug for 1 case and now I can try to golf it down

Use $v=aeiou; to save 3 more.

@Titus I had the same idea but with a little variant. Thank You

Lua, 66 bytes
$ cat merge.lua
print(((...):gsub(("[]+[^]*[]*[^]*+[^]*"):gsub("]","aeiou]"),"")))
$ lua merge.lua brad+angelina
brangelina
$ lua merge.lua programming+puzzle
progruzzle

Perl 5, 39 bytes
38, plus 1 for -pe instead of -e
s/([aeiou]+[^aeiou]*){1,2} [^aeiou]*//

Hat tip.

Same as the sed answer linked to within, but we may as well have it in Perl also.

Python 2, 139 bytes
n=lambda a,b:a[:a.index(([l for l in[[l,"!"][i!=0and a[i-1]in v]for i,l in enumerate(a)]if l in v]*2)[-2])]+b[sorted([(b+v).index(c)for c in v])[0]:]

This one was hard.
Check it out on repl.it

Lithp, 65 bytes
#X::((replace X (regex "([aeiou]+[^aeiou]*){1,2} [^aeiou]*") ""))

This is basically a port of the JavaScript answer above, in my Lisp-ish functional programming language.
Example usage:
(
    % Note, you can define this as a function, or assign it to a variable
    % and use the call function instead.
    (def f #X::((replace X (regex "([aeiou]+[^aeiou]*){1,2} [^aeiou]*") "")))
    (print (f "programming puzzle"))
)

No online interpreter yet. I'll provide one soon. It won't be difficult, my language is written in JavaScript.
Instead, this puzzle solution is implemented as a working example for my language. It can be run with the following command:
node run.js l_src/progruzzle-colf.lithp

Haskell, 111 108 bytes
v x=elem x"aeiou"
d=dropWhile
e=d v
k=d$not.v
r=reverse
f a|c<-e.k.e.k$a,""/=c=c|1<3=e.k$a
a!b=(r.f.r)a++k b

This non-regex solution turned out longer than expected. Ideone it anyway.

Jq 1.5, 45 bytes
gsub("([aeiou]+[^aeiou]*){1,2} [^aeiou]*";"")

Nothing special, just a port of msh210's perl solution to jq's PCRE.
Try it online!

Japt, 18 bytes
r/\v+\V*){1,2} \V*

Try it online!
Direct port of short JS solution which is in turn the port of Jordan's Ruby solution.
How it works
Ur/\v+\V*){1,2} \V*/

Ur    Replace on the input...
/\v+\V*){1,2} \V*/  this regex with empty string.
      \v == [AEIOUaeiou], \V == [^AEIOUaeiou], `g` flag is on by default in Japt
      so the uncompressed regex is roughly /([aeiou]+[^aeiou]*){1,2} [^aeiou]*/g.

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

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


text:
Build a nest
The challenge is simple: write a program or function that, when given a finite non-negative integer, outputs a nested array.
The rules

Your code must produce a unique valid nested array for every integer 0 ≤ n < 231.
Every possible nested array with up to 16 open brackets must be outputted within this range. (This does not mean that your code can never output a nested array with more than 16 open brackets.)
Your code may output a string representation of the nested array instead of an actual array (with or without commas).

One possible mapping:
0 -> []
1 -> [[]]
2 -> [[[]]]
3 -> [[], []]
4 -> [[[[]]]]
5 -> [[[], []]]
6 -> [[[]], []]
7 -> [[], [[]]]
8 -> [[], [], []]
9 -> [[[[[]]]]]
etc.

Scoring
This is code-golf, so the shortest code in bytes wins.

Are there any time/memory restrictions?

@Dennis Does 1 hour seem reasonable for a time restriction? I have no clue what's reasonable for memory.

Memory isn't a big deal if there's a time limit. One hour seems very generous. I wouldn't want to wait a full hour to verify if my code is fast enough.

@Dennis How about 1 minute, then? 5 minutes? 10?

5 minutes seems a good spot between slow languages can't compete and I have to wait forever to test if my code is fast enough. Do you have a reference implementation? The naïve approach takes one minute for input 3000 in Jelly.

I'd prefer no time restrictions. That gives more scope for originality

Perl likes strings as input and output. So can I output the list members as a single string, e.g.[],[] or even without separator [][]

Related: http://codegolf.stackexchange.com/questions/66127/catalan-numbers

I'm not sure I understand. are there other valid outputs? could it go 2: [[]], 3:[[[]]], 4:[[[[]]]], 5[[[[[]]]]], etc?

@TonHospel You may output without commas. I guess no time restrictions would be fine, as long as you can prove that your entry is valid.

@tuskiomi As long as every possible array with up to 16 open-brackets is outputted within 0 ≤ n < 2^31, and the output for every integer within this range is unique and a valid array, the program is valid. I don't believe your example is valid because (at least from what I can see) it will never output [[][]] or anything like that. See the existing answers for examples of other valid outputs.

Am I right in saying that there are 2^14 possible lists with 16 opening brackets?

@Myridium The number of possible lists with n opening brackets is the n-1'th Catalan number. There are 9694845 possible lists with 16 opening brackets.

Python, 153 128 bytes
s=l=0;r="";n=input()
for d in bin(n)[2:]*(n>0):c=d<"1";l=[l,s>1][c];r+="]"*c+(1-l*c)*"[";s+=1-c-l*c
print"["+r+"["*l+"]"*(s+l+1)

We map a number n to a nested list by looking at its binary digits left-to-right. This algorithm works for any number, not just under 232.

If the current binary digit is an 1, output [.
Otherwise, if the sequence of brackets we've output so far would get balanced by a single closing bracket, output ][.
Otherwise, if this is the last 0 in the binary number, output ][.
Otherwise output ].

Finally, we close any opened brackets.

Python 2.7, 172 149 124 118 bytes
x=input();y="";z=0
for b in bin(x)[2+(x<1):]:y+="[]"[b<"1"];z+=b>"0"or-1;z+=99*(z<0)
print"["+(y,"[]"*(x+16))[z>0]+"]"

Explanation:
Define a bijection by [↔1 and ]↔0. Any arrangement of brackets can then be written as a binary number and vice versa, for instance [][]↔1010(10) and [[][]]↔110100(52). All valid arrangements of up to 15 open brackets (30 brackets in total) are covered by numbers with up to 30 bits (ignoring leading zeros), which are precisely the numbers less than 231.
The first for-loop gives the inverse of this bijection, converting a number to an arrangement of brackets, while checking that the arrangement is valid.
Invalid arrangements are replaced within the print statement by long sequences of brackets to avoid collisions. For instance 11(3)↔[[ is not valid so we concatenate 3+16 brackets instead. This ensures all arrangements are unique.
The resultant arrangement is placed within a pair of brackets to make a nested array, so that 1010(10) becomes [[][]] and 110100(52) becomes [[[][]]]. The extra open bracket means we've now covered all arrays with 16 open brackets.

The following program can be used to figure out the number for a given array with up to 16 brackets.
s=raw_input();o="";
for c in s[1:-1]:
 if c=="[":o+="1"
 if c=="]":o+="0"
print int(o,2)

A nice abuse of the op's intent when he specified "unique"

That's just genius. Well done. (And a comma-less format is allowed.)

Perl, 80 79 bytes
Again uses orlp's algorithm, but this time I first checked if it works...
Includes +1 for -p
Give input number on STDIN
nest.pl <<< 8

nest.pl:
#!/usr/bin/perl -p
($_=sprintf"%b",$_).=2x(s^.^$&or++$n-pos&&/.0/g?++$n%1:$`&&21^eg-$n);y;102;();

Linus's solution is 64 bytes in perl:
#!/usr/bin/perl -p
$_=sprintf"%b",/.+/g;$_=10x($&&&$&+16)if!/^(1(?1)*0)+$/;y;10;()

Dennis's solution is 59 bytes in perl (increasingly slower for large numbers):
#!/usr/bin/perl -p
1while$_-=(sprintf"%b",$n++)=~/^(1(?1)*0)+$/;$_=$&;y;10;()

I feel like you should just score this as 65 bytes, (isn't it 64 actually)?

@Linus While your rules dodge is brilliant and deserves all its upvotes, I do consider it bit of a cheat. For scoring the -p is counted as 1 extra byte

Spoon, 63 bytes (501 bits)
000001001001001011001101001010011011111001010001000000101010
101101100110100101101001000101100010001000000100011000010000
000000000000001110111110010000001110110110010100100100100100
000110011010001000000110110000010000001010110011011011011001
000000011010010010010001000000111011011011101001001001000110
110110010100100101011001000100000011010001000000111011011001
010010010010010001101101101001000110110010110001101101101101
100100010001010010001010011011001000000011001101001001010010
000001100101001000111

This is the following brainfuck program converted to spoon:
-[+[+<]>>+]<+++.[->+>+<<]>>++>>,[>-[<->-----]+<+++[-<+<<.>>>>-<]>[-<<-[->+<]<<<[-]>>>>[-<+<<<+>>>>]<<.>>+<[>-]>[-<+<<.>>>>]<<>>]<,]<<<<[>.>.<<[-]]>>>+[-<.>]+

Reads an integer in binary on stdin, and outputs the nested list on stdin. Requires 0 to be input as the empty string (no digits), and requires a brainfuck interpreter with 8-bit cells. Same algorithm as my Python answer.
Readable version:
-[+[+<]>>+]<+++.           push open bracket and print it
[->+>+<<]                  dup
>>++                       increment to close bracket

>>,[                       read input loop
    >-[<->-----]+<+++          subtract 48 and set up if/else
    [-                         if c == 1
        <+                         increment s
        <<.>>>                     output open bracket
    >-<]>[-<                   else
        <-[->+<]                   decrement and move s
        <<<[-]                     zero l
        >>>>[-<+<<<+>>>>]          l = s and restore s
        <<.>                       output close bracket
        >+<[>-]>[-                 if s == 0
            <+                         undo s decrement
            <<.                        output open bracket
        >>>>]<<
    >>]<
,]

<<<<[                      if l
    >.>.                   output pair
<<[-]]
>>>+[-<.>]                 output close bracket s+1 times

We've recently had this discussion on another answer, and there seems to be no actual intrepreter that is able to handle a 63-byte file. The reference implementation used the bytes 0x30 and 0x31, so this answer would require a 501 byte file.

Jelly, 28 bytes
ḃ2-*µSN;+\>-Ạ
1Ç#Ṫḃ2ṭ2;1ị⁾][

This iterates over all strings of the characters [ and ] that start with a [ and end with a ], verifies if the brackets match, and prints the nth match.
Try it online!

Python 3, 120 114 bytes
def f(n,k=0):
 while~n:
  k+=1
  try:r=eval(bin(k).translate({48:'],',49:'['})[3:-1])+[];n-=1
  except:0
 print(r)

Test it on Ideone.
How it works
The defined function f takes input n and initializes k to 0. We'll keep incrementing k until n + 1 values of k result in a valid output. Every time we find such a value of k, n is decremented once it reaches -1, ~n yields 0, and the list r that corresponds to the last value of k is printed.
The partial mapping from the positive integers to nested lists (i.e., k ↦ r) has to be bijective, but there are no other constraints. The one used in this answer operates as follows.

Convert k to a binary string representation, staring with 0b.
For example, 44 ↦ "0b101100".
Replace all 0's (code point 48) in the string representation with the string "]," and all 1's (code point 49) with [.
For example, "0b101100" ↦ "],b[],[[],],".
Remove the first three characters (they correspond to "0b") and the trailing character (hopefully a comma).
For example, "],b[],[[],]," ↦ "[],[[],]".
Try evaluating the generated code. If this results in an error, k isn't mapped to any list.
For example, "[],[[],]" ↦ ([], [[]]).
Concatenate the result (if any) with the empty list. If this results in an error, k isn't mapped to any list.
For example, ([], [[]]) + [] errors since + cannot concatenate lists and tuples.

Haskell, 71 bytes
p 1=["[]"]
p n=['[':h++t|k<-[1..n-1],h<-p k,_:t<-p$n-k]
((p=<<[1..])!!)

The main function on the last line indexes into a list of all nested arrays, sorted by size (number of open brackets). So, all the arrays of size at most 16 are listed first.
Let's first look at code that's nicer and shorter, but Haskell's typechecker refuses to accept.
p 1=[[]]
p n=[h:t|k<-[1..n-1],h<-p k,t<-p$n-k]
((p=<<[1..])!!)

The function p on input n gives a list of all nested arrays of size n (open brackets). This is done recursively. Each such array consists of some head h (first member) of size k and some tail t (other members) of size n-k, both sizes nonzero. Or, it's the empty array for size n==1.
The expression p=<<[1..] then flattens p(1), p(2), ... into a single infinite list of all arrays sorted by size
[ [], [[]], [[],[]], [[[]]], [[],[],[]], [[],[[]]], [[[]],[]], [[[],[]]], ...

and the main function indexes into it.
... Or, it would, if Haskell didn't whine about "construct[ing] the infinite type: t ~ [t]". Haskell cannot represent the infinite list above whose elements are arbitrarily nested arrays.  All its elements must have the same type, but a type t cannot be the same as a list of t's. In fact, the function p itself cannot be assigned a consistent type without dependent typing, which Haskell lacks.
So, instead we work on strings of brackets, simulating the cons operation by acting on [ and ] characters. This takes an extra 9 bytes. The perils of golfing in a type-safe language.

Haskell, 87 82 bytes
0#0=[""]
n#m=['[':x|n>0,x<-(n-1)#m]++[']':x|n<m,x<-n#(m-1)]
(([0..]>>= \y->y#y)!!)

Outputs the array elements. Usage example: (([0..]>>= \y->y#y)!!) 3 -> "[][]".
Function # builds all nested arrays as strings for n open and m close brackets, by keeping track of how many of each are left over. Always starts with n == m.  The main function calls y # y for every y <- [0,1,...] and picks the element at the index  given by the input.

MATL, 31 bytes
O`@BEqXJYs0&)0>w~hA+tG>~]x92J-c

Try it online! Or verify the first few test cases (takes a few seconds).
The produced mapping is:
0 -> []
1 -> [[]]
2 -> [[][]]
3 -> [[[]]]
4 -> [[][][]]
5 -> [[][[]]]
6 -> [[[]][]]
7 -> [[[][]]]
...

Explanation
The code keeps testing increasing binary numbers, with digit 0 replaced by -1; that is, using 1 and -1 as digits. Digit 1 will represent '[' and -1 will represent ']'.
The program counts until n+1 valid numbers have been obtained. A number is valid if the following two conditions hold:

The sum of digits is zero (that is, there is an equal number of 1 and -1)
The cumulative sum of digits is always positive (that is, the accumulated number of 1 digits always exceeds that of -1) except at the end (where it is zero by condition 1).

Once n+1 valid numbers have been obtained, the last one is transliterated by changing 1 into [ and -1 into ], and then it is displayed.
Code:
O          % Push 0: initial count of valid numbers
`          % Do...while
  @        %   Push iteretation index k, starting at 1
  B        %   Convert to binary. For example, k=6 gives [1 1 0 0]
  Eq       %   Multiply by 2, subtract 1: transforms [1 1 0 0] into [1 1 -1 -1]
  XJ       %   Copy that to clipboard J, without popping it
  Ys       %   Cumulative sum: gives [1 2 1 0]
  0&)      %   Split array into its final element and the rest. Gives 0, [1 2 1]
  0>       %   Yields 1 for positive entries (condition 2). So in this case it
           %   gives [1 1 1]
  w        %   Swap: moves second-top element in the stack (0 in this case) to top
  ~        %   Negate: yields 1 if input is 0 (condition 1). Gives 1 in this case
  h        %   Concatenate horizontally. Gives [1 1 1 1]
  A        %   All: gives 1 if all elements are 1. Gives 1 in this case, meaning
           %   that this k is valid
  +        %   Add the result (0 or 1) to the count of valid numbers
  t        %   Duplicate
  G        %   Push input n
  >~       %   Loop condition: false (exit loop) if count exceeds input n
]          % End loop. At this point the result is in clipboard J, in 1/-1 format
x          % Delete count
92         % Push 92. Will be used to convert 1, -1 to '[', ']' (ASCII 91, 93)
J          % Push result in 1/-1 format
-          % Subtract: converts 1 to 91, -1 to 93
c          % Convert to char. Implicitly display

JavaScript (Node.js), 85 bytes
x=>eval("g=i=>i>1?(h-=i*2%4-1)&&']['[i%2]+g(i>>1):']';for(i=0;~x;~h||--x)h=0,g(i++)")

Try it online!
Work for all positive integers assuming infinite bit width. But may fail when n is large and bit is broken. Slow.
JavaScript (Node.js), 90 bytes
x=>eval("g=i=>i>1?(h-=[i]*2%4-1)&&']['[i%2n]+g(i>>1n):']';for(i=0n;~x;~h||--x)h=0,g(i++)")

Try it online!
Should be enough and theoretically all. Slow.
JavaScript (Node.js), 97 96 bytes
x=>(h=x.toString(2).replace(/./g,c=>']['[i+=c-.5,i-=!i,c],i=0),i-.5?'['+'[]'.repeat(x+20):h)+']'

Try it online!
Only fit the range. Fast for short output


text:
String and ASCII
The Challenge
Given a non-empty string containing only lowercase or uppercase letters and no spaces:

Sum up the ASCII values for each character instance in the input string.
The sum will be converted to binary.
And, the result will be the number of ones in the binary value.

Input example:
abcDeFAaB

Sum up the ASCII values for each character instance, so for this example: 97+98+99+68+101+70+65+97+66 = 761.
Convert the sum (761) to binary. This will give 1011111001.
The final result will be the number of ones (7).

So the output for this example is 7.
Winning Criterion
This is code-golf, so shortest answer in bytes wins!

I'm wondering, what's with all the downvotes? Maybe this challenge isn't too hard but it's not trivial either. Currently it stands for a 0/-3 score. Why?

This is just three separate challenges that already exist mashed together: sum of ordinals (the averaging part is a trivial addition), decimal to binary (a subset of the linked challenge), and count ones in binary.

A mix of multiple existing challenge subsets, even if trivial, shouldn't be considered a duplicate, because in terms of code-golf the solution can be much shorter compared to the multiple ones combined. Indeed, there are already posted answers here of 5 bytes or less.

@seshoumara, it's true that sometimes doing A and B is shorter than doing A and then doing B, but only if A and B have something in common. Summing codepoints and bitcount are so orthogonal that only a language specialised for this challenge would do better than essentially taking separate answers to the previous questions and combining them.

Is there a maximum string length

Why didn't the MATL submission win?

Jelly, 4 bytes
OSBS

TryItOnline
How?
OSBS - Main link: s     e.g. "abcDeFAaB"
O    - ordinal (vectorises)  [97, 98, 99, 68, 101, 70, 65, 97, 66]
 S   - sum                   761
  B  - binary                [1, 0, 1, 1, 1, 1, 1, 0, 0, 1]
   S - sum                   7

Python3, 46 40 bytes
lambda s:bin(sum(map(ord,s))).count("1")

R, 65 53 43 42 bytes
Counting the number of 1s in a binary representation is calculating the Hamming weight of a number, a common procedure in cryptanalysis. There's an R package boolfun, described in this journal article, which handily has a function weight which computes the Hamming weight of any (base 10) integer. That makes our job a lot easier! The rest of the code just sums over the integer representation of STDIN, before sending that to weight.
boolfun::weight(sum(utf8ToInt(scan(,'')))

As an added bonus, this code works for UTF-8 as well as ASCII. There are 7 ones in the binary representation of the sum of 高尔夫 (that's golf in Mandarin).
A note for those playing along at home: unfortunately, boolfun is no longer hosted on CRAN, so if you don't already have it installed you'll have to do it manually with install.packages("https://cran.r-project.org/src/contrib/Archive/boolfun/boolfun_0.2.8.tar.gz", repos = NULL, type = "source"), rather than install.packages(boolfun).
If you really don't want to use boolfun, you can achieve the same result with only two more bytes:
sum(intToBits(sum(utf8ToInt(scan(,''))))==1)

Nice idea with the boolfun package, +1!

MATL, 3 bytes
sBs

Try it online!
Shortest language for this challenge, I think: sum, Binary, sum.

@Ajay Isn't this the winner by code-golf criteria?

05AB1E, 6 5 bytes
ÇObSO

Explanation
 Ç      # convert to list of ascii values
  O     # sum
   b    # convert to binary
    SO  # sum as a list

Try it online!

Bash + coreutils, 43 49 bytes
Edit: corrected version based on manatwork's comments.
od -vAn -tuC|tr '\n ' +|dc -e?2op|grep -o 1|wc -l

Explanation:
The result is printed on STDOUT, with some warnings given on STDERR which can be ignored.
od -vAn -tuC       # get the ASCII value for each string character
|tr '\n ' +        # replace each whitespace with a plus (in dc, a warning will be
                   #raised for each consecutive plus)
|dc -e?2op         # execute input, calculating the sum, then convert to binary
|grep -o 1|wc -l   # count how many ones exist

Run:
echo -n "abcDeFAaB" | ./script.sh 2> /dev/null

Output:
7

A similar solution is presented below (51 bytes), that had the potential to be shorter, but with xxd I can't concatenate multiple flags and also dc only understands upper case hex letters.
xxd -c1 -u -p|tr \\n +|dc -e16i?2op|grep -o 1|wc -l

I'm afraid this works only for the first 16 characters of the input string, because od wraps the output. :( Otherwise nice trick to just add the character address to the characters codes.

@manatwork Good catch, I can fix it with od -An -tuC|tr '[\n ]' +. However, I found a weird printing behavior if input is repetitive. With 32 'a's as input, od prints the first 16 values and then a '*' on the second line :( Do you know how to make it print absolutely each value? I think I have to use xxd instead.

Wow. Never noticed that weird behavior. But -v seems to get rid of it. BTW, no need for brackets in tr's parameter.

@manatwork Updated my answer. Thanks for both suggestions!

Java 7,80,76 bytes
Thanks to kevin for saving 4 bytes
int f(char[]a){int s=0,c=0;for(char i:a)s+=i;for(;s>0;s&=s-1,c++);return c;}

Ungolfed
int f(char[]a){
    int s=0,c=0;
    for(char i:a)
        s+=i;
    for(;s>0;s&=s-1,c++);
        return c;
}

Dang, you beat me to it. I was just about to post this exact answer.. Btw, you can shorten it a bit to this: int f(char[]a){int s=0,c=0;for(char i:a)s+=i;for(;s>0;s&=s-1,c++);return c;} (76 bytes)

I need to learn more!...btw Thanks

Umm, I think you've incorrectly copied/golfed it from your IDE, since you now have the return inside the for-loop instead of behind it (you probably forgot the ; after the for-loop). As you can see in my comment above it first does a for-loop for(;s>0;s&=s-1,c++); ending with semi-colon, and then it returns. And as for the learning part, I've been corrected a lot of times in the past as well. You'll learn it over time. I still have a lot to learn myself and my answers are still occasionally being golfed by others.

@KevinCruijssen oops!•••• and thanks..／人 ◕ ‿‿ ◕ 人＼

PHP, 79 76 bytes
foreach(str_split($argv[1])as$c)$s+=ord($c);echo substr_count(decbin($s),1);

Test online
Ungolfed testing code:
$argv[1] = 'abcDeFAaB';

foreach(str_split($argv[1]) as $c){
    $s += ord($c);
}
echo substr_count(decbin($s),1);

Test online

R, 98 bytes
Was interested in how difficult this would be in R. Turns out you have to do a lot of conversions back and forth (in this solution at least) but I'm sure there should be a shortcut, especially if using packages (can't access any here at work).
sum(as.integer(rev(intToBits(sum(strtoi(sapply(strsplit(readline(),"")[[1]],charToRaw),16L)))))^2)

Could add an explanation if someone is interested.

Before I saw your answer I came up with a very similar solution, which you can see here. You have some unnecessary function calls which can be excluded (e.g. rev, which is needless as you just sum over everything anyway, and the call to sapply is not needed as charToRaw can handle strings with multiple characters). Nice that we ended up with the same solution though!

@rturnbull Nice, I knew there were some unnecessary stuff in there.

One more thing: the L after the 16 ensures that it is of type integer and not numeric, which is good practice for careful programming, but for code golf purposes you can (almost?) always omit it, saving a byte.

><>, 34 bytes
01\
(?\i:@+$0
?!\:2%:}-2,r+$:
n;\~

Try it online!

Haskell, 47 bytes
g 0=0;g n=mod n 2+g(div n 2)
g.sum.map fromEnum

Perl, 36 bytes
Includes +1 for -p
Run with input string without newline on STDIN:
echo -n abcDeFAaB | strsum.pl; echo

strsum.pl:
#!/usr/bin/perl -p
$_=unpack"%b*",pack N,unpack"%32W*"

If the sum of the ASCII values fits in a 16-bit integer you can leave out the 32 and gain 2 more bytes.

Julia, 56 Bytes
f(s)=length(filter(i->i=='1',bin(sum(map(Int,[s...])))))

Convert to ascii value, sum up, filter for 1s, take length of result

JavaScript ES6, 80 78 71 Bytes

g=
    s=>[...s].map(c=>r+=c.charCodeAt(),r=0)|r.toString(2).split`1`.length-1
;

console.log(g.toString().length);    // 71
console.log(g('abcDeFAaB'))          // 7

Saved 7 Bytes thanks to @BassdropCumberwubwubwub
Breakdown
 [...s]                              // Split string into array of chars
 .map(c=>r+=c.charCodeAt(),r=0)      // Sum up ASCII values
 |
 r.toString(2)                       // Convert to binary (represented as string)
 .split`1`.length-1                  // Count occurences of 1

You can change [...r.toString(2)].map(c=>r+=+c,r=0)|r to r.toString(2).split\1`.length-1` to save 7 bytes

@BassdropCumberwubwubwub Thank you.

Can match\1`g.length` work?

Common Lisp, 53
(lambda(s)(logcount(reduce'+(map'list'char-code s))))

PHP, 73 bytes
<?=substr_count(decbin(array_sum(array_map(ord,str_split($_GET[s])))),1);

save to file, call in browser with <scriptpath>?s=<string>
or
<?=substr_count(decbin(array_sum(array_map(ord,str_split($argv[1])))),1);

save to file, run with php <scriptpath> <string>

To run without a file, replace <?= with echo<space> in the second version
and run with php -r '<code>' <string>.

Javascript (ES6), 72 70 bytes
Saved 2 bytes thanks to ETHproductions:

f=
  (s,p=([c,...d])=>c?c.charCodeAt()+p(d):0,q=n=>n&&n%2+q(n>>1))=>q(p(s))
;
console.log(f('abcDeFAaB'));

Explanation:
(s,                                        //Input string
    p=([c,...d])=>c?c.charCodeAt()+p(d):0, //Recursive method to sum up the ASCII values
    q=n=>n&&n%2+q(n>>1)                    //Recursive method to count 1s in the binary form
)=>q(p(s))

Previous solution (72 bytes):
(s,p=([c,...d])=>c?c.charCodeAt()+p(d):0,q=n=>n&&(n&1)+q(n>>1))=>q(p(s))

Nice. You can golf q like so: q=n=>n&&n%2+q(n>>1)

C#, 51 50 bytes
s=>Convert.ToString(s.Sum(x=>x),2).Count(x=>x>48);

can be used like this:
Func<string, int> f=s=>Convert.ToString(s.Sum(x=>x),2).Count(x=>x>48);
f("abcDeFAaB") // == 7

would be so much shorter if Int32.ToString() had a to binary flag.
Edit: saved one byte by converting '0' to int

As far as I remember, x=>x inside Sum() is not required, although I'm not sure if it'll do the implicit cast to integers...

I tried that but there is no .Sum() for string

That's what I feared. How about changing the '0' literal to 48? You actually have it in your example, but not at the golfed code.

of course, stupid me forgetting halve the code

Pyth, 8 bytes
ssM.BsCM

Try it online!
Explanation:
      CM  (M)ap ordinals(C) over input
     s    (s)um
   .B     Binary string
 sM       map cast to integer
s         sum

Mathematica, 53 37 bytes
not the best solution but hey...built-in's ftw
Shortened. Thanks to Martin Ender
DigitCount[Tr@ToCharacterCode@#,2,1]&

ToCharacterCode can be called directly on a string. Total can be shortened to Tr.


text:
Checkers: King Me?
Challenge:
Given a checkerboard, output the smallest amount of moves it would take (assuming black does not move at all) to king a red piece, if possible.
Rules:
Red's side will always be on the bottom, however their pieces may start in any row (even the king's row they need to get to).  Black pieces are stationary, meaning they do not move in between red's movements, but they are removed from the board when captured.  Note that pieces can start on any space on the board, including right next to each other.  This is not how normal checkers is played, but your program must be able to solve these.  (See input 5)  However, checker pieces must only move diagonally (see input 3).  Backward-capturing is allowed if the first capture is forward in the chain (see input 7).
Input:
An 8x8 checkerboard, with board spaces defined as the following characters(feel free to use alternatives as long as they're consistent):
. - Empty
R - Red piece(s)
B - Black piece(s)
Output:
The smallest number of moves it would take a red piece to be 'kinged' by entering the king's row on the top row of the board (black's side), 0 if no moves are required (a red piece started on king's row), or a negative number if it is impossible to king a red piece (ie black occupies it's entire first row).
Input 1:
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
R . . . . . . .

Output 1:
7

Input 2:
. . . . . . . .
. . . . . . . .
. . . . . B . .
. . . . . . . .
. . . B . . . .
. . . . . . . .
. B . . . . . .
R . . . . . . .

Output 2:
2

Input 3:
. B . B . B . B
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
R . . . . . . .

Output 3:
-1

Input 4:
. . . . . . . R
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
R . . . . . . .

Output 4:
0

Input 5:
. . . . . . . .
. . . . . . . .
. . . . . . . .
. B . . B . . .
B . . . . B . .
. B . B . . . .
. . B . . B . .
. . . R R . . .

Output 5:
4

Input 6:
. . . . . . . .
. . . . . . . .
. B . . . . . .
. . B . . . . .
. B . B . . . .
. . . . R . . .
. . . B . . . .
. . . . R . . .

Output 6:
2

Input 7:
. . . . . . . .
. . . . . . . .
. . B . . . . .
. . . . . . . .
. . B . . . . .
. B . B . B . .
. . . . B . . .
. . . . . R . R

Output 7:
4

Scoring:
This is code-golf, so shortest code in bytes wins.

Shouldn't the second test case be 2, since you can double/triple jump?

Is a state array of arrays of integers as input OK?

@DJMcMayhem Oh you're right, I totally forgot about that.  I'll update the outputs appropriately.

@JonathanAllan Yes, that is fine.

I added another testcase that should prove difficult. It involves multiple jumps, multiple pieces and jumping backwards in order to achieve the best possible solution.

@orlp Hm, I was going to say none of the red pieces are allowed to move backwards since none of them are kings (hence the point of the challenge), but it appears some people play with rules where capturing backwards is allowed by non-kinged pieces if the first capture was forward.  I'll add that to the rules since I was not aware of this before.

Should Output 7 be 5 and not 4? I see the backwards capture but I don't see that it saves a move.

Will there always be a solution? If the board is the initial Checkers board, and black cannot move, then there is no solution.

@GregMartin No, the red piece on the right takes 2 moves, one to the left and the second to capture two pieces.  The other red piece can then do a triple capture, followed by 1 more move to the last row, which results in 4 total.  As a side note, the first piece also has the option to capture one more piece during the capture chain which does not effect the number of moves (but perhaps another test case could be introduced where a capture like that could actually be harmful).

@mbomb007 No, see test case 3.  If there is no solution, print out anything other than a valid answer (I assume negative number would be the easiest, but it's up to you).  0 is reserved for a red piece that already sits in the goal row (test case 4).

ooooooooh, you don't have to choose just one red piece, they can team up! I get it

JavaScript (ES6), 354 322 bytes
Takes an array as input with:

0 = empty square
1 = red piece
2 = black piece

Returns the optimal number of moves, or 99 if there's no solution.
It's very fast but could be golfed much more.

F=(b,n=0,C=-1,i)=>b.map((v,f,X,T,x=f&7,y=f>>3)=>v-1||(y&&n<m?[-9,-7,7,9].map(d=>(N=c=X=-1,r=(d&7)<2,T=(t=f+d)>=0&t<64&&(x||r)&&(x<7||!r)?(!b[t]&d<0)?t:b[t]&1?N:b[t]&2&&(d<0&y>1|d>0&C==f)?(X=t,x>1||r)&&(x<6|!r)&&!b[t+=d]?c=t:N:N:N)+1&&(b[f]=b[X]=0,b[T]=1,F(b,n+!(C==f&c>N),c,1),b[f]=1,b[X]=2,b[T]=0)):m=n<m?n:m),m=i?m:99)|m

var test = [
  [ 0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    1,0,0,0,0,0,0,0
  ],
  [ 0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,2,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,2,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,2,0,0,0,0,0,0,
    1,0,0,0,0,0,0,0
  ],
  [ 0,2,0,2,0,2,0,2,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    1,0,0,0,0,0,0,0
  ],
  [ 0,0,0,0,0,0,0,1,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    1,0,0,0,0,0,0,0
  ],
  [ 0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,2,0,0,2,0,0,0,
    2,0,0,0,0,2,0,0,
    0,2,0,2,0,0,0,0,
    0,0,2,0,0,2,0,0,
    0,0,0,1,1,0,0,0
  ],
  [ 0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,2,0,0,0,0,0,0,
    0,0,2,0,0,0,0,0,
    0,2,0,2,0,0,0,0,
    0,0,0,0,1,0,0,0,
    0,0,0,2,0,0,0,0,
    0,0,0,0,1,0,0,0
  ],
  [ 0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,2,0,0,0,0,0,
    0,0,0,0,0,0,0,0,
    0,0,2,0,0,0,0,0,
    0,2,0,2,0,2,0,0,
    0,0,0,0,2,0,0,0,
    0,0,0,0,0,1,0,1
  ]
];

test.forEach((b, n) => {
  console.log("Test #" + (n + 1) + " : " + F(b));
});

99 is probably fine, I can't imagine a real solution taking 99 moves on an 8x8 board.  Nice job!


text:
Translate number pairs to guitar notes
A guitar fretboard diagram looks like this:
  0  1  2  3  4  5  6  7  8  9 10 11 12   <- Fret number (0 means it's open)
|-E--F--F#-G--G#-A--A#-B--C--C#-D--D#-E
|-B--C--C#-D--D#-E--F--F#-G--G#-A--A#-B
|-G--G#-A--A#-B--C--C#-D--D#-E--F--F#-G
|-D--D#-E--F--F#-G--G#-A--A#-B--C--C#-D
|-A--A#-B--C--C#-D--D#-E--F--F#-G--G#-A
|-E--F--F#-G--G#-A--A#-B--C--C#-D--D#-E

As you can see, the first string (from the top) open is an E. The first fret on the first string is an F. The fourth fret on the third string is a B. Note that the first note is the zeroth fret, not the first.
This can be written with numbers on the format string, fret. The strings are numbered from 1 to 6 from top to bottom.
The frets are numbered from 0 to 12 from left to right. The first E is therefore 1, 0. Some other examples:
1, 0 --> E
1, 1 --> F
3, 5 --> C
5, 1 --> A#
6, 6 --> A#

Challenge:
Take N pairs of numbers (s and f), and output a delimited note succession.

The input may be on any suitable format. tuples, 2D-matrix, two separate lists, an interweaved list (string,fret,string,fret...) etc.
The output tone should be separated, but the delimiter is optional (comma, space, dash...). The output can be in either upper or lower case.
s (for string) will be in the range [1, 6] (you may choose to have i 0-indexed)
f (for fret) will be in the range [0, 12]

Test cases and examples:
1 4 5 2 1 3   <- String
4 2 6 3 5 1   <- Fret
G# E D# D A G#

6 2 3 1 4 2 3 2 2 2 6 5 2
0 1 2 3 4 5 6 7 8 9 10 11 12
E C A G F# E C# F# G G# D G# B

3 3 3 3 3 3 3 3 3 3 3 3 3   <- String
0 3 5 0 3 6 5 0 3 5 3 0 0   <- Fret
G A# C G A# C# C G A# C A# G G

// The same test case, but different input and output format:
(3,0)(3,3)(3,5)(3,3)(3,6)(3,5)(3,0)(3,3)(3,5)(3,3)(3,0)(3,0)
G,A#,C,G,A#,C#,C,G,A#,C,A#,G,G

Good luck, and happy golfing!

Not a guitarist (nor even a decent musician, really), but isn't there a significant omission here, if you're expecting output as recognizable tunes?  That is, the note duration - whole, half, quarter notes, &c.

@jamesqf Nope, it's perfectly fine as long as you know the song. This is currently the most popular song on ultimate-guitar.com. Have a look at the intro.

05AB1E, 48 47 43 40 bytes
Uses CP-1252 encoding.
Both strings and frets are 0-based.
v7YT5¾7)y`Šè+•™ÎÚ,Ülu•žh'#A«‡•7V3•3BS£è,

Explanation
v                                # for each pair in input
 7YT5¾7)                         # the list [7,2,10,5,0,7]
 y`                              # flatten the pair [string, fret] and places on stack
 Šè                              # index into the list above using the string
 +                               # add the fret
 •™ÎÚ,Ülu•žh'#A«‡•7V3•3BS£       # list of accords
 è                               # index into the string using the number calculated above
 ,                               # print

Try it online!
Saved 7 bytes thanks to Adnan

Exploiting bugs is very much golfy! .-)

"AA#BCC#DD#EFF#GG#"•7V3•3BS£ instead of "A A# B C C# D D# E F F# G G#"# is a few bytes shorter :).

@Adnan: Ooh, nice base-change :)

Also a compressed version of the "AA#BCC#DD#EFF#GG#" string: •™ÎÚ,Ülu•žh'#A«‡ (since lowercase is allowed :p).

JavaScript (ES6), 79 70 bytes
a=>a.map(([s,f])=>"AA#BCC#DD#EFF#GG#".match(/.#?/g)[(s*7+(s>2)+f)%12])

Requires 1-based strings. Edit: Saved 9 bytes by directly calculating the string to fret conversion, based on @nimi's old answer.

@Arnauld Thanks but I ended up appropriating @ nimi's answer instead.

Much more efficient indeed ;)

Clever. very sneaky answer

Mathematica, 62 bytes (non-competing)
<<Music`;MusicScale[100(#2+{24,19,15,10,5,0}[[#]])&@@@#,E2,9]&

The {24,19,15,10,5,0} and the E2 represent the open-string tones of the six guitar strings (for example, the top string is 24 semitones above the note E2). Non-competing because it doesn't print the names of the notes—it plays the sequence of notes! (only if you have Mathematica, unfortunately) For example,
<<Music`;MusicScale[100(#2+{24,19,15,10,5,0}[[#]])&@@@#,E2,9]&@
 {{4,0},{3,2},{2,3},{1,2},{5,0},{4,2},{3,2},{2,2},
  {5,2},{4,4},{2,0},{2,3},{6,2},{4,4},{3,2},{2,2},
  {6,3},{4,0},{3,0},{2,0},{4,0},{4,4},{3,2},{2,3},
  {6,3},{3,0},{2,0},{2,3},{5,0},{4,2},{3,2},{2,2},{4,0}}

plays the opening 4 bars or so from Pachelbel's Canon. (which is about as much of Pachelbel's Canon as I can stand)

MATL, 48 47 45 bytes
Thanks to @Emigna for a correction regarding input format.
Guitar and code golf... I had to answer this one!
'$)-27<'i)-'F F# G G# A A# B C C# D D#

Input format is: an array of (1-based) string, then an array of (0-based) frets.
Try it online!
Explanation
Some language features used in this answer:

A string is automatically converted to a numerical array of ASCII code
points when some arithmetic operation is applied to it.
Arithmetical operations work element-wise, i.e. vectorized. So the subtraction of a string and a numerical array of the same size gives an array with the subtraction of corresponding entries.
Indexing is 1-based and modular.
A cell array is like a list in other languages. It can contain arbitrary elements, possibly arrays of different types or sizes. Here a cell array will be used to store strings of different lengths (the notes' names).

Commented code:
'$)-27<'                       % Push this string
i                              % Take first input (array of guitar strings)
)                              % Index into the string. For example, input [1 3] gives
                               % the string '$-' (indexing is 1-based)
-                              % Implicitly take second input (array of guitar frets).
                               % Subtract element-wise. This automatically converts the
                               % previous string into an array of ASCII codes. For
                               % example, second input [1 5] gives a result [-35 -40],
                               % which is [1 5] minus [36 45], where 36 and 45 are the
                               % ASCII codes of '$-'
'F F# G G# A A# B C C# D D# E' % Push this string
Yb                             % Split at spaces. Gives a cell array of 12 (sub)strings:
                               % {'F', 'F#', 'G', ..., 'E'}
w)                             % Swap and index into the cell array of strings.
                               % Indexing is 1-based and modular. In the example, since
                               % the cell array has 12 elements, the indexing array
                               % [-35 -40] is the same [1 8], and thus it gives a
                               % (sub-)array formed by the first and eighth cells:
                               % {'F', 'C'}. This is displayed as the cells' contents,
                               % one per line

I knew I was going to find an answer from you as soon as I saw the word "Guitar"

@LuisMendo Very nice! I like the ascii-char index trick :)

Java, 174
String f(int[]s,int[]f){String o="";for(int i=0;i<s.length;++i){int n =(7*s[i]-7+f[i]+(s[i]>2?1:0))%12*2;o+="E F F#G G#A A#B C C#D D#".substring(n,n+2).trim()+" ";}return o;}

Ungolfed:
  String f(int[] s, int[] f) {
    String o = "";
    for (int i = 0; i < s.length; ++i) {
      int n = (7 * s[i] - 7 + f[i] + (s[i] > 2 ? 1 : 0)) % 12 * 2;
      o += "E F F#G G#A A#B C C#D D#".substring(n, n + 2).trim() + " ";
    }
    return o;
  }

C, 104 103 bytes
main(s,f){for(;~scanf("%d%d",&s,&f);printf("%.2s\n",
"E F F#G G#A A#B C C#D D#"+(f+7*~-s+(s>2))%12*2));}

Takes numbers as string fret pairs on stdin, and outputs the note after every pair. E.g.:
1 4
G#
4 2
E
5 6
D#
2 3
D

Ruby, 63 bytes
takes an array of 2-element arrays, in the order [string,fret].
->x{x.map{|i|"BEADGCF"[6-n=((i[0]-3)%5+2+i[1]*7)%12]+?#*(n/7)}}

Explanation
In standard tuning the guitar is one of the few stringed instruments (bowed or fretted) that has inconsistent intervals between its strings. Most have either a consistent 5-semitone interval between all pairs of adjacent strings (a "fourth") or a consistent 7-semitone interval between all pairs of adjacent strings (a "fifth.") These correspond to frequency ratios of 3:4 and 2:3 respectively, and are second in importance only to the "octave" with frequency ratio 1:2.
The guitar has mostly 5-semitone intervals. If it had 5 of these it would have a difference of 25 semitones between the 1st and 6th string. Instead, the interval between the 2nd and 3rd string is reduced to 4 semitones, giving a difference of 24 semitones (2 octaves) which is better for playing chords.
This is inconvenient for the program, so we start by changing the 1-indexed guitar intonation into a 0 indexed 5-string-bass intonation, which has all intervals of 5 semitones:
formula (i[0]-3)%5
Before                            After
String      6 5 4 3 2 1           String 4 3 2 1 0
Note        E A D G B E           Note   B E A D G

Next we add 2, and give the tuning of a fictitious 12 string bass, with intonation of the open strings as follows, and all intervals being 5 semitones (12 string "basses" do exist but I am not sure there are many with precisely this tuning.)
String       11 10 9  8  7  6  5  4  3  2  1  0
Note         A# D# G# C# F# B  E  A  D  G  C  F

As can be seen, all the sharps are grouped together. This pattern can be repeated ad infinitum. It is known as the "circle of fifths" and is fundamental to the Western musical scale (with a bit of tuning adjustment the circle can be closed due to the fact that (3/2)**12 and 2**7 are very similar numbers.
Now we deal with the fret parameter. Unlike many other answers here, which translate the string parameter into a number of frets, I translate the fret parameter into a number of strings. In the table above  it can be seen that adding 7 to the string number puts us on a string whose note name is one semitone higher. (It's in a completely different octave but that does not matter.) So we add i[1]*7 to the string number, and take it modulo 12:
n=(i[0]-3)%5+2+i[1]*7)%12

We subtract this from 6 to get a number in the range 6 to -5 and look up the letter in BEADGCF (Ruby allows negative indices to wrap around back to the end of the array.) If n>=7 we need to add a # symbol to complete the output.
Test program
f=->x{x.map{|i|"BEADGCF"[6-n=((i[0]-3)%5+2+i[1]*7)%12]+?#*(n/7)}}

z=[[6, 2, 3, 1, 4, 2, 3, 2, 2, 2, 6,5,2],[0, 1, 2, 3, 4 ,5 ,6 ,7, 8, 9, 10, 11, 12]].transpose

puts f[z]

Output
E
C
A
G
F#
E
C#
F#
G
G#
D
G#
B

C#, 131 bytes
string n(int[]s,int[]f){return string.Join(" ",s.Zip(f,(x,y)=>"E,F,F#,G,G#,A,A#,B,C,C#,D,D#".Split(',')[(7*x-7+y+(x<3?0:1))%12]));}

Input two separate lists, strings are 1 based.

Welcome to the site! Nice first answer.

@DJMcMayhem: Thank you :-)

Java 7  197,163 bytes
void f(int[]s,int[]f){String[]l={"A","A#","B","C","C#","D","D#","E","F","F#","G","G#"};int[]d={0,7,2,10,5,0,7};int j=0;for(int i:s)out.print(l[(d[i]+f[j++])%12]);}

Ungolfed
  void f(int[]s,int[]f){
 String[]l={"A","A#","B","C","C#","D","D#","E","F","F#","G","G#"};
int[]d={0,7,2,10,5,0,7};
    int j=0;
    for(int i:s)
        out.print(l[(d[i]+f[j++])%12]);

}

Clora, 55 bytes
@T[0,7,2,10,5,0,7]+N%12@T[,A,A#,B,C#,D,D#,E,F,F#,G,G#]!
Explanation
@ numeric mode (read input as numbers)
T[0,7,2,10,5,0,7] Transform input using the array, ex array[Input]
+N Add N (Next input value) to current Input
%12 Modulo 12 the current input value
@ Flag numeric mode off
T[,A,A#,B,C#,D,D#,E,F,F#,G,G#] Translate the input into an array
! Use input as output value

Haskell, 83 82 bytes
zipWith$(!!).(`drop`cycle(words"A# B C C# D D# E F F# G G# A")).([6,1,9,4,11,6]!!)

Takes a list of strings and a list of frets, both 0-indexed. Usage example:
Prelude >  ( zipWith$(!!).(`drop`cycle$words"A# B C C# D D# E F F# G G# A").([6,1,9,4,11,6]!!) ) [0,1,2,3,4,5] [0,0,0,0,0,0]
["E","B","G","D","A","E"]

From the infinite list of notes starting with A#, drop the number of notes given by the list [6,1,9,4,11,6] at index of the string and pick the note at index of the fret from the remaining list.

Unfortunately the intervals between strings are not all equal.

@Neil: ... fixed.

It turned out to be a simple fix in JavaScript - (s*7)+(s>2) - so I'm now using that in my answer.

@Neil: ... working on that, too.

JavaScript (ES6), 82 81 bytes
a=>a.map(b=>(q=(b[0]+.3+b[1]*7.3|0)%12/1.7+10.3).toString(17)[0]+(q%1>.5?"#":""))

I wanted to try an all-math answer, but it turned out a little long. Maybe there's a way to golf it...
Test snippet

f=a=>a.map(b=>(q=(b[0]+.3+b[1]*7.3|0)%12/1.7+10.3).toString(17)[0]+(q%1>.5?"#":""))
console.log(f([[4,1],[2,4],[6,5],[3,2],[5,1],[1,3]]))

I wanted to use toString(17) but struggled to get it in a reasonable byte count.

Python 2, 94, 91, 88 bytes
for s,f in input():print"A A# B C C# D D# E F F# G G#".split()[([7,2,10,5,0,7][s]+f)%12]

There are probably some obvious improvements to be made. Input is a list of pairs, and the strings are 0-indexed, e.g:
[0, 4], [3, 2], [4, 6]...

PHP, 102 Bytes
<?foreach($_GET[i]as$t)echo[E,F,"F#",G,"G#",A,"A#",B,C,"C#",D,"D#"][[0,7,3,10,5][$t[0]%5]+$t[1]%12]._;

Input as multiple array both 0 based for example '[[2,0],[5,3],[2,12],[3,8],[0,3]]'
Nice alternative 106 Bytes to set the # based on mod 7 congruent
<?foreach($_GET[i]as$t)echo EFFGGAABCCDD[$d=[0,7,3,10,5][$t[0]%5]+$t[1]%12].["","#"][$d%7?$d%7%2?0:1:0]._;