text:
Ninjas and Monkeys and Bears, Oh My!
This challenge is NinjaBearMonkey's prize for winning my Block Building Bot Flocks! challenge with the Black Knight submission. Congratulations NinjaBearMonkey!
The challenge here is fairly simple, but has a variety of possible approaches. The story goes that in the world of Isometric Illusions, there are 6 different types of creatures:

Ninjas, abbreviated N
Bears, abbreviated B
Monkeys, abbreviated M
NinjaBears, abbreviated NB
BearMonkeys, abbreviated BM
NinjaBearMonkeys, abbreviated NBM

(NinjaBearMonkey is, of course, the last, most powerful type.)
Your task is to take a census of these creatures when they are lined up side-by-side, i.e. when their abbreviation strings are concatenated. The caveat is that you need to make sure not to over-count the parts of some creatures as separate creatures that happen to look similar. The creatures will line up such that:

Any instance of NBM is 1 NinjaBearMonkey and 0 other creatures.
Any instance of NB not followed by M is 1 NinjaBear and 0 other creatures.
Any instance of BM not preceded by N is 1 BearMonkey and 0 other creatures.
Otherwise, instances of N, B, and M are single Ninjas, Bears, and Monkeys respectively.

The line is read from left to right.
So, for example, in the line of creatures NBMMBNBNBM, there are 0 Ninjas, 1 Bear, 1 Monkey, 1 NinjaBear, 0 BearMonkeys, and 2 NinjaBearMonkeys.
Challenge
Write a program or function that takes in a string of the characters N, B, and M, and prints or returns how many of each of the 6 types of creatures are present in it.
The output should have the form
#N #B #M #NB #BM #NBM

with the respective creature count replacing each # sign. All 6 counts must be shown, separated by spaces, even when they are 0. However, they may be in any order (e.g. #NBM could come first).
Also:

The input string will only contain the characters N, B, and M.
If the empty string is input, then all the counts are 0.
The output may optionally contain a single leading and/or trailing space, and/or a single trailing newline.

The shortest submission in bytes wins.
Examples
Input: NB
Output: 0N 0B 0M 1NB 0BM 0NBM
Input: NBM
Output: 0N 0B 0M 0NB 0BM 1NBM
Input: NBMMBNBNBM (example from above)
Output: 0N 1B 1M 1NB 0BM 2NBM
Input: MBNNBBMNBM
Output: 1N 1B 1M 1NB 1BM 1NBM
Input: NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM
Output: 17N 6B 14M 5NB 8BM 3NBM

I approve this challenge.

Just to confirm: if all you had was 2 NinjaBearMonkeys, you can't form a line? Because they can't stand next to each other?

@AlanCampbell No. NBMNBM would be perfectly valid input. Reading it from left to right there are clearly 2 NinjaBearMonkeys.

Pyth, 22 bytes
 f|pd+/zTT=:zTd_.:"NBM

Quite hackish way to save 1 byte, thanks to @Jakube.

Pyth, 23 bytes
FN_.:"NBM")pd+/zNN=:zNd

Demonstration.
Prints in reverse order, with a trailing space and no trailing newline.
.:"NBM") is all the substrings, _ puts them in the right order, /zN counts occurences, and =:zNd in-place substitutes each occurence of the string in question with a space.
FN_.:"NBM")pd+/zNN=:zNd
FN                         for N in                            :
  _                                 reversed(                 )
   .:     )                                  substrings(     )
     "NBM"                                              "NBM"
           pd              print, with a space at the end,
              /zN          z.count(N)
             +   N                    + N
                  =:zNd    replace N by ' ' in z.

JavaScript ES6, 86 bytes
f=s=>'NBM BM NB M B N'.replace(/\S+/g,e=>(i=0,s=s.replace(RegExp(e,'g'),_=>++i))&&i+e)

(I just had to answer this.) It goes through each substring of NBM, starting with the longer ones, which take higher priority. It searches for each occurrence of that particular string and removes it (in this case replacing it with the current count so it won't be matched again). It finally replaces each substring with the count + the string.
This Stack Snippet is written in the ES5 equivalent of the above code to make it easier to test from any browser. It is also slightly ungolfed code. The UI updates with every keystroke.

f=function(s){
  return'NBM BM NB M B N'.replace(/\S+/g,function(e){
    i=0
    s=s.replace(RegExp(e,'g'),function(){
      return++i
    })
    return i+e
  })
}

run=function(){document.getElementById('output').innerHTML=f(document.getElementById('input').value)};document.getElementById('input').onkeyup=run;run()
<input type="text" id="input" value="NBMMBNBNBM" /><br /><samp id="output"></samp>

Could you change the regex part to 'NBM<newline>BM<newline>...<newline>N'.replace(/./g, ...)', where the <newline>s are literal newlines and the 's are backticks, forming an ES6 template string? Saves two bytes in the regex (. doesn't match newlines).

@WChargin Unfortunately, no, because the output must be space-separated.

Python 2, 78
n=input()
for x in"NBM BM NB M B N".split():n=`n`.split(x);print`len(n)-1`+x,

A variant of Vioz-'s answer. Fun with Python 2 string representations!
Counts occurrences of the substring indirectly by splitting on it, counting the parts, and subtracting 1. Instead of replacing the substrings by a filler symbol, replaces the string by the list that split produced. Then, when we take its string representation, the parts are separated by spaces and commas.

That's insane! Excellently insane, but still insane.

Nice work! Didn't think of that :)

Ruby, 166 80 72 68 characters
f=->s{%w(NBM BM NB M B N).map{|t|c=0;s.gsub!(t){c+=1};c.to_s+t}*' '}

Explanation:

The counting is done in reverse. This is because the longer ninjas and bears and monkeys take precedence over the shorter ones.
For NBM, BM, and NB, the sequences are gsub!'d out of the original string with a block to count how many of these sequences exist (yes, the function modifies its argument).

However, they can't be replaced with nothing, since otherwise BNBMM would be counted as NBM and BM instead of B, NBM, and M (because when the NBM would be removed, it would put the B and M together and there wouldn't be a way to distinguish it). Originally I returned a single character string (.gsub!('NBM'){c+=1;?|}), but I realized I could just return the result of the += (which is a number, so it can't be any of N B M).

For M, B, and N, I can just count how many of them there are in the string (no need to remove them via gsub!). Now it's a loop (don't know why I didn't think of that in the first place), so these are done the same way.

Similar solution in Ostrich, 54 51 chars:
:s;`NBM BM NB M B N`" /{:t0:n;s\{;n):n}X:s;nt+}%" *

Unfortunately not a valid solution, as there is a bug in the current Ostrich version (that is now fixed, but after this challenge was posted).

You can save 3 chars by using the array notation %w(NBM BM NB M B N) and removing the split.

@DickieBoy That's actually 4 chars; thanks!

Ah yes, the dot!

Java, 166 162
void f(String a){String[]q="NBM-NB-BM-N-B-M".split("-");for(int i=0,c;i<6;System.out.print(c+q[i++]+" "))for(c=0;a.contains(q[i]);c++)a=a.replaceFirst(q[i],".");}

And with a few line breaks:
void f(String a){
    String[]q="NBM-NB-BM-N-B-M".split("-");
    for(int i=0,c;i<6;System.out.print(c+q[i++]+" "))
        for(c=0;a.contains(q[i]);c++)
            a=a.replaceFirst(q[i],".");
}

It works pretty simply. Just loop over the tokens, replacing them with dots and counting as long as the input contains some. Counts the big ones first, so the little ones don't mess it up.
I originally tried replacing all at once and counting the difference in length, but it took a few more characters that way :(

As a Java dev, I want to make this shorter and see Java win for a change. After staring at it for awhile I have yet to find a way to make it shorter.

Well it definitely isn't going to win overall. The current leader is 22 bytes and there's just no way to do anything meaningful in Java in that size. My println statement alone is larger than that. I'm satisfied with it, though :D

I'm a bit late but I found a way... change String q[]= to String[]q=

Nice! Can't believe I missed that, it's on my standard list of things to look at :)

I only discovered it after trying to get into Code Golf as a JavaDev, I'm quite surprised at some of the stuff you can do

CJam, 36 32 31 bytes
l[ZYX]"NBM"few:+{A/_,(A+S@`}fA;

Thanks to @Optimizer for golfing off 1 byte.
Try it online in the CJam interpreter.
How it works
l                                e# Read a line L from STDIN.
 [ZYX]"NBM"                      e# Push [3 2 1] and "NBM".
           few                   e# Chop "NBM" into slices of length 3 to 1.
              :+                 e# Concatenate the resulting arrays of slices.
                {          }fA   e# For each slice A:
                 A/              e#   Split L at occurrences of A.
                   _,(           e#   Push the numbers of resulting chunks minus 1.
                      A+         e#   Append A.
                        S        e#   Push a space.
                         @`      e#   Push a string representation of the split L.
                              ;  e# Discard L.

N* -> ``` should be enough.

@Optimize: That works well. Thanks.

Taxi, 6284 bytes
Go to Post Office:W 1 L 1 R 1 L.Pickup a passenger going to Chop Suey.Go to Chop Suey:N 1 R 1 L 4 R 1 L.[A]Switch to plan N if no one is waiting.Pickup a passenger going to Cyclone.N is waiting at Writer's Depot.Go to Zoom Zoom:N 1 L 3 R.Go to Writer's Depot:W.Pickup a passenger going to Crime Lab.Go to Cyclone:N.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 R 1 R 1 R.Pickup a passenger going to Cyclone.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 R 1 R 1 R.Pickup a passenger going to Tom's Trims.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:S 1 L 2 R 1 L.Go to Cyclone:S 1 R 1 L 2 R.Pickup a passenger going to Crime Lab.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:S 1 L 2 R 1 L.Go to Crime Lab:S 1 L 1 L.Switch to plan F if no one is waiting.Pickup a passenger going to Auctioneer School.Go to Rob's Rest:S 1 R 1 L 1 L 1 R 1 R.Switch to plan D if no one is waiting.Go to Bird's Bench:S.Switch to plan B if no one is waiting.Go to Rob's Rest:N.Pickup a passenger going to KonKat's.Go to Bird's Bench:S.Pickup a passenger going to KonKat's.Go to KonKat's:N 1 R 1 L 2 R 1 R 2 R.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:N 1 L 2 L 1 L.Go to Auctioneer School:S.Pickup a passenger going to Rob's Rest.Go to Rob's Rest:N 2 L 1 R.Go to Cyclone:S 1 L 1 L 2 L.Switch to plan C.[B]Go to Auctioneer School:N 1 R 1 R.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:N.Go to Cyclone:N 1 L.[C]Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:N 2 R.Go to Chop Suey:E 2 R.Switch to plan A.[D]Go to Bird's Bench:S.Switch to plan E if no one is waiting.Pickup a passenger going to Sunny Skies Park.[E]Go to Auctioneer School:N 1 R 1 R.Pickup a passenger going to Rob's Rest.Go to Rob's Rest:N 2 L 1 R.Go to Sunny Skies Park:S 1 L 1 L.Go to Cyclone:N 1 L.Switch to plan C.[F]B is waiting at Writer's Depot.Go to Writer's Depot:S 1 R 1 L 2 L.Pickup a passenger going to Crime Lab.Go to Cyclone:N.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 R 1 R 1 R.Pickup a passenger going to Crime Lab.Go to Crime Lab:S 1 L 2 R 2 L.Switch to plan J if no one is waiting.Pickup a passenger going to Auctioneer School.Go to Bird's Bench:S 1 R 1 L 1 L 1 R 1 L.Switch to plan I if no one is waiting.Go to Rob's Rest:N.Switch to plan G if no one is waiting.Pickup a passenger going to KonKat's.[G]Go to Bird's Bench:S.Pickup a passenger going to KonKat's.Go to KonKat's:N 1 R 1 L 2 R 1 R 2 R.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:N 1 L 2 L 1 L.Go to Auctioneer School:S.[H]Pickup a passenger going to Bird's Bench.Go to Bird's Bench:N 2 L 1 L.Go to Cyclone:N 1 R 1 L 2 L.Switch to plan C.[I]Go to Auctioneer School:N 1 R 1 R.Switch to plan H.[J]Go to Bird's Bench:S 1 R 1 L 1 L 1 R 1 L.Switch to plan L if no one is waiting.Go to Rob's Rest:N.Switch to plan K if no one is waiting.Pickup a passenger going to KonKat's.[K]Go to Bird's Bench:S.Pickup a passenger going to KonKat's.[L]Go to Cyclone:N 1 R 1 L 2 L.Pickup a passenger going to KonKat's.Go to KonKat's:N 2 R 2 R.Pickup a passenger going to Sunny Skies Park.Go to Rob's Rest:S 4 R 1 L 1 L 1 R 1 R.Switch to plan M if no one is waiting.Pickup a passenger going to Sunny Skies Park.[M]Go to Sunny Skies Park:S 1 L 1 L.Go to Chop Suey:N 1 R 1 R 3 R.Switch to plan A.[N]Go to Rob's Rest:N 1 L 3 L 1 L 2 R 1 R.Switch to plan O if no one is waiting.Pickup a passenger going to KonKat's.[O]Go to Bird's Bench:S.Switch to plan P if no one is waiting.Pickup a passenger going to KonKat's.[P]Go to KonKat's:N 1 R 1 L 2 R 1 R 2 R.Switch to plan Q if no one is waiting.Pickup a passenger going to Sunny Skies Park.[Q]Go to Sunny Skies Park:N 1 L 2 L 1 L.N is waiting at Writer's Depot.B is waiting at Writer's Depot.M is waiting at Writer's Depot.NB is waiting at Writer's Depot.BM is waiting at Writer's Depot.NBM is waiting at Writer's Depot.Go to Writer's Depot:N 1 L.Pickup a passenger going to Joyless Park.Pickup a passenger going to Joyless Park.Pickup a passenger going to Joyless Park.Go to Joyless Park:N 3 R 2 R 2 L.Go to Writer's Depot:W 1 R 2 L 2 L.Pickup a passenger going to Joyless Park.Pickup a passenger going to Joyless Park.Pickup a passenger going to Joyless Park.Go to Joyless Park:N 3 R 2 R 2 L.[R]Switch to plan Y if no one is waiting.Pickup a passenger going to Cyclone.0 is waiting at Starchild Numerology.Go to Starchild Numerology:W 1 L 2 R 1 L 1 L 2 L.Pickup a passenger going to Addition Alley.Go to Cyclone:W 1 R 4 L.[S]Pickup a passenger going to Auctioneer School.Go to Zoom Zoom:N.Go to Auctioneer School:W 2 L.Go to Sunny Skies Park:N.Switch to plan V if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 L.Pickup a passenger going to Crime Lab.Pickup a passenger going to Crime Lab.Go to Crime Lab:S 1 L 2 R 2 L.Switch to plan T if no one is waiting.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:N 1 L 1 L.1 is waiting at Starchild Numerology.Go to Starchild Numerology:S 1 R 1 L 1 L 2 L.Pickup a passenger going to Addition Alley.Go to Addition Alley:W 1 R 3 R 1 R 1 R.Pickup a passenger going to Addition Alley.Go to Cyclone:N 1 L 1 L.Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:N 2 R.Go to Auctioneer School:W 2 L 1 L.Switch to plan U.[T]Go to Cyclone:N 4 L 2 L.Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:N 2 R 1 L 1 R.Go to Auctioneer School:W 1 L 1 R 2 L 1 L.[U]Pickup a passenger going to Cyclone.Go to Cyclone:N 4 L.Switch to plan S.[V]Go to Addition Alley:N 1 R 1 R 1 R.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:N 1 R 1 R.Pickup a passenger going to Post Office.Go to Cyclone:N 1 L 1 L 2 R.Pickup a passenger going to Post Office." " is waiting at Writer's Depot.Go to Writer's Depot:S.Pickup a passenger going to Post Office.Go to Post Office:N 1 R 2 R 1 L.Go to Auctioneer School:S 1 R 1 L 1 L.Pickup a passenger going to Tom's Trims.Go to Narrow Path Park:N 3 R 1 R 1 L 1 R.[W]Switch to plan X if no one is waiting.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:W 1 L 1 R 2 L 1 L.Go to Zoom Zoom:N 1 R.Go to Narrow Path Park:W 1 L 1 L 1 R.Switch to plan W.[X]Go to Tom's Trims:E 1 R 4 R 1 L.Go to Joyless Park:N 1 R 1 L 3 R.Switch to plan R.[Y]

Try it online!
This ain't winning me any Code Golf competitions, but this was a nice reminder for me not to write any more complex programs in Taxi. (Sooo many special cases, and sooo much gas management...)
A more commented version can be found here, if you dare.

R, 153 134 118
This got longer really quickly, but hopefully I'll be able to shave a few.  Input is STDIN and output to STDOUT.
Edit Change of tack.  Got rid of the split string and counting parts.  Now I replace the parts with a string one shorter than the part.  The difference between the string lengths is collected for output.
N=nchar;i=scan(,'');for(s in scan(,'',t='NBM BM NB M B N'))cat(paste0(N(i)-N(i<-gsub(s,strtrim('  ',N(s)-1),i)),s),'')

Explanation
N=nchar;
i=scan(,'');                     # Get input from STDIN
for(s in scan(,'',t='NBM BM NB M B N'))  # Loop through patterns
  cat(                           # output
    paste0(                      # Paste together
      N(i) -                     # length of i minus
      N(i<-gsub(                 # length of i with substitution of
        s,                       # s
        strtrim('  ',N(s)-1)     # with a space string 1 shorter than s
        ,i)                      # in i
      ),
      s)                         # split string
  ,'')

Test run
> N=nchar;i=scan(,'');for(s in scan(,'',t='NBM BM NB M B N'))cat(paste0(N(i)-N(i<-gsub(s,strtrim('  ',N(s)-1),i)),s),'')
1: NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM
2:
Read 1 item
Read 6 items
3NBM 8BM 5NB 14M 6B 17N
> N=nchar;i=scan(,'');for(s in scan(,'',t='NBM BM NB M B N'))cat(paste0(N(i)-N(i<-gsub(s,strtrim('  ',N(s)-1),i)),s),'')
1: NBMMBNBNBM
2:
Read 1 item
Read 6 items
2NBM 0BM 1NB 1M 1B 0N
>

Pyth, 19 bytes
jd+Ltl=zc`zd_.:"NBM

This is a mixture of @isaacg's Pyth solution and @xnor's incredible Python trick.
Try it online: Demonstration or Test harness
Explanation
jd+Ltl=zc`zd_.:"NBM   implicit: z = input string
             .:"NBM   generate all substrings of "NBM"
            _         invert the order
  +L                  add left to each d in ^ the following:
         `z             convert z to a string
        c  d            split at d
      =z                assign the resulting list to z
    tl                  length - 1
jd                    join by spaces and implicit print

Julia, 106 97 bytes
b->for s=split("NBM BM NB M B N") print(length(matchall(Regex(s),b)),s," ");b=replace(b,s,".")end

This creates an unnamed function that takes a string as input and prints the result to STDOUT with a single trailing space and no trailing newline. To call it, give it a name, e.g. f=b->....
Ungolfed + explanation:
function f(b)
    # Loop over the creatures, biggest first
    for s = split("NBM BM NB M B N")

        # Get the number of creatures as the count of regex matches
        n = length(matchall(Regex(s), b))

        # Print the number, creature, and a space
        print(n, s, " ")

        # Remove the creature from captivity, replacing with .
        b = replace(b, s, ".")
    end
end

Examples:
julia> f("NBMMBNBNBM")
2NBM 0BM 1NB 1M 1B 0N

julia> f("NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM")
3NBM 8BM 5NB 14M 6B 17N

SAS, 144 142 139 129
data;i="&sysparm";do z='NBM','NB','BM','N','B','M';a=count(i,z,'t');i=prxchange(cats('s/',z,'/x/'),-1,i);put a+(-1)z@;end;

Usage (7 bytes added for sysparm):
$ sas -stdio -sysparm NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM << _S
data;i="&sysparm";do z='NBM','NB','BM','N','B','M';a=count(i,z,'t');i=prxchange(cats('s/',z,'/x/'),-1,i);put a+(-1)z@;end;
_S

or
%macro f(i);i="&i";do z='NBM','NB','BM','N','B','M';a=count(i,z,'t');i=prxchange(cats('s/',z,'/x/'),-1,i);put a+(-1)z@;end;%mend;

Usage:
data;%f(NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM)

Result:
3NBM 5NB 8BM 17N 6B 14M

You can save a couple bytes using cats('s/',z,'/x/') in place of 's/'||strip(z)||'/x/'.

Nice, that was quite a trip back to 139 :)

126 bytes: macro a i="&sysparm";do z='NBM','NB','BM','N','B','M';a=count(i,z,'t');i=prxchange(cats('s/',z,'/x/'),-1,i);put a+(-1)z@;end;%

122: data;i="&sysparm";do z='NBM','NB','BM','N','B','M';a=count(i,z,'t');i=prxchange(cats('s/',z,'/x/'),-1,i);put a+(-1)z@;end;. Since you're already reading from sysparm, you may as well just run it as a data step. And if you're running in batch, you don't need run;.

Since you're using the command line switch -sysparm, you need to add 9 bytes to your score per general code golf rules (number of characters in the switch name + hyphen + space = 9). So using my most recent suggestion, you'd be at 131.

But you could get 129 by using a modern style macro which doesn't read from the command line argument: %macro a(i);i="&i";do z='NBM','NB','BM','N','B','M';a=count(i,z,'t');i=prxchange(cats('s/',z,'/x/'),-1,i);put a+(-1)z@;end;%mend;

Well noted @AlexA. still finding my way through the particulars of the rules

If the -batch and -stdio flags are required for this to work, you need to count those too, unfortunately. But again, you can get around that with a modern style macro.

-batch and -stdio would not be required unless running from the command line.  I will add the count for -sysparm, which makes it 129, equal with the modern style macro.

Python 2, 93 88 89 84 Bytes
Taking the straightforward approach.
def f(n):
 for x in"NBM BM NB M B N".split():print`n.count(x)`+x,;n=n.replace(x,"+")

Call like so:
f("NBMMBNBNBM")

Output is like so:
2NBM 0BM 1NB 1M 1B 0N

You can remove the space after in.

In Python 2, you can convert to a string representation with `x`.

PHP4.1, 92 bytes
Not the shortest one, but what else would you expect from PHP?
To use it, set a key on a COOKIE, POST, GET, SESSION...
<?foreach(split(o,NBMoNBoBMoMoBoN)as$a){echo count($T=split($a,$S))-1,"$a ";$S=join('',$T);}

The apporach is basic:

Split the string into the names of the creatures
Count how many elements there are
Subtract 1 (an empty string would give an array with 1 element)
Output the count and the creature name
Join it all together, using an empty string (which will reduce the string and remove the last creature)

Easy, right?

Perl, 46
#!perl -p
$_="NBM BM NB M B N"=~s/\w+/~~s!$&!x!g.$&/ger

Explanation on how this works?

JavaScript, 108 116 bytes
Just a straight forward approach, nothing fancy
o="";r=/NBM|NB|BM|[NMB]/g;g={};for(k in d=(r+prompt()).match(r))g[d[k]]=~-g[d[k]];for(k in g)o+=~g[k]+k+" ";alert(o);

Does not work: All 6 counts must be shown, separated by spaces, even when they are 0.. Test case: N

@edc65 Woah. I just missed that part. Thanks for pointing that out. Fixed it for the cost of 8chars

C, 205 186 184 bytes
A little different approach based on state machine. where t is the state.
a[7],t,i;c(char*s){do{i=0;t=*s==78?i=t,1:*s-66?*s-77?t:t-4?t-2?i=t,3:5:6:t-1?i=t,2:4;i=*s?i:t;a[i]++;}while(*s++);printf("%dN %dB %dM %dNB %dBM %dNBM",a[1],a[2],a[3],a[4],a[5],a[6]);}

Expanded
int a[7],t,i;

void c(char *s)
{
    do {
        i = 0;
        if (*s == 'N') {
            i=t; t=1;
        }
        if (*s == 'B') {
            if (t==1) {
                t=4;
            } else {
                i=t;
                t=2;
            }
        }
        if (*s == 'M') {
            if (t==4) {
                t=6;
            } else if (t==2) {
                t=5;
            } else {
                i=t;
                t=3;
            }
        }
        if (!*s)
            i = t;
        a[i]++;
    } while (*s++);
    printf("%dN %dB %dM %dNB %dBM %dNBM",a[1],a[2],a[3],a[4],a[5],a[6]);
}

Test function
#include <stdio.h>
#include <stdlib.h>

/*
 * 0 : nothing
 * 1 : N
 * 2 : B
 * 3 : M
 * 4 : NB
 * 5 : BM
 * 6 : NBM
 */
#include "nbm-func.c"

int main(int argc, char **argv)
{
    c(argv[1]);
}

Wouldn't using for(;;*s++){...} instead of do{...}while(*s++); save some bytes? Also, you don't need the newline character in the printf.

I think you meant for(;*s;s++). But I needed to loop with that last null character. Good call on saving the \n, which is not required.

SpecBAS - 164
1 INPUT s$
2 FOR EACH a$ IN ["NBM","BM","NB","M","B","N"]
3 LET n=0
4 IF POS(a$,s$)>0 THEN INC n: LET s$=REPLACE$(s$,a$,"-"): GO TO 4: END IF
5 PRINT n;a$;" ";
6 NEXT a$

Uses the same approach as a lot of others. Line 4 keeps looping over the string (from largest first), replaces it if found.
SpecBAS has some nice touches over original ZX/Sinclair BASIC (looping through lists, finding characters) which I'm still finding out.

C, 146
f(char*s)
{
  char*p,*q="NBM\0NB\0BM\0N\0B\0M",i=0,a=2;
  for(;i<6;q+=a+2,a=i++<2)
  {
    int n=0;
    for(;p=strstr(s,q);++n)*p=p[a>1]=p[a]=1;
    printf("%d%s ",n,q);
  }
}

// Main function, just for testing
main(c,a)char**a;{
  f(a[1]);
}

Haskell - 177 bytes (without imports)
n s=c$map(\x->(show$length$filter(==x)(words$c$zipWith(:)s([f(a:[b])|(a,b)<-zip s(tail s)]++[" "])))++x++" ")l
f"NB"=""
f"BM"=""
f p=" "
l=["N","B","M","NB","BM","NBM"]
c=concat

(Sorry for the internet necromancy here.)
The Haskell Platform doesn't have string search without imports, and I wanted to show off and exploit the fact that the searched strings are all substrings of one (without repetitions), so that grouping characters can be done by identifying pairs that are allowed to follow each other, which is what f does here.
I still need the full list l in the end to check for equality and display exactly as required, but would not, had the challenge only been to report the number of occurrences of the possible words in any order.

Vyxal, 18 bytes
`NBM`KṘ(n/₅‹n+¨…_∑

Try it Online!
`NBM`              # 'NBM'
     K             # Substrings
      Ṙ(           # Iterate over
        n/         # Split current string by current substring of NBM
          ₅‹       # Duplicate and decrement length
            np¨…_  # Prepend current substring of NBM and output with a trailing space
                 ∑ # Concatenate for next iteration

Husk, 27 bytes
;zS`+ös←Lx₁GoΣ`x⁰₁
↔ÖLQ"NBM

Try it online!
uses the splitting technique from the Vyxal answer.
Husk, 28 bytes
m§+osL←k€₁Ẋ`-U¡Ṡ-(→n₁ḣ
Q"NBM

Try it online!
Funny set intersection based idea.

Japt -S, 18 bytes
Outputs in reverse order.
"NBM"ã ÔËiUèDU=rDS

Try it (footer reverses the output)
"NBM"ã ÔËiUèDU=rDS     :Implicit input of string U
"NBM"ã                 :Substrings of "NBM"
       Ô               :Reverse
        Ë              :Map each D
         i             :  Prepend
          UèD          :    Count of D in U
             U=        :    Reassign to U*
               rD      :      Replace D with
                 S     :      Space
                       :Implicit output joined with spaces

*This is done within the second argument of the è method but as that only expects 1 argument, it's result is ignored within the mapping & prepending.

Excel, 149 145 bytes
Saved 4 bytes by realizing I can directly use LEN(a) after I rewrote the function from my first - never submitted - draft.
=LET(a,SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"NBM",1),"BM",2),"NB",3),LEN(a)-LEN(SUBSTITUTE(a,{"N","B","M",3,2,1},))&{"N","B","M","NB","BM","NBM"})

Start by replacing NBM with 1 then BM with 2 and NB with 3. Now we have a string that is as many characters long as they are creatures. One by one, we check the difference between that string's length and it's length with one of the creatures removed. Output is an array of cells.

Bash - 101
I=$1
for p in NBM BM NB M B N;{ c=;while [[ $I =~ $p ]];do I=${I/$p/ };c+=1;done;echo -n ${#c}$p\ ;}

Pass the string as the first argument.
bash nmb.sh MBNNBBMNBM

Explained a bit:
# We have to save the input into a variable since we modify it.
I=$1

# For each pattern (p) in order of precedence
for p in NBM BM NB M B N;do
    # Reset c to an empty string
    c=

    # Regexp search for pattern in string
    while [[ $I =~ $p ]];do
        # Replace first occurance of pattern with a space
        I=${I/$p/ }
        # Append to string c. the 1 is not special it could be any other
        # single character
        c+=1
    done

    # -n Suppress's newlines while echoing
    # ${#c} is the length on the string c
    # Use a backslash escape to put a space in the string.
    # Not using quotes in the golfed version saves a byte.
    echo -n "${#c}$p\ "
done

rs, 275 bytes
(NBM)|(NB)|(BM)|(N)|(B)|(M)/a\1bc\2de\3fg\4hi\5jk\6l
[A-Z]+/_
#
+(#.*?)a_b/A\1
+(#.*?)c_d/B\1
+(#.*?)e_f/C\1
+(#.*?)g_h/D\1
+(#.*?)i_j/E\1
+(#.*?)k_l/F\1
#.*/
#
#(A*)/(^^\1)NBM #
#(B*)/(^^\1)NB #
#(C*)/(^^\1)BM #
#(D*)/(^^\1)N #
#(E*)/(^^\1)B #
#(F*)/(^^\1)M #
\(\^\^\)/0
 #/

Live demo and tests.
The workings are simple but a little odd:
(NBM)|(NB)|(BM)|(N)|(B)|(M)/a\1bc\2de\3fg\4hi\5jk\6l

This creatively uses groups to turn input like:
NBMBM

into
aNBMbcdeBMfghijkl

The next line:
[A-Z]+/_

This replaces the sequences of capital letters with underscores.
#

This simply inserts a pound sign at the beginning of the line.
+(#.*?)a_b/A\1
+(#.*?)c_d/B\1
+(#.*?)e_f/C\1
+(#.*?)g_h/D\1
+(#.*?)i_j/E\1
+(#.*?)k_l/F\1
#.*/

This is the beginning cool part. It basically takes the sequences of lowercase letters and underscores, converts them into capital letters, groups them together, and places them before the pound that was inserted. The purpose of the pound is to manage the sequences that have already been processed.
#

The pound is re-inserted at the beginning of the line.
#(A*)/(^^\1)NBM #
#(B*)/(^^\1)NB #
#(C*)/(^^\1)BM #
#(D*)/(^^\1)N #
#(E*)/(^^\1)B #
#(F*)/(^^\1)M #
\(\^\^\)/0
 #/

The capital letters are replaced by their text equivalents with the associated counts. Because of a bug in rs (I didn't want to risk fixing it and getting disqualified), the empty sequences are converted into (^^), which is replaced by a 0 in the second-to-last line. The very last line simply removes the pound.

KDB(Q), 76 bytes
{" "sv string[-1+count@'enlist[x]{y vs" "sv x}\l],'l:" "vs"NBM NB BM N B M"}

Explanation
                                                   l:" "vs"NBM NB BM N B M"     / substrings
                        enlist[x]{y vs" "sv x}\l                                / replace previous substring with space and cut
              -1+count@'                                                        / counter occurrence
       string[                                  ],'                             / string the count and join to substrings
{" "sv                                                                     }    / concatenate with space, put in lambda

Test
q){" "sv string[-1+count@'enlist[x]{y vs" "sv x}\l],'l:" "vs"NBM NB BM N B M"}"NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM"
"3NBM 5NB 8BM 17N 6B 14M"
q){" "sv string[-1+count@'enlist[x]{y vs" "sv x}\l],'l:" "vs"NBM NB BM N B M"}""
"0NBM 0NB 0BM 0N 0B 0M"

Haskell, 244 bytes
import Data.List
s="NBM"
[]#_=[[]]
a#[]=[]:a#s
l@(a:r)#(b:m)
 |a==b=let(x:y)=r#m in((a:x):y)
 |True=[]:l#m
c?t=length$filter(==t)c
p=["N","B","M","NB","BM","NBM"]
main=getLine>>= \l->putStrLn.intercalate " "$map(\t->show((l#[])?t)++t)p

Some suggestions: You're using p and s only once, so there's no need to give it a name (-> a#[]=[]:a#"NBM", same for p). BTW: words"N B M NB BM NBM" instead of the list of strings saves additional bytes. The import is only for intercalate, it's shorter te re-implement it: ...putStrLn.tail.((' ':)=<<)$map... and get rid of the import. Put the all the guards | in the definition of # in a single line and use 1<2 instead of True: ...#(b:m)|a==b=...l#m|1<2=[]... ...

... ? can be defined shorter with a list comprehension: c?t=sum[1|x<-c,x==t]. Again, you're using ? only once, so use the body directly: ...show(sum[1|x<-l#[],x==t]).

Stax, 18 bytes
â╥)3╨‼!∩╢←◘♀←N╟Ijƒ

Run and debug it

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


text:
Turn over a new leaf
You're given a tree, which in computer science tradition, has the root at the top and leaves at the bottom. The leaf nodes are labelled with numbers. Your goal is to take the special leaf marked -1 and move it up to be the new root.
[3, [[16], -1], [4]]  -->  [[[[4], 3], [16]]]

You can imagine rotating the special leaf to the top and letting the rest of tree hang off of it. Keeping the tree in the plane while rotating it to get the correct left-to-right order of all the branches.
The new tree has all the leaves of the original tree except for -1.
Input:
A tree whose leaves are distinct positive integers, except for one leaf of -1. The root of the tree will have at least two branches coming off.
The input is given as a nested list like [3, [[16], -1], [[4]]] or its string representation. Delimiters are optional and up to you, but adjacent numbers need to be separated.
Output:
Output or print the flipped tree in the same format as your input. The order of the list entries must be correct. In-place modification is fine.
If your input/output is a data type, it must be one that prints in the required format by default. Built-ins that basically do the task for you are not allowed.
Test cases:
>> [3, [[16], -1], [4]]
[[[[4], 3], [16]]]

>> [2, -1]
[[2]]

>> [44, -1, 12]
[[12, 44]]

>> [[[[-1]]], [[[[4]]]]]
[[[[[[[[[4]]]]]]]]]

>> [[1, 2, 3], [4, -1, 6], [7, 8, 9]]
[[6, [[7, 8, 9], [1, 2, 3]], 4]]

>> [9, [8, [7, [6, -1, 4], 3], 2], 1]
[[4, [3, [2, [1, 9], 8], 7], 6]]

The example doesn't seem to line up with the diagram. The 4 has two more brackets around it than the 3, but is diagramed only 1 layer deeper.

CJam, 24 24 22 bytes
l~{):T]{s$}$(+T1+}gW<p

Try it online.
Thanks Dennis for removing 2 bytes.
Explanation
l~          e# Read the input.
{           e# Do:
    ):T     e# Save the last item to T.
    ]       e# Wrap everything else (as an array) and the last item into an array,
    {s$}$   e#   where the one with -1 (having "-" if stringified) is the first item.
    (+      e# Insert the second array into the first array as the first item,
            e#   or just move the -1 to the end if the first item is already -1.
    T1+     e# Check if the array before this iteration ended with -1.
}g          e# Continue the loop if it did't.
W<p         e# Remove the -1 and print.

You can use {s$}$, with sort order reversed. Also, an anonymous function would save one byte over a full program.

@Dennis Thanks. But if it is a function, I guess I'll need an extra [.

Pyth, 26 25 24 23 bytes
L?y.>b1}\-`Jtb.xyahbJ]J

Demonstration. Test Harness.
This defines a function, y, which takes a nested Pyth list as input.
There are three cases to explore in this recursive function, due to the ternary, ?, and the try - except function, .x. In the function, the input is b.
The first case occurs when }\-`Jtb is truthy. This tests whether there is a - in the string representation of tb, the "tail" of b, which is all of b except its first element. tb is also stored in J. Since all labels are positive except for -1, this will be true if and only if the -1 is not in the first element of the list.
In this case, we cyclically right shift b by 1 with .>b1, and then call the function recursively. This ensures that we will progress to the next step with the element containing -1 as the head (first element) of the list.
In the next two cases, the above is falsy, so -1 is in the head of the list.
In the second case, ahbJ does not throw an error. An error will be thrown if and only if hb is an integer. If this is not the case, then hb is a list, and we need to rotate the tree so that the -1 leaf is nearer the root. ahbJ accomplishes this by appending J as a single element at the end of hb, which effectively moves the root of the tree from b to hb.
In the third and final case, an error is thrown. Thus, hb is a single element. Because of the test in the first case, hb must be -1. Thus, we can return the rest of b, namely J, wrapped in a list, namely ]J.

source: Stack Exchange

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

sort: votes


text:
Check if there is an isomorph substring
This question is an extension of Check if words are isomorphs  and copies the first part of it to give the definition of an isomorph.
Two words are isomorphs if they have the same pattern of letter repetitions. For example, both ESTATE and DUELED have pattern abcdca
ESTATE
DUELED

abcdca

because letters 1 and 6 are the same, letters 3 and 5 are the same, and nothing further. This also means the words are related by a substitution cipher, here with the matching E <-> D, S <-> U, T <-> E, A <-> L.
Given two strings X and Y, with X no longer than Y, the task is to determine if there is a substring of Y which is an isomorph with X.
Input: Two non-empty strings of letters from a..zA..Z which one string per line.  This will come from standard input.
Output A substring of the second string which is an isomorph with the first string, if such a thing exists. Otherwise output "No!".
Rules Your code must run in linear time in the total length of the input.
Score Your score is the number of bytes in your code.  Fewest bytes wins.

Example input and output
adca
ddaddabdaabbcc

dabd

Tip
There is at least one not that complicated, practically fast and linear time solution to this problem.

@AlexA. I think someone told me that if you restrict the running time/complexity then it should be code-challenge. I am happy to change it if that is wrong of course.

If the run time is bounded by a rule and does not influence the scoring, code-golf is a better fit than code-challenge.

linear time means it needs to be O(m+n) and not O(m x n) nor O(m x (n-m)) where m, n are length of first and 2nd string?

@someuser Yes it means  O(m+n) .

Are the two input strings of equal length? If not, could you give some examples with their respective outputs?

@BetaDecay See "Given two strings X and Y, with X no longer than Y, the task is to determine if there is a substring of Y which is an isomorph with X."

I think the idea of KMP algorithm should still work. But I'm too lazy to golf a piece of code using 6 arrays together.

Python 2, 338 326 323 321 310 306 297 293 290 289 280 279 266 264 259 237 230 229 226 223 222 220 219 217 (260 238 231 228 225 223 221 220 218 with 0 exit status)
exec'''s=raw_input()
S=[M-s.rfind(c,0,M)for M,c in enumerate(s)]
k=0
j=x=%s
while k<=M+x:
 if S[k]>j<W[j]or S[k]==W[j]:
    k+=1;j+=1;T+=[j]
    if j-L>x:print s[k-j:k];z
 else:j=T[j]
'''*2%('-1;T=[0];W=S;L=M',0)
print'No!'

The algorithm is a variation of KMP, using an index-based test for character matching. The basic idea is that if we get a mismatch at position X[i] then we can fall back to the next possible place for a match according to the longest suffix of X[:i] that is isomorphic to a prefix of X.
Working from left to right, we assign each character an index equal to the distance to the most recent previous occurrence of that character, or if there is no previous occurrence then we take the length of the current string prefix. For example:
MISSISSIPPI
12313213913

To test whether two characters match, we compare indices, adjusting appropriately for indices that are greater than the length of the current (sub)string.
The KMP algorithm becomes a little simplified since we cannot get a mismatch on the first character.
This program outputs the first match if one exists. I use a runtime error to exit in the event of a match, but the code can be easily modified to exit cleanly at the cost of some bytes.
Note: For computing indices, we can use str.rfind (as opposed to my earlier approach using a dictionary) and still have linear complexity, assuming that str.rfind starts searching from the end (which seems the only sane implementation choice) -- for each character in the alphabet, we never have to traverse the same part of the string twice, so there is an upper bound of (size of alphabet) * (size of string) comparisons.
Since the code got fairly obfuscated in the course of golfing, here is an earlier (293 byte) solution that's a bit easier to read:
e=lambda a:a>i<W[i]or a==W[i]
exec('s=raw_input();S=[];p={};M=i=0\nfor c in s:S+=[M-p.get(c,-1)];p[c]=M;M+=1\nW=S;L=M;'*2)[:-9]
T=[0]*L
k=1
while~k+L:
 if e(W[k]):i+=1;k+=1;T[k]=i
 else:i=T[i]
m=i=0
while m+i<M:
 if e(S[m+i]):
    if~-L==i:print s[m:m+L];z
    i+=1
 else:m+=i-T[i];i=T[i]
print'No!'

The e function tests equivalence of characters. The exec statement assigns indices and does some variable initialisations. The first loop processes X for fall back values, and the second loop does the string search.
Update: Here is a version that exits cleanly, at the cost of one byte:
r='No!'
exec'''s=raw_input()
S=[M-s.rfind(c,0,M)for M,c in enumerate(s)]
k=0
j=x=%s
while k<=M+x:
 if S[k]>j<W[j]or S[k]==W[j]:
    k+=1;j+=1;T+=[j]
    if j-L>x:r=k=s[k-j:k]
 else:j=T[j]
'''*2%('-1;T=[0];W=S;L=M',0)
print r

I think you can save a byte by doing python3. r=raw_input vs. r=input saves 4 bytes and the parens on print only cost 3.

@Maltysen thanks for the comment. I didn't consider Python 3 when writing this, but as for cost and savings, there is an additional 2 byte cost since you can't mix spaces and tabs for indentation in Python 3.

@Maltysen just to follow up, the issue is now no longer tabs but brackets for exec.

This is a really great answer! I look forward to seeing it in cjam now :)

Python 3, 401 bytes
import string,itertools
X=input()
Y=input()
x=len(X)
t=[-1]+[0]*~-x
j=2
c=0
while j<x:
 if X[j-1]==X[c]:c+=1;t[j]=c;j+=1
 elif c>0:c=t[c]
 else:t[j]=0;j+=1
s=string.ascii_letters
*b,=map(s.find,X)
for p in itertools.permutations(s):
 m=i=0
 while m+i<len(Y):
  if p[b[i]]==Y[m+i]:
   if~-x==i:print(Y[m:m+x]);exit()
   else:i+=1
  else:
   if-1<t[i]:m+=i-t[i];i=t[i]
   else:i=0;m+=1
else:print("No!")

This is still mostly ungolfed, but I think it should work. The core algorithm is KMP, plus an additional factor which is factorial in the size of the alphabet (which is fine, since the alphabet is constant). In other words, this is/should be one completely impractical linear algorithm.
Here's a few annotations to help with the analysis:
# KMP failure table for the substring, O(n)
t=[-1]+[0]*~-x
j=2
c=0
while j<x:
 if X[j-1]==X[c]:c+=1;t[j]=c;j+=1
 elif c>0:c=t[c]
 else:t[j]=0;j+=1

# Convert each char to its index in a-zA-Z, O(alphabet * n)
s=string.ascii_letters
*b,=map(s.find,X)

# For every permutation of letters..., O(alphabet!)
for p in itertools.permutations(s):
 # Run KMP, O(n)
 m=i=0
 while m+i<len(Y):
  if p[b[i]]==Y[m+i]:
   if~-x==i:print(Y[m:m+x]);exit()
   else:i+=1
  else:
   if-1<t[i]:m+=i-t[i];i=t[i]
   else:i=0;m+=1
else:print("No!")

For testing, you can replace s with a smaller alphabet than string.ascii_letters.

APL (Dyalog), 32 bytes
This is an infix function, taking X as left argument and Y as right argument.
{(s,⊂'No!')⊃⍨(⍳⍨¨s←⍵,/⍨≢⍺)⍳⊂⍳⍨⍺}

Try it online!
{…} anonymous lambda where ⍺ and ⍵ represent the arguments (X and Y)
 ⍳⍨⍺ ɩndex selfie of X (ɩndices of the first occurrence of elements of X in X)
 ⊂ enclose so we can look for that entire pattern
 (…)⍳ ɩndex of first occurrence of that in…
  ≢⍺ tally (length) of X
  ⍵,/⍨ all substrings of that size of Y (lit. concatenation reduction of those, but that is a no-op)
  s← store in s (for substrings)
  ⍳⍨¨ ɩndex selfie of each of those
 now we have the index of the first pattern, or 1 + the number of patterns if no match was found
 (…)⊃⍨ use that index to pick from…
  ⊂'No!' the enclosed string (so that it functions as a single element)
  s, prepended with s

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


text:
Rotate a Chinese checkerboard
A Chinese checkerboard looks like this (based on this question, but this time it has a fixed size):
            G
           . G
          G G G
         G G . G
B B B B . . Y G . Y . Y Y
 B B B . . G . . . Y Y Y
  B . B . . . . . Y . Y
   B . . . . . . . . Y
    . . . . . . . . .
   . P . . . . . O O .
  P P . . . . . . . O O
 P P P . . . R . . O O .
P P P P . . R . . O O O O
         R . R R
          R R R
           R .
            R

Each non-space character in this example can be replaced by any non-space printable ASCII character in the input, while spaces are never changed. Note that it isn't guaranteed to be a valid arrangement in Chinese checker (such as it may not have exactly 7 different kind of characters).
Your task is to rotate it by a multiple of 60 degrees.
This is the above example rotated by 60 degrees clockwise:
            B
           B B
          B B B
         B . B B
P P P . . . B . . G G . G
 P P P P . . . . . G G G
  P P . . . . . G Y . G
   P . . . . . . . G G
    . . . . . . . . .
   R . . . . . . . . Y
  R . R R . . . . Y Y .
 R R R . . . O . . . Y Y
R . R R . . . O . Y Y Y Y
         O O O .
          O O O
           O .
            O

The input is a non-negative integer and a Chinese checkerboard. Your program (or function) should rotate it by the integer * 60 degrees. You decide whether to rotate clockwise or counterclockwise, as long as it is consistent. Both the input and output shouldn't have extra leading or trailing spaces.
This is code-golf. Shortest code wins.

CJam, 61 59 43 40 38 36 bytes
{{_N/eeSf.*:sW%zsS-\{_' >{;(}&+}/}*}

This is an anonymous function that expects a string and an integer on the stack.
Thanks to @jimmy23013 for golfing off 19 bytes.
Try it online in the CJam interpreter.
Idea
We can assign an order to the printable characters of the checkerboards by reading them eastwards, then southwards.
This way, the original and rotated checkerboard
            G                                  B
           . G                                B B
          G G G                              B B B
         G G . G                            B . B B
B B B B . . Y G . Y . Y Y          P P P . . . B . . G G . G
 B B B . . G . . . Y Y Y            P P P P . . . . . G G G
  B . B . . . . . Y . Y              P P . . . . . G Y . G
   B . . . . . . . . Y                P . . . . . . . G G
    . . . . . . . . .                  . . . . . . . . .
   . P . . . . . O O .                R . . . . . . . . Y
  P P . . . . . . . O O              R . R R . . . . Y Y .
 P P P . . . R . . O O .            R R R . . . O . . . Y Y
P P P P . . R . . O O O O          R . R R . . . O . Y Y Y Y
         R . R R                            O O O .
          R R R                              O O O
           R .                                O .
            R                                  O

become
G.GGGGGG.GBBBB..YG.Y.YYBBB..G...YYYB.B.....Y.YB........Y..........P.....OO.PP.......OOPPP...R..OO.PPPP..R..OOOOR.RRRRRR.R

and
BBBBBBB.BBPPP...B..GG.GPPPP.....GGGPP.....GY.GP.......GG.........R........YR.RR....YY.RRR...O...YYR.RR...O.YYYYOOO.OOOO.O

respectively.
We can find the second sequence in the first checkerboard by reading its characters northeastwards, then southeastwards.
To achieve this in code, we start by prepending n - 1 spaces to the nth row of the checkerboard (shown on the left). Then, we reverse the order of the rows (shown on the right).
            G                                                       R
            . G                                                   R .
            G G G                                               R R R
            G G . G                                           R . R R
    B B B B . . Y G . Y . Y Y                       P P P P . . R . . O O O O
      B B B . . G . . . Y Y Y                       P P P . . . R . . O O .
        B . B . . . . . Y . Y                       P P . . . . . . . O O
          B . . . . . . . . Y                       . P . . . . . O O .
            . . . . . . . . .                       . . . . . . . . .
            . P . . . . . O O .                   B . . . . . . . . Y
            P P . . . . . . . O O               B . B . . . . . Y . Y
            P P P . . . R . . O O .           B B B . . G . . . Y Y Y
            P P P P . . R . . O O O O       B B B B . . Y G . Y . Y Y
                      R . R R                       G G . G
                        R R R                       G G G
                          R .                       . G
                            R                       G

Finally, we transpose rows with columns:

            B

           BB

          BBB

         B.BB

    PPP...B..GG.G

    PPPP.....GGG

    PP.....GY.G

    P.......GG

    .........

   R........Y

  R.RR....YY.

 RRR...O...YY

R.RR...O.YYYY

OOO.

OOO

O.

O

The whitespace is all over the place, but the printable characters are in the correct order if we read them eastwards, then southwards.
All that's left to do is replacing the nth printable character of the original checkerboard by the nth printable character of the last modification.
Code
                                   e# Stack: String B, Integer A
{                               }* e# Repeat A times:
 _N/                               e#   Push a copy of B and split it at linefeeds.
    ee                             e#   Enumerate the lines of B.
      Sf.*:s                       e#   Execute S.*s for each line:
                                   e#     [4 "abc"] -> "    abc"
            W%                     e#   Reverse the order of line lines.
              z                    e#   Zip; transpose rows with columns.
               s                   e#   Flatten the arrays of strings.
                S-                 e#   Remove spaces.
                                   e#   This pushes a string L.
                  \{          }/   e#   For each character C in the unmodified B:
                    _' >           e#     Check if C is bigger than ' '.
                        {  }&      e#     If it is:
                         ;(        e#      Discard C and shift out a char from L.
                             +     e#     Append a char (C or from L) to L.
                                   e#  L is B rotated by 60 degrees. Set L := B.

_,,Sf*\.+W%ze_.

@jimmy23013: Much better than my sorting approach. Thanks!

liq{_N/eeSf.*W%:szsS-\{_' >{;(}&\}/;]}@*, but I was thinking of rotating by 60 degrees, not 45 degrees when I was writing this challenge...

@jimmy23013: Wow, thanks! I was try a different approach, but qN/(i{_eeSf.*W%:szSf-{},.{' f+sW<\,' e[}}*N* is even longer than what I had before...

Python 2, 171 bytes
def f(S,n):
 o="";E=enumerate;B=S.splitlines(1)
 for r,l in E(B):
  for c,q in E(l):z=r-8;y=6-(z+c)/2;x=-y-z;exec"x,y,z=-y,-z,-x;"*n;o+=q*(q<"!")or B[z+8][12-y+x]
 print o

This is perhaps the only time I've ever found str.splitlines useful — for all other times, .split("\n") is shorter.
Use like f(S,10).
Explanation
For each char in the input, we either:

Keep it if it's a space or newline, or
Replace it with the correct char otherwise

To figure out which char to replace with, we convert the grid to cube coordinates (x, y, z), rotate n times by transforming (x, y, z) -> (-y, -z, -x), then convert back.


text:
Prime Nerd Sniping Pattern
Longest day of the year - here's something to waste the extra time...

Overview
Note this is not a popularity contest and not a graphical output challenge - you are only required to output a string of 65,536 zeroes and ones. The Stack Snippet at the bottom of the question will display this as a 256 by 256 black and white image and calculate your official score. You can then save the image and upload it to your answer alongside your code (since the string output will not fit in a 30,000 character Stack Exchange answer).

Scoring
The score of an image is the sum of the scores of its individual pixels. The score of an individual pixel is the sum of the subscores for each of the non-orthogonal, prime distance pixels that are of opposite colour to the pixel being scored. The subscore for each such pixel is 1/p where p is the prime distance.
In the context of this question, the terms have the following definitions:

Non-orthogonal: A pixel is non-orthogonal to the pixel being scored if it is not in the same row and is not in the same column.
Prime distance: A pixel is at a prime distance from the pixel being scored if they are separated by a Euclidean distance that is exactly a prime number. In particular, distance is the minimum distance measured toroidally - the top left pixel is a distance of sqrt(2) from the bottom right pixel (all 4 edges wrap).
Opposite colour: A pixel is of opposite colour to the pixel being scored if their values sum to 1. That is, the first is 0 and the second is 1, or the first is 1 and the second is 0.

The Stack Snippet includes example code that shows how to score an image, but does not include any optimisations or an efficient approach, just correct code so scoring of final images can be done consistently.
If anything in the code is not correct, please let me know either in the comments or in chat.
JavaScript may not necessarily be the best language for answering this particular challenge. Note that the Snippet code deliberately gives no clues as to faster approaches. It will only have efficiencies introduced that have already been demonstrated in an existing answer.

Visualisation
The scoring pixels
For an intuitive feel for the distribution of the scoring pixels, here (in purple) are the non-orthogonal prime distance pixels for pixel (128, 128) of a 256 by 256 image:

A random image
This is the randomly generated image from the example Python 3 answer. It has a score of 138,267.64 and gives you something to beat.

Input
The code does not require input.
Output
The code should output a string of 65,536 zeroes and ones, representing the pixels of a black and white 256 by 256 image. The digits should be a continuous string, with no separators. You may find copying and pasting easier if you output to a file, but this is up to you.
Your code may also output other information that you find useful, as long as the string can be copied and pasted into the Stack Snippet. For example, you may wish to output the best yet string to a file and the best yet score to STDOUT at regular intervals, allowing the user to choose when to stop the search.

Stack Snippet
As pointed out by Sp3000, the snippet was taking 10 minutes to calculate a score, which is a little too slow, even for a deliberately inefficient reference implementation. I've edited in Sp3000's suggested improvement of precomputing the pixel offsets for the scoring, and it now takes a few seconds to calculate a score.

canvas = document.getElementById('canvas')
ctx = canvas.getContext('2d')
scoreArea = document.getElementById('scoreArea')
pastedData = document.getElementById('pastedData')
timeout = 0

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499]

primesSquared = []
for (i=0; i<primes.length; i++) {
    primesSquared.push(primes[i] * primes[i])
}

width = canvas.width
height = canvas.height
area = width * height

scoringFilter = calculateScoringFilter()

function calculateScore() {
    var percentage = Math.floor(currentIndex / 65536 * 10000) / 100
    scoreArea.value = 'Calculating:' + percentage + '%'
    for (var t=0; t<1000; t++) {
        if (currentIndex < 65536) {
            partialScore += pixelScore(currentIndex)
            currentIndex += 1
        } else {
            scoreArea.value = 'Score: ' + partialScore
            return
        }
    }

    timeout = setTimeout(calculateScore, 10)
}

function pixelScore(i) {
    var score = 0
    var x = i % width
    var y = Math.floor(i / width)
    var a, b, xd, yd, j, k, d, m
    for (k=0; k<scoringFilter.length; k++) {
        bundle = scoringFilter[k]
        m = bundle[0]
        a = m % width
        b = Math.floor(m / width)
        j = ((x+a) % width) + width * ((y+b) % height)
        d = bundle[1]
        score += Math.abs(pixels[i] - pixels[j]) / d
    }
    return score
}

function display(pixels) {
    for (var i=0; i<area; i++) {
        ctx.fillStyle = pixels[i] ? 'white' : 'black'
        ctx.fillRect(i % width, Math.floor(i / width), 1, 1)
    }
}

function stop() {
    clearTimeout(timeout)
    scoreArea.value = 'Calculation cancelled.'
}

function isPrimeSquared(n) {
    return primesSquared.indexOf(n) > -1
}

function applyToImage() {
    var potentialPixels = []
    var pastedString = pastedData.value
    if (pastedString.length !== 65536) {
        scoreArea.value = 'Incorrect length:' + pastedString.length
        return
    }
    var i, digit
    for (i=0; i<pastedString.length; i++) {
        digit = pastedString.substring(i, i + 1)
        if (digit === '0') {
            potentialPixels.push(0)
        } else if (digit === '1') {
            potentialPixels.push(1)
        } else {
            scoreArea.value = 'Invalid character ' + i + ':' + digit
            return
        }
    }
    pixels = potentialPixels
    display(pixels)
    scoreArea.value = 'Calculating score...'
    partialScore = 0
    currentIndex = 0

    timeout = setTimeout(calculateScore, 10)
}

function calculateScoringFilter() {
    var scoringFilter = []
    var i, x, y, xd, yd
    for (i=0; i<area; i++) {
        x = i % width
        y = Math.floor(i / width)
        xd = Math.min(x,(-x+width)%width)
        yd = Math.min(y,(-y+height)%height)
        dSquared = xd*xd + yd*yd
        if (xd && yd && isPrimeSquared(dSquared)) {
            d = Math.sqrt(dSquared)
            scoringFilter.push([i, d])
        }
    }
    return scoringFilter
}
<canvas id='canvas' width='256' height='256'></canvas>

<input id='scoreArea' rows='1' readonly></input>

<button onclick='applyToImage()'>Apply string to image</button>
<button onclick='stop()'>Stop</button>

Paste in string of 65,536 zeroes and ones here:

<input id='pastedData'></input>

If you use the output or the code of another answer as the starting point for your own code, please remember to give credit and link to the supporting answer. Answers to this question do not need to credit the example answer or the code in the question.
Credit to Randall Munroe for the term Nerd Sniping

CJam, score 276496.9062958626
2,128*_(]128*

It turns out to be optimal, because: There aren't any non-orthogonal pairs with distance 2. So the distance must be odd, and so is the distance squared. As p2=x2+y2, one of x and y (squared or not) must be odd, and the other must be even. Those points are always in the opposite color in this image.
This and its negative are also the only optimal solutions. In an optimal solution, no non-orthogonal, prime distance pixels should have the same color. There are diagonally adjacent opposite pixels like (3,4) and (4,3). By filling pixels of the opposite of opposite color, etc, we can get a diagonal with the same color. Starting from each pixel in the diagonal, we can get all the anti-diagonals filled in the same way. Note that they wrap around. It is still optimal if they don't, though.

I was hoping it would take longer for people to notice that...

It took me a long time to work out that there was an optimal solution when writing this question, so I thought it would be worth posting as a challenge. How did you see it so quickly? Was it just obvious or did you have a particular thought process?

P.S. I don't know what time you saw this question but an optimal solution 71 minutes after the question was posted is deserving of a bounty - I'll just have to wait 2 days before I can assign it...

@trichoplax From your first image, it seemed there are many points in the same diagonal. I was thinking of using wider stripes at the beginning. And then I opened Gimp to verify my idea. And to my surprise, I got a completely black image when I filled it with this pattern.

@trichoplax I think I saw this question only after posting this comment.

So less than 26 minutes - impressive :)

@trichoplax Given that you knew there was an optimal solution, I think you would have been better off revising the question to make it less solvable. Though jimmy23013 found it fast, it's always a matter of time until someone finds it, and then it's over.

@xnor in hindsight I agree. If I post a similar question in future I'll try to establish that it is open ended so that there isn't a definite point where further answers are no longer possible.

I like the explanation. Short but complete.

Python 3, score 138267.64
This is a minimal answer as an example of what is required, and as something to beat...
It includes

The language name.
The score from the Stack Snippet in the question.
The image saved from the Stack Snippet.
The code used to produce the string of 65,536 zeroes and ones.

Output

Code
from random import random

output_string = ''
filename = '65536digits.txt'

for t in range(65536):
    digit = int(random() * 2)
    output_string += str(digit)

with open(filename, 'w') as output_file:
    output_file.write(output_string)

This is just an example. Python may not necessarily be the best language for competitive answers to this particular challenge.


text:
mtDNA mutation tree
Background:
MtDNA is a part of the human DNA that is passed from a mother to a child and it rarely mutates. Since this is true for all humans it is possible to create a huge tree that visualize how all humans are related to each other through their maternal ancestry all the way back to the hypothetical EVE. Every mutation in the MtDNA when a child is born creates a new sub-branch from its parent branch in the tree.
Find out more about Mitochondrial DNA (mtDNA) here: https://en.wikipedia.org/wiki/Mitochondrial_DNA
Objective:

Your program is served a list of mtDNA tree branches mutation count and your program should deliver a tree view of it

Example input and output:
The input is a 3-column semi-colon separated table with a line for each branch. Example:
L0a'b'f'k;L0;14
L0a'b'f;L0a'b'f'k;23
L0;mtEVE;10
L0a'b;L0a'b'f;30
L0a;L0a'b;38
L0a1'4;L0a;39
L0a1;L0a1'4;40
L0a1a;L0a1;42
L0a1a NL;L0a1a;43
L0a1a1;L0a1a NL;44
L0a1a2;L0a1a NL;45
L0a1a3;L0a1a NL;44
L0a1 NL;L0a1;41
L0a1b;L0a1 NL;44
L0a1b NL;L0a1b;45
L0a1b1;L0a1b NL;46
L0a1b1a;L0a1b1;47
L0a1b1a1;L0a1b1a;48
L0a1b2;L0a1b NL;48
L0a1b2a;L0a1b2;50
L0a1c;L0a1 NL;45
L0a1d;L0a1 NL;44
L0a4;L0a1'4;55
L0a2;L0a;47
L0a2a;L0a2;49
L0a2a1;L0a2a;50
L0a2a1a;L0a2a1;51
L0a2a1a1;L0a2a1a;53
L0a2a1a2;L0a2a1a;53
L0a2a2;L0a2a;53
L0a2a2a;L0a2a2;54
L0a2b;L0a2;57
L0a2b1;L0a2b;58
L0a2c;L0a2;60
L0a2d;L0a2;49
L0a3;L0a;53
L0b;L0a'b;48
L0f;L0a'b'f;37
L0f1;L0f;61
L0f2;L0f;41
L0f2a;L0f2;46
L0f2a1;L0f2a;59
L0f2b;L0f2;63
L0k;L0a'b'f'k;39
L0k1;L0k;48
L0k2;L0k;54
L0d;L0;21
L0d1'2;L0d;25
L0d1;L0d1'2;30
L0d1 NL;L0d1;31
L0d1a;L0d1 NL;38
L0d1a1;L0d1a;41
L0d1c;L0d1 NL;39
L0d1c1;L0d1c;45
L0d1c1a;L0d1c1;46
L0d1c1b;L0d1c1;46
L0d1b;L0d1 NL;36
L0d1b1;L0d1b;40
L0d2;L0d1'2;31
L0d2a'b;L0d2;32
L0d2a;L0d2a'b;42
L0d2a1;L0d2a;43
L0d2b;L0d2a'b;46
L0d2c;L0d2;45
L0d3;L0d;39

Your program should output a left-to-right tree view including some numbers based on the input. Based on the example input, this is valid output:
  0│ ┐                                                               mtEVE               [  0][ 63]
 10│ └♦♦♦♦♦♦♦♦♦┬────────────────┬─────────────────────────────────── L0                  [ 10][ 63]
 21│           │                └♦♦♦♦♦♦♦♦♦♦┬──────┬───────────────── L0d                 [ 11][ 46]
 39│           │                           │      └♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦ L0d3                [ 18][ 39]
 25│           │                           └♦♦♦┐                     L0d1'2              [  4][ 46]
 30│           │                               ├♦♦♦♦┬─────────────── L0d1                [  5][ 46]
 31│           │                               │    └┬────┬┐         L0d1 NL             [  1][ 46]
 36│           │                               │     │    │└♦♦♦♦┬─── L0d1b               [  5][ 40]
 40│           │                               │     │    │     └♦♦♦ L0d1b1              [  4][ 40]
 38│           │                               │     │    └♦♦♦♦♦♦┬── L0d1a               [  7][ 41]
 41│           │                               │     │           └♦♦ L0d1a1              [  3][ 41]
 39│           │                               │     └♦♦♦♦♦♦♦┬────── L0d1c               [  8][ 46]
 45│           │                               │             └♦♦♦♦♦┬ L0d1c1              [  6][ 46]
 46│           │                               │                   ├ L0d1c1a             [  1][ 46]
 46│           │                               │                   └ L0d1c1b             [  1][ 46]
 31│           │                               └♦♦♦♦♦┬┬───────────── L0d2                [  6][ 46]
 45│           │                                     │└♦♦♦♦♦♦♦♦♦♦♦♦♦ L0d2c               [ 14][ 45]
 32│           │                                     └┬──┐           L0d2a'b             [  1][ 46]
 42│           │                                      │  └♦♦♦♦♦♦♦♦♦┬ L0d2a               [ 10][ 43]
 43│           │                                      │            └ L0d2a1              [  1][ 43]
 46│           │                                      └♦♦♦♦♦♦♦♦♦♦♦♦♦ L0d2b               [ 14][ 46]
 14│           └♦♦♦┬────────┐                                        L0a'b'f'k           [  4][ 63]
 39│               │        └♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦┬─────┬──────── L0k                 [ 25][ 54]
 48│               │                                 │     └♦♦♦♦♦♦♦♦ L0k1                [  9][ 48]
 54│               │                                 └♦♦♦♦♦♦♦♦♦♦♦♦♦♦ L0k2                [ 15][ 54]
 23│               └♦♦♦♦♦♦♦♦┬──┐                                     L0a'b'f             [  9][ 63]
 30│                        │  └♦♦♦♦♦♦┬───────────┐                  L0a'b               [  7][ 60]
 48│                        │         │           └♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦ L0b                 [ 18][ 48]
 38│                        │         └♦♦♦♦♦♦♦┬────┬─┬────────────── L0a                 [  8][ 60]
 53│                        │                 │    │ └♦♦♦♦♦♦♦♦♦♦♦♦♦♦ L0a3                [ 15][ 53]
 39│                        │                 │    └┬────┐           L0a1'4              [  1][ 55]
 40│                        │                 │     │    └┬────┬──── L0a1                [  1][ 50]
 42│                        │                 │     │     │    └♦┬── L0a1a               [  2][ 45]
 43│                        │                 │     │     │      └┬┐ L0a1a NL            [  1][ 45]
 44│                        │                 │     │     │       │├ L0a1a1              [  1][ 44]
 44│                        │                 │     │     │       │└ L0a1a3              [  1][ 44]
 45│                        │                 │     │     │       └♦ L0a1a2              [  2][ 45]
 41│                        │                 │     │     └┬────┬┐   L0a1 NL             [  1][ 50]
 44│                        │                 │     │      │    │└♦♦ L0a1d               [  3][ 44]
 45│                        │                 │     │      │    └♦♦♦ L0a1c               [  4][ 45]
 44│                        │                 │     │      └♦♦┬───── L0a1b               [  3][ 50]
 45│                        │                 │     │         └┬─┐   L0a1b NL            [  1][ 50]
 46│                        │                 │     │          │ └┬─ L0a1b1              [  1][ 48]
 47│                        │                 │     │          │  └┬ L0a1b1a             [  1][ 48]
 48│                        │                 │     │          │   └ L0a1b1a1            [  1][ 48]
 48│                        │                 │     │          └♦♦┬─ L0a1b2              [  3][ 50]
 50│                        │                 │     │             └♦ L0a1b2a             [  2][ 50]
 55│                        │                 │     └♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦ L0a4                [ 16][ 55]
 47│                        │                 └♦♦♦♦♦♦♦♦┬─┬───┬────┬─ L0a2                [  9][ 60]
 49│                        │                          │ │   │    └♦ L0a2d               [  2][ 49]
 49│                        │                          │ │   └♦┬┬─── L0a2a               [  2][ 54]
 50│                        │                          │ │     │└┬── L0a2a1              [  1][ 53]
 51│                        │                          │ │     │ └┬─ L0a2a1a             [  1][ 53]
 53│                        │                          │ │     │  ├♦ L0a2a1a1            [  2][ 53]
 53│                        │                          │ │     │  └♦ L0a2a1a2            [  2][ 53]
 53│                        │                          │ │     └♦♦♦┬ L0a2a2              [  4][ 54]
 54│                        │                          │ │         └ L0a2a2a             [  1][ 54]
 57│                        │                          │ └♦♦♦♦♦♦♦♦♦┬ L0a2b               [ 10][ 58]
 58│                        │                          │           └ L0a2b1              [  1][ 58]
 60│                        │                          └♦♦♦♦♦♦♦♦♦♦♦♦ L0a2c               [ 13][ 60]
 37│                        └♦♦♦♦♦♦♦♦♦♦♦♦♦┬─┬─────────────────────── L0f                 [ 14][ 63]
 61│                                      │ └♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦ L0f1                [ 24][ 61]
 41│                                      └♦♦♦┬───┬───────────────── L0f2                [  4][ 63]
 46│                                          │   └♦♦♦♦┬──────────── L0f2a               [  5][ 59]
 59│                                          │        └♦♦♦♦♦♦♦♦♦♦♦♦ L0f2a1              [ 13][ 59]
 63│                                          └♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦ L0f2b               [ 22][ 63]

Input: Details
The input table is not sorted in any particular order. If we randomly reorder the input lines, the output should remain the same.
Each line in the input represents a mtDNA tree branch or a hypothetical tree branch. The input table could be any number of lines in length.
Input: Details - Column A (branch name):
The first column is the actual branch name. The name divides the input lines into 2 groups of line types that should be handled different (explained later) from each other:

Type 1: Name consists of any ' or the suffix NL
Type 2: Name doesn't consist of any ' or the suffix NL.

The name can be up to 20 characters in length.
Input: Details - Column B (parent branch name):
The second column contains a pointer to the parent branch name. Several lines (branches) can share the same parent.
There is always exactly 1 distinct parent branch name in the input table that points to a parent that isn't represented among the input lines,
that parent branch name is the root for the tree. In the example input that is the third line pointing to the root: mtEVE.
If the input has more than one root, or endless loops, it is an invalid input.
Input: Details - Column C (# of mutations):
The third column is the total number of mutations that particular branch has had counting from the root. Human mtDNA hasn't mutated more than 100 times
in a single line from the hypothetical maternal root (Human/chimp ancestor EVE), but your program should be able to handle 3 digit # of mutations, up to 999.
From the input you can calculate a branch # of unique mutations by substracting its # of mutations from its parent # of mutations.
Output: Details
Your program should output 1 out of 3 different error messages if the input is invalid according to the input description.

Error message 1, if the input has more than one root: ERROR: Multiple roots
Error message 2, if the input parent pointers loops: ERROR: Endless loop
Error message 3, anything else invalid about the input: ERROR: Invalid input

If the input contains no errors, your program should output the tree according to the following constraints:
Each line consists of 5 parts A, B, C, D, and E:

A: 5 characters, 3 char right-aligned # of mutations, a vertical line character: | and 1 blankspace
B: [max # of mutations] characters wide tree + 1 blankspace
C: 20 characters, left-aligned branch name
D: 5 characters, 3 character right-aligned # of unique mutations for the branch encapsulated between [ and ]. (Unique mutations will be explained below).
E: 5 characters, 3 character right-aligned max # of total mutations for this branch and all child-branches encapsulated between [ and ].

A branch # of unique mutations is the difference in # of mutations the current branch has from the # of mutations its parent branch has. The first line is the root and it should be represented with 0 for # of mutations and # of unique mutations.
Output: Details - line order/sortation
If two or more sub-branches are sharing the same parent, the branches are ordered by the sub-branches maximum # of total mutations in descending order. In our example L0a1'4, L0a3 and L0a2 shares the parent: L0a.
In the tree view the order from top to bottom is, sub-branches maximum # of total mutations within parenthesis: L0a3 (53), L0a1'4 (55), L0a2 (60).
If two or more sub-branches shares the same maximum # of mutations on child branches, they are vertically aligned and branched from their parent from the
same spot, line ordering among those sub-branches is alphabetical.
Output: Details - tree (part B)
The tree should be drawn with the following ascii characters: └, ─, ┬, ┐, ├, │, ♦
The logic of the tree is that all mutations should be represented. A branch from a parent branch: ┬ or ┐ represents 1 mutation. Additional unique mutations on the
same branch are represented by: ♦ and they must be left-aligned and placed before the first sub-branch.
Sub-branches are branched from their parent along the x-axis and the position is determined by the maximum # of mutations among all subsequent child branches.
As hinted before the input has 2 different type of input lines. Type 1 with any ' characters or the NL suffix in the branch name, should not fill the horizontal line to the far right on their line but end with a ┐ on the last sub-branch. In the example it is applied to the following branches:
L0a'b'f'k;L0;14
L0a'b'f;L0a'b'f'k;23
L0a'b;L0a'b'f;30
L0a1'4;L0a;39
L0a1a NL;L0a1a;43
L0a1 NL;L0a1;41
L0a1b NL;L0a1b;45
L0d1'2;L0d;25
L0d1 NL;L0d1;31
L0d2a'b;L0d2;32

Hopefully the example input and output answers any additional questions about how the tree should be drawn, consider it part of the challenge to figure out the logic.
Inspiration
You are welcome to try out my (un-golfed) javascript version for inspiration: http://artificial.se/DNA/mtDNAmutationTree3.html (it lacks error checking, and some statistics is added that is not part of this particular challenge).
A complete mtDNA-tree version [based on http://www.phylotree.org/ mtDNA tree Build 16 (19 Feb 2014)] can be found here:
http://artificial.se/DNA/mtDNAfull.html
The data-file used for the full tree:
http://artificial.se/DNA/mtDNA_full.txt
This is a code-golf challenge.

L0d1 shouldn't be placed before L0d2, according to the sorting rule : "... descending order ..."

L0a1'4 is not (55) but (39), L0a2 is not (60) but (47) ... Could you clarify this ?

L0d1 and L0d2 are both 46, therefor alphabetical order is applied

L0a4 55 and a child of L0a1'4 so maximum mutations for L0a1'4 is 55

I have a few questions: 1) Is this a real project? I have the impression that something like this could be worth actual money. 2) How did you get the example output? 3) Why does part A have 8 characters instead of 5? 4) Why does part D have 6 characters instead of 5? 5) Why does "L0a1 NL" have "4" in part D?

@aditsu 1) Not sure what you mean by 'real project'. Well, I have my own working (un-golfed) 'project' here: http://artificial.se/DNA/mtDNAmutationTree3.html save the input as .txt-file and upload to create a tree. If you make money out of it, please send some to me ;). 2) From my own javascipt application. 3) Bug in my question, accidently added 4 extra blankspaces in front, will fix! 4) Same as 3.

@aditsu 5) Another typo from me, it should read 1 in unique mutations. Will fix!

I have been working on a program to do this all day, but it is unfinished and not golfed at all. I was disheartened when I saw that you already have an ungolfed solution because it means that I probably wasted my day off. Would you give the bounty to an ungolfed answer, or should I stop now? Also, sorry for asking for clarification instead of answering. I am not permitted to comment yet and have no other way to reach Plarsen.

Okay, sorry about that Mike Bufardeci. Bounty goes to first answer, golfed or un-golfed (that is not a copy of my version). I cannot guarantee how other users vote on your answer though, because this is code-golf afterall.

Thanks; 1) I thought maybe some company or university doing research on this stuff needed to analyze data and represent it this way, I guess I was wrong :p @MikeBufardeci should probably be more disheartened that I had my solution >90% finished before I first commented (that's how I knew to ask questions 3-5, especially 5), but anyway, I have to go for a few hours; we'll see what happens :)

I found one more problem: "L0a1 NL" has 45 in part A, should be 41. And another note: the character codes you mentioned for those symbols seem to refer to code page 437; they're totally different in unicode, and missing from ISO 8859-1/2 and Windows-1252

@aditsu You are correct, fixed! Great answer btw, the bounty is yours

Python 3, 925 bytes
Yay, under 1 KB! Probably still room for golfing...
import sys
class L:
 def __init__(x,**k):x.__dict__.update(k)
m={}
def e(x):print('ERROR: '+x);exit()
try:
 for x in sys.stdin:a,b,c=x.split(';');m[a]=L(s=a,p=b,m=int(c),l=0)
except:e('Invalid input')
a=set()
def k(x):
 if x.l<0:e('Endless loop')
 if x.l<1:y=m.get(x.p);x.l=-1;k(y)if y else a.add(x.p);x.l=1
for x in m:k(m[x])
r=L(s=a.pop(),p=0,m=0)
if a:e('Multiple roots')
m[r.s]=r
c={}
def u(x):
 c[x.s]=[m[y]for y in m if m[y].p==x.s];x.x=x.m
 for y in c[x.s]:u(y);x.x=max(x.x,y.x)
u(r)
o=[]
def f(p,x,o=o):
 d=x.m-p.m;j=p.m+r.x-x.x;s=x.s;x.i=len(o);l=sorted(c[s],key=lambda t:(t.x,t.s));q=' '*j+'└'+'♦'*(d-1);z='─'
 if"'"in s or s[-2:]=='NL'or x==r:q+=z*(x.x-l[0].x);z=' '
 o+=list("%3d│ "%x.m+q+z*(r.x-len(q))+' %-20s[%3d][%3d]'%(s,d,x.x)),;j+=5;o[p.i][j]='┐┬'[o[p.i][j]in'─┬']
 for i in range(p.i+1,x.i):o[i][j]='├│'[o[i][j]in' │']
 for y in l:f(x,y)
f(r,r)
print('\n'.join(''.join(x)for x in o))


text:
Covering Array Validator
A covering array is an N by k array in which each element is one of {0, 1, ..., v-1} (so v symbols in total), and for any t columns chosen (so an N x t array) contains all possible v^t tuples at least once. The applications of Covering Arrays range from software and hardware testing, interaction testing, and many other fields. A research question (and which will be a follow-up to this question) is to find the minimal Covering Array of given t,k,and v; an analogue of this would be designing a software system with the minimal number of tests required to test all t-way interactions of the system. Only for t=v=2 is the optimal case known for all k (some values of t and v have some optimal CA designs for one value of k, but this is not the common case).
Here, we focus on validation of Covering Arrays, as this is a very time-consuming process for very large Covering Arrays.
Input: A file that contains the Covering Array. The format is described in Scoring below.
Output: Valid if the input is a valid covering array, and Invalid if it is not.
Goal: in any language you want, write a program that validates if the input is a covering array in the fastest time. I will run programs on my machine, which is a Mac Pro 3.5 Ghz 6-Core Intel Xeon E5 (2013) with 16 GB RAM (1866 MHz).
Rules:

Any language is allowed, as long as it can read from a file, where the filename is given as input.
All you need to print is Valid or Invalid, nothing else.
No third-party libraries; you can only use the libraries/modules that are already built-in to the language.
No use of the Internet for validation (i.e., the validation must be done within the program itself).
You are allowed to have multi-threading/multi-core solutions. However, I will test it on the machine described above.
If your program requires a compilation, describe in your answer what compilation options that you selected (i.e., like g++ -O3 validator.cpp ca.5.6^7.txt).

Scoring: the total score is the total amount of time in milliseconds to produce all of the valid outputs. I will test your program against a number of CAs, and it reports the total amount of time required to execute validation of all sample CAs as input. The CAs will be selected from this link (the text files are provided there, and is linked to from the first link above also).
The format of the files posted there is provided as follows: the first line of the file is N, the name of the file is ca.t.v^k.txt, and the next N rows of the file contain k space-separated integers.
Fastest code (i.e., lowest score) wins!
Edit: after looking at some sample covering arrays on the site, the format is not entirely consistent. If you can change (or provide the file) the format to match the format described above, that would be very helpful.

Lowest score wins, right? I think I understand the requirements, but your challenge would probably benefit from some examples, i.e. at least one valid and one invalid instance.

Although your first link does provide examples. So maybe just point at that once more.

@Oliphaunt Thank you, I'll correct it.

@Ryan is it okay to use the C standard math library (#include <math.h>)? As you probably know, it's a part of the c stdlib, but it was separated from the other parts because it is relatively big ...

@ThomasOltmann Yes that's okay.

If there is a Java answer, are you going to take into account Class Loading, Code Warm-Up and Garbage Collection while doing the performance analysis?

@MT0 those are good considerations. There can be a use of System.currentTimeMillis() before and after the relevant code, and just print how long it took that way. As for garbage collection, we can just make the stack size and heap size large enough.

I am having some troubling understanding covering arrays. If i have a input array with 4 columns i need to check all 2 and 3 column combinations of the 4 column array? So for 2 column arrays there needs to be 00, 01, 10, 11 present and for the 3 column sub arrays there needs to be 000,001,010 ... present atleast once?

@Vajura you have to check all of the t column (t is in the input) combinations - that's all you have to do. By default, you get all t-1, t-2, etc. combinations if you satisfy t.

In the given files, what does a "-" represent in the array? Are we supposed to test for non-rectangular arrays?

@Cain The "-" represents a "don't care" - that is, that entry can be any value from 0 to v-1 and the array is still covering.

So should our code be able to account for that? Would that be a wild-card, or could each "-" only represent one possible val?

@Cain you don't have to (you can set all of those entries to 0 if you want) - but if you want to do so for simplicity, say so in your answer.

I found this and the follow-up minimizing question a few days ago. Do you have any sample times for  rough comparison purposes?

@MaxHaaksman do you mean the accepted answer or validators that I have seen before? In either case, I don't have them, sorry! But the best one for Python I've seen is the accepted answer.

Python solution
Uses multiprocessing package to test validity of each v-set of columns selected from the input matrix.
Download from here.
Run:
$ python main.py ca.t.v^k.txt

This reports one of the CAs (specifically, ca.3.4^19.txt) on the site as Invalid.

It was a bug. Fixed now.

Seems good, looks like it works well! I'll test it for speed later.

@Ryan did you got to test the speed?

I didn't need to as there were no other submissions that worked (and I could test). If there is another submission, I will test and report times. But if I remember correctly, some of the strength 4 arrays took a few seconds for verification.

Is that fast or slow?

Yes because we are essentially doing O(N*v^4) steps for validation.

C, 7.29min for ca.5.4^64.txt on an Intel Core i5-4570 + 8GB ram
Update: Sometimes gives wrong results
I've compiled it with gcc -O3 cav.c -o cav. Simply run it with the CA file's name as first (and only) parameter.
In my case: ./cav ca.2.2^4.txt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

int t, v, k, N; /* initial parameters */
uint16_t *ca; /* The CA */
uint16_t *cia; /* Column index array - the columns we selected to compare */
uint8_t *combos;
int num_combos; /* Size of the combo 'hash map' (see compareColumns()) */

int ipow(int base, int exp) /* basic integer pow function 'stolen' from StackOverflow ;) */
{
    int result = 1;
    while(exp)
    {
        if(exp & 1)
            result *= base;
        exp >>= 1;
        base *= base;
    }
    return result;
}

char compareColumns(int base, int child)
{
    int pos = base, maxpos = k - child, child_dec = child - 1;
    if(child == 0)
    {
        while(pos != maxpos)
        {
            cia[child] = pos++;
            memset(combos, 0, num_combos);
            int rv = 0; /* The offset in the CA for the current row */
            int n;
            for(n = 0; n < N; n++) /* For every row */
            {
                int key = 0; /* This is basically a HashMap key, using the same algorithm that you use for accessing 2D data in a 1D array. */
                int df = 1; /* Dimension factor - needed for the hash-map-key-like algorithm */
                int i;
                for(i = 0; i < t; i++) /* For every selected column */
                {
                    key += df * ca[cia[i] + rv]; /* Calculate the key */
                    df *= v;
                }
                combos[key] = 1; /* Set the 'boolean' at 'key' in the 'hash map' to 1 */
                rv += k;
            }
            if(memchr(combos, 0, num_combos) != NULL) /* If there are still any 0s (any needed combinations that aren't found), exit immediately! */
                return 0;
        }
    }
    else
    {
        while(pos != maxpos)
        {
            cia[child] = pos++;
            if(!compareColumns(pos, child_dec))
                return 0;
        }
    }
    return 1;
}

int main(int argc, char **argv)
{
    /* Fetch user input & allocate memory */
    sscanf(argv[1], "ca.%d.%d^%d.txt", &t, &v, &k);

    FILE *file = fopen(argv[1], "r");
    fscanf(file, "%d", &N);

    int num_vals = k * N, i;
    num_combos = ipow(v, t);

    ca  = (uint16_t*)malloc(num_vals * sizeof(uint16_t));
    cia = (uint16_t*)malloc(t * sizeof(uint16_t));
    combos = (uint8_t*)malloc(num_combos * sizeof(uint8_t));

    for(i = 0; i < num_vals; i++)
    {
        int val;
        fscanf(file, " %d", &val);
        ca[i] = val;
    }
    fclose(file);

    /* The main algorithm implementation */
    if(compareColumns(0, t - 1))
        printf("Valid!\n");
    else
        printf("Invalid!\n");

    /* Free memory */
    free(combos);
    free(cia);
    free(ca);
    return 0;
}

I'll try to explain: I'll begin with compareColumns: if it has children (int child), it goes through (allmost) all the columns and kicks off a new call to compareColumns after each step, which itself then walks from the last position of its parent until the end (minus it's own children) of the CA. However, if the function is called with no children (child = 0), it will take all the selected rows and generate something like a hash map key from it. This key will then be used to set a specific cell of the array combos to 1. At the end, it checks if all cells of 'combos' are 1 (i.e. if all combinations appeared at least once). If all cells are 1, it will proceed. If at least one cell is 0, it will abort immediately and print "Invalid!".

how does your algorithm work like ?

I run into a Segmentation fault: 11 when I ran this (even for small CAs).

@Thomas Oltmann I have an algorithm similar in my head, please try to explain more to avoid putting same algorithm

@Ryan i ran it here with stdin input without using files and gave me this result for ca.2.2^2000.txt:
Success time: 0.68 memory: 2144 signal:0
Valid!

@Agawa001 I figured it out, I was doing a command incorrectly.

I have your code working, but also get a Segmentation fault: 11 when I use larger CAs, such as the one here: http://math.nist.gov/coveringarrays/ipof/cas/t=5/v=6/ca.5.6%5E46.txt.zip

@Ryan Okay, thats interesting: I can't even run my small test CA with debug options enabled, because it seg faults. However, if i compile it with -O3 and no debug options, it works. Seems like my pretty fast algorithm is just waaay too memory wasteful ...

Yes the algorithm actually is very fast on my other machine. I'll try various other options too. Feel free to edit your answer if you find a less memory-intensive version.

@Ryan I'm currently trying to find the most memory wasting arrays via gdb and valgrind. :)

I'm not sure your algorithm is working - I ran it on ca.2.2^126.txt and removed everything but the first 3 rows. There needs to be at least 4 rows in order to be a CA at all, but your program reports it as Valid.

Okay, I'll try to fix it.

@Ryan Fixed it ;)

For some reason, now it is reporting Invalid for the default CAs on the site.

Could you please specify which CAs are reported as Invalid? The CAs I tested were all reported correctly ...

@ThomasOltmann Any one I download, such as http://math.nist.gov/coveringarrays/ipof/cas/t=6/v=2/ca.6.2%5E7.txt.zip. Also, others in the v, t in {5, 6} don't work.

@ThomasOltmann I think I know why - there is no way to get to the return 1 statement in compareColumns.

Fantom
Mostly just a brute force solution, except it does a few preliminary checks ahead of time and uses a binary search to find tuples in each sub-array. I think Fantom optimizes most built in stuff, like the sorts and array manipulations, pretty well under-the-hood. Note: Replaces "-" with : "0" for simplicity.
To Run
Download Fantom from the link in the title, and set up your system variables using instructions here.
Save in a file called isCA.fan
run as fan isCA.fan "pathToFile"
class isCA
{
  public static Void main(Str[] args){

    Int start := Duration.nowTicks;
    //Initialize everything
    path := "file:" + args.first
    params := path.split(File.sep.chars.first).last.split('.')
    t := Int.fromStr(params[1])
    params = params[2].split('^')
    v := Int.fromStr(params[0])
    k := Int.fromStr(params[1])
    StrArray := File(Uri.fromStr(path)).in.readAllLines[1..-1]
    array := StrArray.map |Str line -> Str[]| {line.replace("- ", "0 ")[0..-2].split(' ').map |Str s ->Int| {Int.fromStr(s)}}

    //echo("t: $t\n v: $v\nk: $k")

    //Comparison function
    compare := |Int[] a, Int[] b -> Int| {
      Int i := 0
      result := -1
      done := false
      while(i < a.size - 1 && !done){
        if(a[i] != b[i]){
          result = a[i] <=> b[i]
          done = true
        }
        i++
        if(!done){
          return a[i] <=> b[i]
        }
      }
      return result
    }

    //Basic checks to speed up the Not Valid time
    array = array.sort(compare).unique

    //Each column contains each value
    k.times|Int i|{
      vals := Range(0, v, true).toList
      array.each |Int[] row|{
        vals.remove(row[i])
      }
      if(!vals.isEmpty){ respond(false, start)}
    }

    //umm, I guess I'll start with the brute-force method until I think of something better
    vals := Range(0,v,true).toList
    tuples := permutations(vals)
    temp := [,]
    t.times{ temp.add(1)}
    (k - t).times{ temp.add(0) }
    colBins := permutations(temp).unique

    colBins.each |Int[] bin| {
      //Construct columns
      smallArray := array.map |Int[] row -> Int[]|{
        r := [,]
        row.each |Int a, Int index|{ if(bin[index] == 1){r.add(a)}}
        return r
      }

      tList := tuples.dup
      Int cols := t
      //Binary search the array
      while(cols >= v){
        smallArray.sort(compare)
        found := [,]
        tList.each|Int[] tuple, Int index|{
          Int find := smallArray.binarySearch(tuple, compare)
          //echo("Found $tuple at $find in $smallArray")
          if(find >= 0){found.add(index)}
        }
        //Remove first col and try again
        smallArray = smallArray.map|Int[] a -> Int[]| {return a[1..-1]}
        cols--;
        //ignore tuples we already found
        tList = tList.findAll|Int[] list, Int index -> Bool| {!found.contains(index)}
      }

      if(!tList.isEmpty){
        echo("Cols $bin does not contain $tList")
        respond(false, start)
      }

    }
    respond(true, start)
  }

  private static Void respond(Bool b, Int start){
    if(b) echo("Valid")
    else echo("Not Valid")
    echo("Time: " + (Duration.nowTicks() - start))
    Env.cur.exit
  }

  private static Int[][] permutations(Int[] a){
    result := [,]
    recurse([,], a, result)
    return result
  }

  private static Void recurse(Int[] pre, Int[] a, Int[][] results){
    //echo("Recursing $pre\nwith $a")
    if(a.isEmpty) {
      results.add(pre)
      return
    }

    for(Int i := 0; i < a.size; i++){
      d := a.dup
      d.removeAt(i)
      recurse(pre.dup.add(a[i]), d, results )
    }
  }
}

I can't find a way to install Fantom on Mac OS X.

Ooh, Hmm, never used it on OS X, I'll have to look into that, sorry!