text:
Alphabet cannon
A cannonball is fired so that in the first eyeblink of its flight it ascends by N treetops, during the second eyeblink by N-1 treetops, etc until it reaches the highest point of its trajectory. Then it starts falling by 1, 2, etc treetops per eyeblink until it hits the ground. At the same time the cannonball is moving horizontally with a constant velocity of 1 treetop/eyeblink.
Your task is to draw the trajectory with consecutive letters from the English alphabet. If you run out of letters, start again from 'A'. Write a function or a program. The input is an integer N (1≤N≤15). The output can be a character matrix in any reasonable form, for instance a newline-separated string or a list of strings. Letters can be all lowercase or all uppercase. Extra leading and trailing spaces are allowed. Standard loopholes are forbidden. Shorter code is better.
in:
5
out:
    OP
   N  Q
   M  R
  L    S
  K    T
  J    U
 I      V
 H      W
 G      X
 F      Y
E        Z
D        A
C        B
B        C
A        D

in:
1
out:
AB

Closely related.

Why are O and P in the same level in the example? If I read the spec correctly, it seems it should go up one treetop for P and descend by one for Q.

@Skyler At every tick, the alphabet goes 1 to the right and N vertically. N decreases every tick as well. Between O and P, the tick goes 1 to the right, but 0 up- or down-wards.

@Skyler that depends on where you imagine the ball - in the centre of each letter, or moving from the bottom-left to the top-right point of each vertical block of letters (and later top-left to bottom-right); in either case, I admit there's a bit of discontinuity at the apex, which I ignored for the sake of keeping it easy to golf

Looks like  alphabet cannons are now canon.

What is the maximum n that we need to support?

@DomHastings if it makes any difference for your code: 15 (strictly less than an arbitrary not-too-high power of 2 that I just made up)

@ngn Hah, I was tinkering with @TonHospel's Perl solution and came up with 1 byte less, but it only supports up to 14!

@DomHastings what!? ...diffing and trying to figure out how 14 is special... So, is (A..Z)x9 supposed to return nine copies of the alphabet? I'm not very familiar with Perl. When I tried it, it returned one copy.

Yeah, if you do print((A..Z)x9) you'll get 9 copies. Otherwise it just replicates the result of calling print 9 times. I accept 15 as the maximum though. I'll try and think about other ways to reduce byte count instead! Thanks!

@DomHastings silly me... parentheses, of couse. I don't mind lowering the limit, but I think your improvement for n<=14 is still interesting out-of-the-box thinking and would be appreciated as-is :)

05AB1E, 33 32 29 28 bytes
>*As∍2ä`R)ζRIL£vyε`N·úJ])˜.c

Try it online!
Explanation
>*                             # push input*(input+1)
  As∍                          # take that many characters from the alphabet (with wrap)
     2ä                        # split in 2 parts
       `R)                     # reverse the second part
          ζ                    # zip (gives a list of pairs)
           R                   # reverse
            IL£                # split into parts of sizes equal to [1,2...]
               vy              # for each (part y, index N)
                 ε             # for each pair in that part
                  `N·úJ        # insert N*2 spaces between the characters
                       ]       # end loops
                        )˜     # wrap in a flattened list
                          .c   # format as lines padded to equal length

I feel like Nú» or something like that could be used to print as you go instead of ])~.c

All I could come up with is this implementation here but that's worse by 2 bytes.

Stax, 29 24 bytes
╦'♫ΓqπL⌂δ@╚n>DI∙Q┴òkεwö╔

Run and debug it online
The corresponding ascii representation of the same program is this.
VA*xRr:m|/xH({rix/|1*_%:T)mMm

VA*                             repeat alphabet input times
   xRr:m                        [x ... 1, 1 ... x] where x=input
        |/xH(                   get consecutive substrings of specified sizes
             {           m      map substrings using block
              ix<|1*            reverse string if index<x
                    _%:T)       left-pad to appropriate triangular number
                          Mm    transpose and output

R, 169 163 161 153 150 110 109 bytes
This approach fills in a matrix and then prints the matrix.
Golfed
function(n)write(`[<-`(matrix(" ",M<-2*n,k<-sum(1:n)),cbind(rep(1:M,c(n:1,1:n)),c(k:1,1:k)),LETTERS),1,M,,"")

Thanks @Giuseppe for 153.
Thanks @JDL for 150.
See @Giuseppe's comment for 112, and some edits for 110 now 109. Rip original code.
function(n){a=matrix(" ",M<-2*n,k<-sum(1:n))
Map(function(x,y,z)a[x,y]<<-z,rep(1:M,c(n:1,1:n)),c(k:1,1:k),head(LETTERS,2*k))
cat(rbind(a,"
"),sep="")}

If plotting a valid output then 73 bytes
function(n,k=sum(1:n))plot(rep(1:(2*n),c(n:1,1:n)),c(1:k,k:1),pc=LETTERS)

153 bytes -- your solution printed an extra space at the apex which I fixed, and then I also golfed down a few things. Nice answer!

can you use Map instead of mapply?

@JDL You are right. I always think that Map is a wrapper for lapply instead of mapply. Thanks for 150

This kept bothering me, because I thought there should be a way to index the matrix by row,column pairs directly with [ rather than having to go through mapply (or Map), so I found a way to do that. I also remembered that write exists and can replace cat for 112 bytes!

@Giuseppe My comment about "" didn't work, but with [<-, we can manage to squeeze everything within one line, eliminating the need for some variable definitions. 110 bytes: https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPs7wosyRVIyHaRjdBIzexpCizQkNJQUnH10bXSCtPJ9tGt7g0V8PQKk9TUyc5KTMvRaMotQDI99VJ1sizMtSBymhkg9nZQLaPa0iIa1Cwpo4S0BQdIKn5P03DVPM/AA

Wait, 1 does replace "", 109 now: https://tio.run/##LcmxCsIwFEbhVymZ/ltuwHQsWbuZRbu51KYNhNCrxBR9@1jE7TucXENjdQ27@BIfAqF3jmXFdLN6wnYvOX6gGsXO6q4VTla/9g2mFyL2c5QFeX0e7dhDesP/g/RzOnwexnG4XIkNO2alqAaYE9Uv

@Vlo nicely done! only 10 bytes to go to get this below 100 :)

@Giuseppe If plotting is not against the rules then 73 is possible function(n,k=sum(1:n))plot(rep(1:(2*n),c(n:1,1:n)),c(1:k,k:1),pc=LETTERS)

Python 2, 140 135 133 bytes
lambda n:[' '*(n-j)+chr(~-i%26+65)+'  '*j+chr((n*-~n-i)%26+65)for i,j in zip(range(n*-~n/2,0,-1),sum([-~i*[i]for i in range(n)],[]))]

Try it online!

MATL, 29 bytes
,G:tPY"tf1Y2y@?tn+P])Z?]Pv1X!

Try it online!
How it works
,        % Do twice
  G:     %   Push [1 2 ... n], where n is the input
  tP     %   Duplicate, flip: pushes [n n-1 ... 1]
  Y"     %   Run-length decoding: gives vector with n ones, n-1 twos ... (*)
  tf     %   Duplicate, find: gives [1 2 3 ... n*(n-1)/2] (**)
  1Y2    %   Push string 'ABC...Z'
  y      %   Duplicate from below: pushes [1 2 3 ... n*(n-1)/2]  again
  @?     %   If we are in the second iteration
    tn   %     Duplicate, length: pushes n*(n-1)/2
    +    %     Add: gives [n*(n-1)/2+1 n*(n-1)/2+2 ... n*(n-1)*2]
    P    %     Flip: gives [n*(n-1)/2 n*(n-1)/2-1 ... n*(n-1)/2+1]
  ]      %   End if
  )      %   Index (1-based, modular) into the string. Gives a substring
         %   with the letters of one half of the parabola (***)
  Z?     %   Sparse: creates a char matrix with the substring (***) written
         %   at specified row (*) and column (**) positions. The remaining
         %   positions contain char(0), which will be displayed as space
]        % End do twice. We now have the two halves of the parabola, but
         % oriented horizontally instead of vertically
P        % Flip the second half of the parabola vertically, so that the
         % vertex matches in the two halves
v        % Concatenate the two halves vertically
1X!      % Rotate 90 degrees, so that the parabola is oriented vertically.
         % Implicitly display

C, 184 bytes
i,j,k,l,m,h,o;f(n){char L[o=n*n][n*3];for(i=o;i--;)for(L[i][j=n*2]=h=k=0;j--;)L[i][j]=32;for(m=n;!h|~i;m-=1-h*2)for(h+(l=m)?++j:++h;l--;)L[h?i--:++i][j]=65+k++%26;for(;o--;)puts(L+o);}

Try it online!
Unrolled:
i, j, k, l, m, h, o;
f(n)
{
    char L[o=n*n][n*3];

    for (i=o; i--;)
        for (L[i][j=n*2]=h=k=0; j--;)
            L[i][j] = 32;

    for (m=n; !h|~i; m-=1-h*2)
        for (h+(l=m)?++j:++h; l--;)
            L[h?i--:++i][j] = 65 + k++%26;

    for (; o--;)
        puts(L+o);
}

interesting, I can't compile this (there's no main) but TIO can

@ngn It's just a function, you need to add the main to compile it. On TIO, the main is in the footer section.

Java (OpenJDK 8), 121 bytes
n->{for(int l=n*++n/2,r=l,i=1,j=0;l>0;j=j-->0?j:i++)System.out.printf("%"+(n-i)+"c%"+(2*i-1)+"c%n",--l%26+65,r++%26+65);}

Try it online!
Explanation
n->{                             // int-accepting consumer
 for(                            //  loop
   int l=n*++n/2,                //    declare l (left) is the first character to print.
                                 //              Oh, and n is increased to reduce byte count later.
       r=l,                      //            r (right) is the second character to print.
       i=1,                      //            i is the "outer-loop" index
       j=0;                      //            j is the "inner-loop" index
   l>0;                          //    while there are characters to print
   j=j-->0?j:i++)                //    simulate two loops in one,
                                 //      where j starts from 0 and always decreases until it reaches 0
                                 //      at which point j is reset to i and i is increased
  System.out.printf(             //   Print...
   "%"+(n-i)+"c%"+(2*i-1)+"c%n", //    2 characters
                                 //    - the first with n-i-1 whitespaces (remember, n was increased)
                                 //    - the second characters with 2*i-2 whitespaces
   --l%26+65,                    //    the first character to print is the left one, we decrease it.
   r++%26+65                     //    the second character to print is the right one, we increase it.
  );                             //
                                 //  end loop
}                                // end consumer

Charcoal, 33 31 bytes
≔⁰ηＦ…±Ｎ⊕θ«¿ι→↓Ｆ↔ι«Ｐ§αη≦⊕η¿›ι⁰↓↑

Try it online! Link is to verbose version of code. Edit: Saved 2 bytes thanks to @ASCII-only. Explanation:
≔⁰η

Initialise the current letter as an index into the uppercase alphabet to 0.
Ｆ…±Ｎ⊕θ«

Make a loop from the negation of the input to the input inclusive.
¿ι→↓

Normally each column is to the right of the previous. However, there is no column for zero. Instead, a correction is needed to ensure that the left and right sides align.
Ｆ↔ι«

Loop for each letter in the column.
Ｐ§αη

Print the current letter.
≦⊕η

Increment the letter index.
¿›ι⁰↓↑

Move up or down depending on which side of the trajectory we're on.

Seems like there could be a shorter way to do this but not sure how :/

31 bytes

Clojure, 417 319 bytes
(defn cannon[n](let[a(map #(char(+ 65 %))(iterate #(if(> % 24)0(inc %))0))m1(reverse(reduce #(concat %(repeat %2(- n %2)))[](range 0(inc n))))p1(map-indexed #(str(apply str(repeat %2 " "))(nth a %))m1)m2(reverse(reduce #(concat %(repeat %2(-(* 2 %2)2)))[](reverse(range 0(inc n)))))p2(reverse(map-indexed #(str(apply str (repeat %2 " "))(nth a(+(count p1)%)))m2))](doseq[x(reverse(map #(str % %2)p1 p2))](println x))))

At some point I got tangled up in reverse calls and gave up on the idea to make it as short as possible. I just wanted to have a working solution. Here you go...
Sort of ungolfed
(defn cannon [n]
  (let [a (map #(char (+ 65 %)) (iterate #(if (> % 24) 0 (inc %)) 0))
        m1 (reverse (reduce #(concat % (repeat %2 (- n %2))) [] (range 0 (inc n))))
        p1 (map-indexed #(str (apply str (repeat %2 " ")) (nth a %)) m1)
        m2 (reverse (reduce #(concat % (repeat %2 (- (* 2 %2) 2))) [] (reverse (range 0 (inc n)))))
        p2 (reverse (map-indexed #(str (apply str (repeat %2 " ")) (nth a (+ (count p1) %))) m2))]
    (doseq [x (reverse (map #(str % %2) p1 p2))] (println x))))

Update
Motivated by Olivier's comment, I managed to cut multiple reverse calls and apply some general golfing tricks to cut characters. Also I created aliases for reverse, map-indexed, concat, repeat and str because I used them multiple times each.
(defn c[n](let[a(map #(char(+ 65 %))(iterate #(if(> % 24)0(inc %))0))k #(reduce %[](range 0(inc n)))r #(apply str(repeat % " "))rv reverse m map-indexed c concat t repeat s str p(m #(s(r %2)(nth a %))(rv(k #(c %(t %2(- n %2))))))](rv(map #(s % %2)p(rv(m #(s(r %2)(nth a(+(count p)%)))(k #(c %(t %2(-(* 2 %2)2))))))))))

Ungolfed
(defn c [n]
  (let [a (map
           #(char (+ 65 %))
           (iterate
            #(if (> % 24) 0 (inc %))
            0))
        k #(reduce
            %
            []
            (range 0 (inc n)))
        r #(apply str (repeat % " "))
        rv reverse
        m map-indexed
        c concat
        t repeat
        s str
        p (m
           #(s
             (r %2)
             (nth a %))
           (rv (k #(c % (t %2 (- n %2))))))]
    (rv
     (map
      #(s % %2)
      p
      (rv
       (m
        #(s
          (r %2)
          (nth a (+ (count p) %)))
        (k #(c % (t %2 (- (* 2 %2) 2))))))))))

Creates the function c which accepts the value n and returns a list of lines.

This is not an answer as there is apparently no attempt to golf at all (you even say so).

Okay, this is much better! ;-)

Perl 5, -n 112 92 90 88 bytes
For once the terribly long printf seems to win.
#!/usr/bin/perl -n
$p=$q=$_*($%=$_+1)/2;map{printf"%$%c%$.c
",--$p%26+65,$q++%26+65for--$%..$';$.+=2}//..$_

Try it online!

Nice improvement! I was trying to get (A..Z)x9 to work, but it was just too short of the limit! Had that for 91 only. :)

@DomHastings Yours was a nice try at synergy between the two almost repeated letter calculations. That one irks me too.

Python3 + numpy, 124 115
from pylab import*
def i(N):
 x=zeros((N,2*N),'U');x[r_[N-1:-1:-1,0:N],r_[:2*N]]=map(chr,r_[0:2*N]%26+65)
 return x

This creates an appropriately sized array, finds the indices for the trajectory and assigns the appropriate character to them.
The most complex part is generating the characters A-Z, which relies on a very hackish cast of numbers to a string type.
The returned object is a unicode array.
Edit: Saved 9 bytes replacing numpy code that generated the characters A-Z ((r_[0:2*N]%26+65).view('U1')[::2]) with map, as suggested here.

Python 3, 139 136 bytes
f=lambda n,o=0:n and'\n'.join([f(n-1,o+n).replace('\n','\n ')]+[chr(65+(n+o+~i)%26)+'  '*~-n+chr(65+(n*n+o+i)%26)for i in range(n)])or''

Try it online!
Generates each layer recursively, given the size and offset.
-3 bytes thanks to Jo King

@JoKing Thanks, I always forget about the ~ operator!

You can also change n and ... or'' to n*' 'and ... for another byte

J, 78 75 bytes
(26{.65|.a.)($~#)`(;/@])`(' '$~1+{:@])}i.@+:(,.~(|.,])@i.@-:@#)@#~1+i.@-,i.

Try it online!
-3 thanks to ngn

(,|.)@i.@- -> i.@-,i.

Thanks @ngn.  This is one of those where it felt like there should be a solution in 40-50 bytes, but if there is I wasn't able to see it....

Python 2, 182 bytes
I=input()
S=list('ZYXWVUTSRQPONMLKJIHGFEDCBA'*I)
R=range
print zip(*[(' '*(sum(R(abs(i))))+eval('S.pop()+'*abs(i)+"''")[::[-1,1][i>0]]).ljust(sum(range(I+1)))for i in R(-I,I+1)if i])

Try it online!
Returns list of lists of chars.
Primitive verification here

Jelly, 35 bytes
ṪṚṭ
r1m0RØAṁs⁸U2¦Ç⁶ṁ$;¥\€ÇzZ¥€⁶ẎUZY

Try it online!

Ruby, 106 103 bytes
->n,f=2*s=-~n*n/2-1{l=*?A..?Z;(1..n).map{|i|i.times{puts' '*(n-i)+l[(f-s)%26]+' '*~-i*2+l[(s+=1)%26]}}}

Try it online!

Yabasic, 125 bytes
An basic solution that uses graphics mode to print the characters at the correct column and row of the screen.
Input""n
Clear Screen
For i=-n To n
For j=1To Abs(i)
k=i>0
?@(i+n-k,(i^2-i)/2+j-2*j^(!k)+k)Chr$(c+65)
c=Mod(c+1,26)
Next
Next

Because this solution uses graphics mode, it cannot be executed on TIO.
Output
Below is the output for input 7

QBasic 1.1, 124 bytes
Takes input and shoots a cannon. Due to screen size limitations, \$n\$  must be \$\leq 6\$.
INPUT n
CLS
FOR i=-n TO n
FOR j=1TO ABS(i)
k=i>0
LOCATE(i^2-i)/2+j-2*j^-(k=0)-k+1,i+n+k+1
?CHR$(c+65)
c=(c+1)MOD 26
NEXT j,i

Python 3, 190 bytes
j,r,c,s=int(input()),range,[],[];a=(j+1)*j;b=a//2
for i in r(j):k=i+1;c.extend([j-k]*k)
for i in r(a):s+=chr(ord('A')+(i%26))
for i in r(b):print(' '*c[i]+s[b-i-1]+' '*(2*(j-c[i]-1))+s[b+i])

Try it online!
I tried my best. Let me know if any optimisations are possible.

k4, 76 71 bytes
{+|:'p$(-k,|k:+\l)$(x#b),|:'x_b:(i:-1_0,+\l,|l)_a:(2*p:+/l:|1+!x)#.Q.a}

some rearranging+assignments to save 5 bytes

{+|:'(+/l)$(-k,|k:+\l)$(x#i_a),|:'((-x)#i:-1_0,+\l,|l)_a:(2*+/l:|1+!x)#.Q.a}

half-hour effort with some effort to shave off a few bytes, but there's probably much more that can be done here. will come back to it. fun challenge!


text:
Counting Sheep to Fall Asleep
Most people are familiar with the trope about counting sheep to fall asleep. There's a herd of sheep, some of them jumping over a fence, and you count the sheep as they jump. Supposedly, this helps quiet your mind and gets you into a sleep-like state so that you'll fall asleep.
Here's an ASCII sheep facing to the right, waiting to be counted:
'00^>
 ||

Here's an ASCII sheep jumping over a fence:
'00^>
 /\
 ++

Here's one facing to the left, having already been counted:
<^00'
  ||

The Challenge
Given two input integers, n and m, with n > 2 describing how many sheep total, and m > 0 saying how many sheep have already been counted, output an ASCII art representation of counting sheep to fall asleep.
Now for the twist:

Due to the size of the pens the sheep are in, the top row can only hold a maximum of 10 sheep, not counting the currently jumping sheep which must also always be in the top row.
The subsequent rows cannot have the sheep outside their respective pens (you can't have more sheep on the left in the second row than you do in the first row, and same for the right).
If there are 11 or more total sheep, the top row must have 10 plus the jumping sheep in it.
Leading/trailing whitespace, and whitespace between the sheep doesn't matter, so long as:

There is a minimum of one whitespace character between sheep
All the characters line up appropriately.

So long as these rules are met, the actual arrangement of the sheep is up to your implementation.
Examples
For example, here is n=3 and m=1, the simplest case.
         '00^>
'00^>     /\      <^00'
 ||       ++        ||

Here is n=11 and m=6, the most sheep that can fit on one horizontal line.
                        '00^>
'00^> '00^> '00^> '00^>  /\   <^00' <^00' <^00' <^00' <^00' <^00'
 ||    ||    ||    ||    ++     ||    ||    ||    ||    ||    ||

Here's a different example of that, with n=11 and m=1
                                                      '00^>
'00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^>  /\   <^00'
 ||    ||    ||    ||    ||    ||    ||    ||    ||    ++     ||

A bigger example with n=30 and m=12
                                                '00^>
'00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^>  /\   <^00' <^00'
 ||    ||    ||    ||    ||    ||    ||    ||    ++     ||    ||

'00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^>       <^00' <^00'
 ||    ||    ||    ||    ||    ||    ||    ||           ||    ||

'00^>                                                 <^00' <^00'
 ||                                                     ||    ||

                                                      <^00' <^00'
                                                        ||    ||

                                                      <^00' <^00'
                                                        ||    ||

                                                      <^00' <^00'
                                                        ||    ||

Here's an example with n=17 and m=2
                                                '00^>
'00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^>  /\   <^00' <^00'
 ||    ||    ||    ||    ||    ||    ||    ||    ++     ||    ||

'00^> '00^> '00^> '00^> '00^> '00^>
 ||    ||    ||    ||    ||    ||

Here's an example with n=19 and m=3
                                          '00^>
'00^> '00^> '00^> '00^> '00^> '00^> '00^>  /\   <^00' <^00' <^00'
 ||    ||    ||    ||    ||    ||    ||    ++     ||    ||    ||

'00^> '00^> '00^> '00^> '00^> '00^> '00^>
 ||    ||    ||    ||    ||    ||    ||

'00^>
 ||

Note that all of these are examples. For the last one, you may wind up creating a vertical array of sheep on the right-hand side, which will allow the left hand side to fit onto two rows instead. Or maybe a 2x2 square of sheep on the right-hand side, which would also fit the left-hand side sheep onto two rows. Etc.
I/O and Rules

Input can be taken in any reasonable format and by any convenient method.
Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Output can be to the console, returned as a list of strings, returned as a single string, etc.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

@Rod I added a bigger example, but note that it's only an example and your output could be different.

Related.

Recommended test case: n=11 and m=9

@Adám There can be 10 test cases for n=11 such that 0<m<=10. This forces you to have all the sheep on the top row and a dynamic number of sheep on the left (n-1-m) and right (m) of the fence and cannot use fixed pen sizes.

@MT0 True, but one or two test cases should be enough to show that a solution works.

@Adám There exist two n=11 test cases already. Do more test cases actually add anything at this point?

@AdmBorkBork Yes, you don't have a case with less than 9 waiting but plenty of already counted. The two answers so far failed on such cases.

@AdmBorkBork I changed your formatting slightly to "prettify" the part that used 1) and 2). Feel free to roll it back.

Also related.

APL (Dyalog Unicode), 118 bytesSBCS
Anonymous infix lambda. Takes n as left argument and m as right argument. Returns a nested array result, but the default display of this nested array follows specifications. Uses up to nine columns for counted sheep and remaining columns for waiting sheep.
{(r⍴(×/r←d,⍨⌈w÷d←10-⍵⌊⊢/r)↑w⍴(w←⍺-⍵+1)⍴⊂s@2⌽S)(↑(s←'>',⍨¯1↓b)' /\' ' ++')(r⍴(×/r←9,⍨⌈⍵÷9)↑⍵⍴⊂S←⌽↑''(b←'''00^<')' ||')}

Try it online!
{…} anonymous lambda; ⍺ is left argument, ⍵ is right argument
This function has three distinct parts: Waiting, Jumping, and Counted. Each one is parenthesised, causing the result to be a three-element list.
Counted (r⍴(×/r←9,⍨∘⌈⍵÷9)↑⍵⍴⊂S←⌽↑''(b←'''00^<')' ||')
''(…)' ||' the three lines of a mirrored counted sheep, the middle one being:
 b←'''00^<' the body and is assigned to b
↑ mix the list of strings into a character matrix (padding with spaces)
⌽ mirror that
S← assign to S (big Sheep)
⊂ enclose it so we can deal with it as a unit
⍵⍴ use the number of counted sheep to cyclically reshape that
(…)↑ take the following number of elements from that (padding with prototypical items, i.e. the same array but with all characters replaced by spaces)
 ⍵÷9 a ninth of the number of counted sheep
 ⌈ round up
 9,⍨ append 9 to that
 r← assign to r (what we will reshape with; rows and columns)
 ×/ product of that list (this is how many elements we need, including fills)
r⍴ reshape that to an array with the dimension lengths r
Jumping (↑(s←'>',⍨¯1↓b)' /\' ' ++')
(…)' /\' ' ++' the three lines of a jumping sheep, the first one being:
 ¯1↓b drop the last character from b
 '>',⍨ append a right-facing head
 s← store in s (small sheep)
↑ mix the list of strings into a character matrix (padding with spaces)
Waiting (r⍴(×/r←d,⍨⌈w÷d←10-⍵⌊⊢/r)↑w⍴(w←⍺-⍵+1)⍴⊂s@2⌽S)
⌽S mirror S
s@2 put s at line 2 of that (replacing the current data there)
⊂ enclose it so we can deal with it as a unit
(…)⍴ cyclically reshape that to the following size:
 ⍵+1 the number of counted sheep plus one
 ⍺- subtract that from the total
 w← assign to w (waiting)
(…)↑ take the following number of elements from that (padding with prototypical items)
 ⊢/r the rightmost element of r (i.e. the number of used columns for counted sheep)
 ⍵⌊ the minimum of total and that
 10- subtract that from ten
 d← assign to d (difference; missing columns)
 w÷ divide w by that
 ⌈ round up (gives number of needed rows)
 d,⍨ append d
 r← assign to r (what we will reshape with; rows and columns)
 ×/ product of that list (this is how many elements we need, including fills)
r⍴ reshape that to an array with the dimension lengths r

@WeijunZhou You're right, will fix.

I was wondering how the heck I would answer this challenge. I guess that's how :p

@WeijunZhou Fixed.

"Always reserves nine columns for waiting sheep and a single column for counted sheep." Does this work for n=11,m=9 and the rule "the top row must have 10 plus the jumping sheep in it."?

Javascript, 281, 293, 288 Bytes
a="      ";c=((n,m)=>{b="";for(i=0;i<(q=m>(o=(l=(t=n-m-1)?t:0)/9)?m:o);++i){for(j=0;j<3;++j){b+=[a,"'00^> "," ||   "][j].repeat(r=l>i*9?(z=o-i)>1?9:Math.ceil(z*9):0)+a.repeat((l>9?9:l)-r)+(i?"     ":["'00^>"," /\\  "," ++  "][j])+[a," <^00'","   || "][j].repeat(m>i?1:0)+"\n"}}return b});

Be careful when using the below snippet, there's a heavy risk of sudden induced narcolepsy.

  <form id="form">
    <input type="text" name="n" placeholder="n (sheep total)">
    <input type="text" name="m" placeholder="m (sheep in right hand field)">
    <button type="submit">Let's Go!</button>
  </form>

  <pre id="output">
  </pre>

  <script>
    a="      ";c=((n,m)=>{b="";for(i=0;i<(q=m>(o=(l=(t=n-m-1)?t:0)/9)?m:o);++i){for(j=0;j<3;++j){b+=[a,"'00^> "," ||   "][j].repeat(r=l>i*9?(z=o-i)>1?9:Math.ceil(z*9):0)+a.repeat((l>9?9:l)-r)+(i?"     ":["'00^>"," /\\  "," ++  "][j])+[a," <^00'","   || "][j].repeat(m>i?1:0)+"\n"}}return b});
      form.addEventListener("submit", function(e){
        e.preventDefault();

        var n = parseInt(form.n.value);
        var m = parseInt(form.m.value);

        if(n != NaN && m != NaN){
          if(m > n){
            output.innerText = "C'mon man, how can you have more sheep in the right hand field than there are sheep in general?";
          }
          else{
            output.innerText = c(n, m);
          }
        }
        else{
          output.innerText = "Numbers only please.";
        }
      });
    </script>

This shows 4 counted sheep for n=50, m=3 and also has misaligned sheep for n=20, m=3. Also n=20, m=1 shows 2 counted sheep.

Fixed those errors. Also found some sheep were escaping due to rounding errors.

If m = n you get an error.

This is a scenario that i assumed could be ignored. The way the question was written stated that:
m = The count of sheep on the right hand side
n = The count of sheep in total
And that there's a sheep also jumping the fence. Therefore n cannot be equal to m, i therefore didn't account for it.

C, 392 bytes
Thanks to @Jonathan Frech for saving a byte!
#define F;for(
x,y,k;p(L,a,b,t)char L[][78];{F k=5;k--;)L[x=a*4+(t<2)][y=b*6+k]=t?"'00^>"[k]:"<^00'"[k];L[++x][y-=~!t]=47;L[x][++y]=92;L[x][--y]=L[x+=(t>1)][y]=t<2?'|':43;}i,l;f(n,m){char L[i=n*4][78]F;i--;){F L[i][l=77]=0;l--;)L[i][l]=32;}F l=n+~m;++i<l&&i<9+!m;)p(L,0,i,1);l-=i;p(L,0,i++,2)F;i<11&&m--;)p(L,0,i++,0)F i=0;l--;)p(L,++i,0,1)F i=1;m-->0;)p(L,i++,10,0)F l=0;l<i*4;)puts(L+l++);}

Try it online!
Unrolled:
#define F;for(

x, y, k;
p(L, a, b, t) char L[][78];
{
    F k=5; k--;)
        L[x=a*4+(t<2)][y=b*6+k] = t ? "'00^>"[k] : "<^00'"[k];

    L[++x][y-=~!t] = 47;
    L[x][++y] = 92;
    L[x][--y] = L[x+=(t>1)][y] = t<2 ? '|' : 43;
}

i, l;
f(n, m)
{
    char L[i=n*4][78]
    F; i--;)
    {
        F L[i][l=77]=0; l--;)
            L[i][l] = 32;
    }

    F l=n+~m; ++i<l&&i<9+!m;)
        p(L,0,i,1);

    l-=i;
    p(L,0,i++,2)

    F; i<11&&m--;)
        p(L,0,i++,0)

    F i=0; l--;)
        p(L,++i,0,1)

    F i=1; m-->0;)
        p(L,i++,10,0)

    F l=0; l<i*4;)
        puts(L+l++);
}

y+=1+!t can be y-=~!t.

@JonathanFrech Yep, thanks!

Python 2, 222 277 bytes
n,m=input();n-=m+1
s=" '00^>"
j=1;L='  ||  '
a,b=[[[5,5],[10-m,m]][m<9],[n,10-n]][n<9]
print' '*6*a+s
while n>0 or 0<m:N,M=min(n,a),min(m,b);n-=a;m-=b;print '%-*s'%(6*a,N*s),'%5s'%('/\  '*j)+'%*s'%(6*b,M*" <^00'")+'\n'+'%*s'%(-6*a,N*L),'%5s'%('++  '*j),'%*s'%(6*b,M*L)+'\n';j=0

Try it online!

Fails on n=11 and m=2.

I don't get 11 sheep on the first row when I ran this.

@RobertBenson Thanks, fixed

Charcoal, 98 bytes
Ｎθ≔⁻⊖ＮθηＦ⟦⟦00¶/\¶++ θ⌊⟦⌈⟦⁵⁻χη⟧θ⟧⟧⟦0^>¶\¶+  η⌊⟦⌈⟦⁵⁻χθ⟧η⟧⟧⟧«Ｊ⁰¦⁰‖Ｔ§ι⁰↗Ｆ§ι¹«<^00'¶  || ↗¿¬﹪⊕κ§ι²”|Ｉ4Ｏ

Try it online! Link is to verbose version of code. Explanation:
Ｎθ

Input the number of sheep that have already been counted.
≔⁻⊖Ｎθη

Input the total number of sheep and calculate how many still need to be counted.
Ｆ⟦⟦00¶/\¶++ θ⌊⟦⌈⟦⁵⁻χη⟧θ⟧⟧⟦0^>¶\¶+  η⌊⟦⌈⟦⁵⁻χθ⟧η⟧⟧⟧«

Create an array of two arrays. Each array has the following elements:

A string containing half of the jumping sheep
The number of sheep on that side of the fence
The number of sheep in one row on that side of the fence, which is either

the number of sheep on that side of the fence, if fewer than 5, or
10 - the number of sheep on the other side of the fence, if fewer than 5, or
5, if both sides have at least 5 sheep

Ｊ⁰¦⁰‖Ｔ§ι⁰↗

Reflect the canvas and print the half jumping sheep.
Ｆ§ι¹«

Loop through the sheep on that side.
<^00'¶  || ↗

Print a sheep.
¿¬﹪⊕κ§ι²”|Ｉ4Ｏ

If this is the end of the row then print some newlines and spaces to get to the start of the next sheep.

AWK, 293 bytes
{f=" '00^>"
l="  ||  "
L="  /\\   "
p="  ++   "
Y=$2
X=$1-Y-1
E="      "
x=$1>11?Y<5?10-Y:X>5?5:X:X
y=$1>11?X<5?10-X:5:Y
printf"%"6*(x+1)"s\n",f
for(;X>0||Y>0;A=B=""){for(i=0;i++<x;B=B (X>=0?l:E))A=A (--X>=0?f:E)
A=A L
B=B p
for(i=0;i++<y&&--Y>=0;B=B l)A=A"<^00' "
print A"\n"B"\n"
L=p=E" "}}

Try it online!
I tried using string substitutions to avoid some loops, but it took a lot more code.
Explanation
{f=" '00^>"    Let's assign
l="  ||  "     some variables
L="  /\\   "   for the ASCII
p="  ++   "    pieces
Y=$2        The number of sheep that have already jumped
X=$1-Y-1    Sheep patiently waiting to jump
E="      "  A string to keep things spaced properly
x=$1>11?Y<5?10-Y:X>5?5:X:X  If there's enough sheep, let's use 5 per column
y=$1>11?X<5?10-X:5:Y        Otherwise, use enough to get 11 sheep in first row
printf"%"6*(x+1)"s\n",f     Print the top part of the jumping sheep
for(;X>0||Y>0;A=B=""){      Loop until we've printed all the sheep
  for(i=0;i++<x;              Loop over waiting sheep in this row
    B=B (X>=0?l:E))             Build the "legs" string
      A=A (--X>=0?f:E)            Build the "bodies" string
  A=A L                       Add the legs and post
  B=B p                       for the jumping sheep
  for(i=0;i++<y&&--Y>=0;   Loop over the jumped sheep in this row
    B=B l) A=A"<^00' "     Add to the "legs" and "bodies" string
  print A"\n"B"\n"         Print what we've got so far
  L=p=E" "                 Prevent the jumping sheep's parts from printing lots of times
}}

I must say the sheep art is rather cute. :)

source: Stack Exchange

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

sort: votes


text:
ID generator with no matching contiguous pairs
Given 2 inputs (m=minimum starting id, n=number of ids), generate a sequential list of ids, starting at >=m, made up of the digits 0-9 where no 2 contiguous numbers are the same, e.g. 1232 is ok, 1233 is not (contains 2 '3's next to each other).
Example
for m=985, n=6, below shows what ids would be generated/skipped
...
985 - ok, 1st
986 - ok, 2nd
987 - ok, 3rd
# skip 0988 (contains '88')
989 - ok, 4th
# Skip 099x (contains '99')
# Skip 100x (contains '00')
1010 - ok, 5th
# Skip 1011 (contains '11')
1012 - ok, 6th
...

Output
Each ID should be printed on a new line, as for the above sequence:
985
986
987
989
1010
1012

Rules
Standard code-golf rules, lowest byte count wins

Welcome to PPCG! Each ID should be printed on a new line I highly discourage explicitly restricting the output to a particular format.

Test case: an input where m has consecutive identical digits. It shouldn't cause anybody to trip up but it'll be nice to have for people to consider. Say, m=988, n=3.

Is it okay to return a list of IDs (i.e. a 1-D array of integers), instead of printing to stdout?

Wait a minute... don't immediately answer challenges that has something that should/may/can be fixed (in this case, the strict output format)

As, if the rules are kept they're bad, and if they're changed existing answers are invalidated (suboptimal).

@user202729 The answers won't be invalidated in this case.

@EriktheOutgolfer But suboptimal. Doing more than what the challenge requires is invalid.

@user202729 That doesn't make answers invalid... If anything, the answers will either get fixed or they're just following the old rules.

@EriktheOutgolfer - First time on here, why is specifying the output format discouraged? Many of the code golf questions I've looked at are specifically about outputting information in a certain format (e.g. output as a square / christmas tree etc.)

@beirtipol Outputting in a very specific format is discouraged for challenges whose main point is not the output. [tag:ascii-art] challenges are all about outputting things, that's why they are allowed to do it. But requiring us to join the results by newlines adds nothing to the challenge, but rather adds unnecessary bytes to the submissions. See Things to avoid when writing challenges.

Aha, understood. Will note it for next time. Looking at some of the answers below, I think that changing the question to remove this would be unfair?

For the ones written in golfing languages changing the rule to allow more output formats wouldn't affect them. For the rest you can just leave a comment saying the output format isn't restricted anymore.

Can n be 0 ?

@beirtipol So is the output restricted or not? Can I print the numbers as strings enclosed in quotes ("989"...)?

I'll leave output restricted as is. Don't think I should change the rules now after submission

@TonHospel - yes, n could be 0

Jelly, 6 bytes
DIẠµ#Y

Try it online!
How it works?

DIẠµ#Y – Full program. Argument: two integers, X and Y.

   µ#  – Return the first Y integers higher than or equal to X that satisfy:
 I     – The increments ...
D      – ... Of their base-10 digits ...
  Ạ    – ... Are all non-0.
     Y – Join the result by newlines.

Brachylog, 11 10 bytes
{≤ṫẹ~ḅẉ}ᶠ⁾

Input is a list of two numbers.
Try it online!
Explanation
The built-in ḅ takes a list or string, like "1000220", and splits it into blocks of equal adjacent elements, like ["1","000","22","0"].
In this program, I apply the ~ operator to it, so it works in reverse: it takes a list of strings, checks that each string consists of repetitions of a single character and neighboring strings have different characters, and concatenates the list.
The predicate ≤ enumerates numbers starting from the first input in increasing order, and I check a condition on them, printing those that satisfy it and stopping when I've found enough.
{≤ṫẹ~ḅẉ}ᶠ⁾  Input is a pair, say [M=988,N=3].
{      }ᶠ⁾  Apply this predicate to M and compute the first N results.
 ≤          Take a number that is greater than or equal to M (first up is 988).
  ṫ         Convert it to string: "988"
   ẹ        Split it into substrings of length 1: ["9","8","8"]
     ~ḅ     Apply ḅ in reverse: fails, try next number.
       ẉ    If ḅ succeeds, print the resulting string and a newline.
            This counts as a result of the predicate.

05AB1E, 9 bytes
µÐÔQi=¼}>

Try it online!
Exlpanation
µ           # loop until counter equals n
 Ð          # triplicate current value (initially m)
  Ô         # connected uniqueified on the copy at the top of the stack
   Q        # compare to unmodified for equality
    i  }    # if true
     =      # print current value while leaving it on the stack
      ¼     # increment the counter
        >   # increment current value

Java 8, 83 bytes
(m,n)->{for(;n>0;m++)if(!(m+"").matches(".*(.)\\1.*")){System.out.println(m);n--;}}

Explanation:
Try it online.
(m,n)->{                      // Method with two integer parameters and no return-type
  for(;n>0;                   //  Loop as long as `n` is larger than 0
      m++)                    //    After every iteration: increase `m` by 1
    if(!(m+"").matches(".*(.)\\1.*")){
                              //   If there are no repeated adjacent digits:
      System.out.println(m);  //    Print `m`
      n--;}}                  //    And decrease `n` by 1

Very nice. Out of curiosity, where would be the appropriate forum for this question where the challenge wasn't "bytes" but "efficiency"?

@beirtipol By most efficient you mean fastest execution time? In that case probably also here on PPCG, with the tags code-challenge and fastest-code. Although posting the exact same challenge now and changing code-golf to fastest-code will probably still be closed as a dupe..

R, 111 92 71 bytes
function(m,n)while(F<n){if(!grepl("(.)\\1",m)){cat(m,'
');F=F+1}
m=m+1}

Try it online!
Uses grepl to search for repeated digits.

You don't join the result by newlines, and the OP didn't respond if this is allowed yet (though I hope It'll be fine)

@Mr.Xcoder ah, right, I noticed that and then copied and pasted the wrong version :(

PowerShell, 59 bytes
param($m,$n)for(;$n){if("$m"-notmatch"(.)\1"){$m;$n--}$m++}

Try it online!
Basically similar to the other answers. Loops so long as we have numbers left to print (for(;$n)), tests whether we have a regex match against a double-digit and if not it puts that on the pipeline and decreases $n. Then we increment $m and loop again. The elements are picked up from the pipeline and the implicit Write-Output gives us a newline-separated output for free.

Jelly, 9 bytes
DŒgZLỊµ#Y

Try it online!
If not for the output restriction, Y can be removed.

C, 73 bytes
k;f(s,n){for(;n--;printf("%d\n",s++))for(k=s;k;)k=k%10-k/10%10?k/10:++s;}

Try it online!

Perl 6, 56 bytes
{.put for grep({none .comb Zeq.comb.skip},$^a..*)[^$^b]}

Try it
Expanded:
{  # bare block lambda with placeholder params $a $b

  .put for

  grep(

    {
      none          # create a none junction (True if all are False)

        .comb       # the input split into digits
        Zeq         # Zip using &infix:«eq» operator
        .comb.skip  # the input split into digits starting at second one
    },

    $^a .. *        # a Range starting at the first argument

  )[ ^ $^b ]        # take the first $b values
}

Perl 5.10.0 + -n, 40 39 bytes
for(;$i;$_++){!/(.)\1/&&$i--&&say}$i=$_

Try it online!
-1 byte thanks to Xcali
Input on two lines, first n, then m. Make sure that there is NO newline after m:
(echo '6'; echo -n '985') | perl -nE 'for(;$i;$_++){!/(.)\1/&&$i--&&say}$i=$_'

You can eliminate the 'm' to save a byte.

@Xcali Thanks, don't know what I was thinking ...

Perl 5, -ln 33 bytes
Enter 2 lines on STDIN, first starting id then count
#!/usr/bin/perl -ln
$n-=!/(.)\1/&&say,$_++while$n.=<>

Try it online!

I did not know that $n.=<> worked like that, especially with the -=...

@DomHastings Unfortunately I'll have to roll it back since $n can be 0 so doing them both together is wrong

Retina, 34 bytes
.0A`
"$+"{\/(.)\1/{`.+
*
)C`
.+
*

Try it online! Takes n and m as input on separate lines. Explanation:
.0A`

Turn off automatic output and delete n from the work buffer.
"$+"{

Repeat n times.
\

Print the value of m at the end of the following looped group.
/(.)\1/{`

Loop while there are contiguous digits.
.+
*

Convert to unary.
)C`

Count the number of empty strings, which is one more than the number of characters, thus adding 1 and converting back to decimal. This ends the inner loop.
.+
*

Having printed m, add 1 again in the same way. (The last line doesn't need a C` because it's the default stage type for the last line.) The outer loop is implicitly ended.
Note that converting to unary and back to decimal is a little slow; for 39 bytes, a version that doesn't do any conversion:
.0A`
"$+"{\/(.)\1/+`.+
$.(*__
.+
$.(*__

Try it online! Explanation: $.( calculates the length of the rest of the substitution, conveniently without actually expanding it; since the length of *_ is implicitly the matched value and the length of _ is of course 1 this just increments the value.

Pyth, 12 bytes
j.f.A.+jZTEQ

Try it here

Stax, 9 8 bytesCP437
ç@F6╕↔┤ú

Try it online!
Happen to coincide with @Mr.Xcoder's algorithm in his Jelly answer.
-1 byte per comment by @recursive.
Explanation
Uses the unpacked format to explain.
{$:-|A}gn
{     }gn    Generator, generate given number of values, using block as a filter
                 And implicit output, one element on a line.
             In Stax, only 0 and [] is falsy.

 $           Convert the number to string
  :-         Difference between contiguous digit
    |A       All of them are truthy (may use `:*` as well)

https://staxlang.xyz/#c=%C3%A7%40F6%E2%95%95%E2%86%94%E2%94%A4%C3%BA&i=985+6%0A99+3&a=1&m=2 gives 8 bytes.  Implicit eval works on multiple values as long as they're on the first line of standard input.

@recursive Thank you, that is something I didn't notice although it is documented.

Haskell, 94 93 91 bytes
-1 byte thanks to Laikoni
-2 bytes thanks to Zgarb
import Data.List
a!0=[]
a!b|all(null.tail)$group$show a=show a++'\n':(a+1)!(b-1)|c<-a+1=c!b

Try it online!
First Haskell golf.

Welcome to Haskell golfing! group(show a) can be group$show a.

(<2).length can be null.tail

Python 2, 80 73 bytes
-7 bytes thanks to Mr. Xcoder

m,n=input()
while n:
 if~-sum(i*2in`m`for i in`99**9`):print m;n-=1
 m+=1

Try it online!

Haskell, 70 bytes
-19 bytes thanks to nimi.
s#n=unlines$map show$take n$filter(and.(zipWith(/=)=<<tail).show)[s..]

Try it online!
17 bytes dedicated to separating by newlines.

53 bytes

You don't join the result by newlines, and the OP didn't respond if this is allowed yet (though I hope It'll be fine)

@Mr.Xcoder Agh, fixing...

You can use mapM and print. Try it online!

JavaScript (ES6), 50 bytes
Takes input in currying syntax (m)(n).
m=>g=n=>n?/(.)\1/.test(m++)?g(n):~-m+`
`+g(n-1):''

Try it online!

C# (.NET Core), 91 bytes
m=>n=>{for(;n-->0;System.Console.WriteLine(m++))for(int k=m;k>0;k=k%10!=k/10%10?k/10:++m);}

Port of @Steadybox' C answer.
Try it online.

Perl 5 (-nl), 42 bytes
$l=<>;do{!/(.)\1/&&$l--&&say}while++$_&&$l

Try it online!

AWK, 90 bytes
{for(j=$1;k<$2;j++){for(a=b=d;++b<=(n=split(j,A,""))&&a!=c=A[b];a=c);if(n<b&&++k)print j}}

Try it online!
This is a lot uglier than I thought it would be.  I discovered that AWK only has back-substitution in its gensub function which would make it not very efficient to use for this application.
So this is a very straightforward approach of incrementing an ID counter, splitting the counter at each character, looping through the characters to see if any character is the same as the previous character. If no repeated characters are found, print the ID counter and increment the number of IDs printed.
I will try to refrain from making a statement along the lines of "AWK should have the ability to do more robust regular expressions", but it will be difficult.

Bash + GNU utilities, 35
seq $1 inf|egrep -v '(.)\1'|sed $2q

Try it online.

Ruby, 47 bytes
->s,n{/(.)\1/!~s&&p(s)&&n-=1;s.next!;n>0&&redo}

Try it online!
If you don't like the quote marks, it's 50 bytes
->s,n{puts s if/(.)\1/!~s&&n-=1;s.next!;n>0&&redo}

Try it online!

Pip, 22 bytes
--aLb{W`(.)\1`N++a0Pa}

Try it online!
Explanation
--aLb{W`(.)\1`N++a0Pa}
                        a,b are command-line arguments
--a                     Decrement a
   Lb{               }  Loop b times:
       `(.)\1`           Regex matching a character followed by itself
      W       N++a       While that regex matches in incremented a:
                  0       No-op
                   Pa    When the while loop exits, a is a valid ID; print it

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


text:
Build a half cardinal cyclic quine
A half cardinal cyclic quine is a cyclic quine with two states, one perpendicular to the other.
Rules
You can decide which rotation you want to implement, clockwise or counter-clockwise.
Once rotated, any gaps in your code should be replaced with spaces to preserve the positioning.
Your program must satisfy the community definition of a quine.
This is code-golf so the shortest program in each language wins. Your first program is used for your byte count.
Standard loopholes are forbidden.
Examples
If your program is:
$_='print';eval

Then the next iteration must be either:
$
_
=
'
p
r
i
n
t
'
;
e
v
a
l

or
l
a
v
e
;
'
t
n
i
r
p
'
=
_
$

which must output the original program:
$_='print';eval

If your program is:
;$_=';
;$_=';
print

Then the next iteration must be either:
;;
''t
==n
__i
$$r
;;p

or:
p;;
r$$
i__
n==
t''
 ;;

which must output the original program:
;$_=';
;$_=';
print

Related.

Somewhat related.

So, we pad the code with spaces to keep its shape after turning?

@EriktheOutgolfer Yes, I'll confirm that in the body, thanks! I've also clarified that the first program is the byte-count used.

Is the only difference between this and the post @MartinEnder linked that that is a transpose and this is a rotation?

@dylnan No, the other one doesn't ask for a mutual quine.

Having seen the answers so far I think the real challenge would be the anticlockwise one or a quine with more than one lines (so that rotation is different from transposition or simply inserting newlines).

@WeijunZhou Indeed, I'm not sure how feasible it is, but I have a more complex version of this in the sandbox.

Are the quine and its rotation allowed to be the same?

You might want to require the two programs to be different. Otherwise, quines which happen to have rotational symmetry would be valid answers.

And the same applies to the one in the sandbox

I really want to see an answer in Python, even if it has symmetry. I'm getting stuck

@mbomb007 I'm not sure I feel the programs have to be different, I think a quine that can be rotated would be valid as I feel that might be a challenge on its own. Does that help you compete (not really I'm guessing, by the last comment!), I would love to see a Python solution!

I sure hope no lovely red birds are going to be harmed in the course of this contest...

I think another interesting scoring method would be max(width, height) ** 2, so getting your program to be more square would be incentivized.

@mbomb007 I quite like that... Perhaps a challenge to create a quine that is the same when rotated 90° using that scoring mechanism?

CJam, 19 17 15 bytes
{s"_~"+N*""-}_~

Try it online! Try the rotation.
Explanation
{s"_~"+  e# Standard quine framework. Puts a string representation of the entire
         e# program on the stack.
  N*     e# Riffle linefeeds into the string, which is effectively a clockwise
         e# rotation by 90°.
  ""-    e# Does nothing.
}_~

In the rotated code, we've got linefeeds everywhere:
{
s
"
_
~
"
+
N
*
"
"
-
}
_
~

As Lynn noticed on Dom's earlier quine challenge inserting linefeeds actually still forms valid quine, because the linefeeds inside the block will just be retained verbatim anyway, and there will also be linefeeds in the "_~" string to make those two characters at the end show up on their own line. So {s"_~"+...}_~ (with linefeeds) is still a valid quine framework (although there'll be an additional linefeed at the end of the string). N* now inserts even more linefeeds into that string, but we don't really care: because now ""- has a linefeed inside that string so it actually removes all linefeeds from the program representation. So we end up with the horizontal form of the code again, undoing the rotation.

Stax, 28 bytes
"8H^Hs+2*A]/Mm"8H^Hs+2*A]/Mm

Run and debug the first form
Run and debug the second form

><>, 22 bytes
 "2+}>oao#ov*48}}*d3'v

Try it online!
Rotated anti-clockwise:
v
'
3
d
*
}
}
8
4
*
v
o
#
o
a
o
>
}
+
2
"

Try it online!
The first one prints the line in reverse with newlines interspersed, and the second prints it in reverse without the newlines.

This is very clever!

Good going on approaching it on hard mode!

05AB1E, 36 34 bytes
4"D6Ø·çýD¶åi¶KëS»"D6Ø·çýD¶åi¶KëS»

Try first iteration
or Try next iteration


text:
RGB to Xterm Color Converter
256-color Xterm-compatible terminals add 240 colors on top of the usual 16 system colors. Colors 16-231 use 6 levels (0, 95, 135, 175, 215, 255) of red, green, and blue, ordered lexicographically. Colors 232-255 are simply 24 levels of gray (8...238 by 10s). To get a better idea of what I'm talking about, see this table.
The Challenge
Your goal is to make a program or function that takes, as input, rgb values, and outputs the number corresponding with the closest Xterm color to that rgb value. Since the 16 system colors (colors 0-15) are often customizable, you will be excluding them from this conversion.
To better define what the "closest" color is, use the Manhattan distance along red, green, and blue components. For example, rgb(10, 180, 90) is 20 units away from rgb(0, 175, 95) (color 35) because abs(10 - 0) + abs(180 - 175) + abs(90 - 95) == 20. If the input color is equally between two or more Xterm colors, output the Xterm color with the highest index.
Examples
 R   G   B     Xterm
  0   0   0 ==> 16
 95 135   0 ==> 64
255 255 255 ==> 231
238 238 238 ==> 255

 90 133 140 ==> 66
218 215 216 ==> 188
175 177 178 ==> 249

175   0 155 ==> 127
 75  75  75 ==> 239
 23  23  23 ==> 234
115 155 235 ==> 111

Rules

Standard loopholes are forbidden
Your program or function is allowed to take rgb values in any reasonable format, including:

Separate arguments for red, green, and blue
A list, tuple, dictionary, or similar
Delimiter-separated string or stdin
Hex colors (e.g. #ff8000)

You may assume that all r, g, and b, values will be integers between 0 and 255.
Since the 16 system colors are to be excluded from the mapping, all outputs should be in the range 16...255.

This is code-golf, so shortest code wins.

Haskell, 132 bytes
v=0:[95,135..255]
f c=snd$maximum[(-sum(abs<$>zipWith(-)c x),i)|(i,x)<-zip[16..]$[[r,g,b]|r<-v,g<-v,b<-v]++[[g,g,g]|g<-[8,18..238]]]

Try it online!
Takes input as a list of integers [red, green, blue].
Fairly straightforward implementation. First I build a list of the Xterm colors we're using with two list comprehensions concatenated together. The first of which handles colors 16-231 by triple iterating over v which contains the values those colors use. The second one just iterates over the grey values and puts them in all three slots. Then I index it with zip (starting at 16) and make a pair with the manhattan distance (negated) and that index and take the maximum. I used maximum because we're tie-breaking on the largest index and this way saves me one extra -.

Ruby, 280 180 166 164 155 bytes
->c{d=0,95,135,175,215,255
a=(0..239).map{|n|n<216?[d[n/36],d[(n%36)/6],d[n%6]]:[n*10-2152]*3}.map{|t|t.zip(c).map{|a,b|(a-b).abs}.sum}
a.rindex(a.min)+16}

Try it online!
A lambda taking the input color as an array of integers.
I had more trouble generating the Xterm colors than I expected! I'm prepared to be outgolfed embarrassingly modestly in that area. I used base conversion as a kind of compression, but the only way I know to do so in Ruby is through Integer#to_s which is a little bit awkward.
-100 bytes: Read the problem more carefully, and ignore the 16 system colors ^_^;
-14 bytes: Use hand base conversion instead of .to_s(6)
-2 bytes: Skip square brackets when declaring array
-9 bytes: Create list of Xterm colors with only one map; this also saves a plus sign and a pair of parens.
->c{
  d=0,95,135,175,215,255                 # d is the set of possible RGB values
  a=(0..239).map{|n|                     # Create the array of Xterm triplets
    n<216 ? [d[n/36],d[(n%36)/6],d[n%6]] # Convert x from base 6 to base d, or
          : [n*10-2152]*3                #   create a uniform triplet
  }.map{|t|
    t.zip(c).map{|a,b|(a-b).abs}.sum     # Map from triplets to Manhattan distance
  }
  a.rindex(a.min) +                      # Find the last index of the lowest distance
  16                                     # Offset for the exluded system colors
}

BTW, You don't need to map to the 16 system colors. Maybe I should make that clearer in the description.

Ooh, that will help me quite a bit! I definitely missed that in the original question wording.

Kotlin, 299 290 267 265 bytes
(16..255).associate{it to if(it<232)(it-16).let{i->listOf(0,95,135,175,215,255).let{l->listOf(l[i/36],l[(i/6)%6],l[i%6])}}else(8..238 step 10).toList()[it-232].let{listOf(it,it,it)}}.minBy{(k,v)->(it.zip(v).map{(a,b)->kotlin.math.abs(a-b)}.sum()*256)+(256-k)}!!.key

Beautified
(16..255).associate {
    it to if (it < 232) (it - 16).let { i ->
            listOf(0, 95, 135, 175, 215, 255).let { l ->
                listOf(
                        l[i / 36],
                        l[(i / 6) % 6],
                        l[i % 6])
            }
        } else (8..238 step 10).toList()[it - 232].let { listOf(it, it, it) }
}.minBy { (k, v) ->
    (it.zip(v).map { (a, b) -> kotlin.math.abs(a - b) }.sum() * 256) + (256 - k)
}!!.key

Test
data class Test(val r: Int, val g: Int, val b: Int, val out: Int)

val test = listOf(
        Test(0, 0, 0, 16),
        Test(95, 135, 0, 64),
        Test(255, 255, 255, 231),
        Test(238, 238, 238, 255),

        Test(90, 133, 140, 66),
        Test(218, 215, 216, 188),
        Test(175, 177, 178, 249),

        Test(175, 0, 155, 127),
        Test(75, 75, 75, 239),
        Test(23, 23, 23, 234),
        Test(115, 155, 235, 111)
)
fun z(it:List<Int>): Int =
(16..255).associate{it to if(it<232)(it-16).let{i->listOf(0,95,135,175,215,255).let{l->listOf(l[i/36],l[(i/6)%6],l[i%6])}}else(8..238 step 10).toList()[it-232].let{listOf(it,it,it)}}.minBy{(k,v)->(it.zip(v).map{(a,b)->kotlin.math.abs(a-b)}.sum()*256)+(256-k)}!!.key

fun main(args: Array<String>) {
    for (i in test) {
        val r = z(listOf(i.r, i.g, i.b))
        println("$i ${i.out} ==> $r")
    }
}

TIO
TryItOnline

Stax, 41 bytes
¬ÿ▒ú╘Σt∙Æ9φ☻ùí&BQq═IÜH∩Å╧♥f⌠óH]╨⌡≤@■Q‼Hr¼

Run and debug online!
ASCII version of 50 bytes:
"4GOW_g"{52-5*m3|^24{A*vv]3*m+{;\{E:-m|+mc|m|IH16+

C (gcc), 202 192 157 150 (141 bugged) 138 134 bytes
l,m,t,i;a(c,x){x=abs(c-=i>215?i*10-2152:x*40+!!x*55);}f(r,g,b){for(i=l=240;i--;t=a(r,i/36)+a(g,i/6%6)+a(b,i%6),t<l?l=t,m=i:1);i=m+16;}

Thanks @ceilingcat
Try it online!

The problem isn't defined by the tests (which are clearly labeled as examples), so please get a new test added instead.

@TonHospel I fixed the bug now and cut down -3 bytes, but thanks for the answer

Batch, 266 bytes
@set/ax=15,m=999
@set s=for %%b in (0 95 135 175 215 255)do @
@%s:b=r%%s:b=g%%s%call:c %* %%r %%g %%b
@for /l %%g in (8,10,238)do @call:c %* %%g %%g %%g
@echo %n%
:c
@set/ax+=1,r=%4-%1,g=%5-%2,b=%6-%3
@set/ad=%r:-=%+%g:-=%+%b:-=%
@if %d% leq %m% set/an=x,m=d

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


text:
Calculate the Hafnian as quickly as possible
The challenge is to write the fastest code possible for computing the Hafnian of a matrix.
The Hafnian of a symmetric 2n-by-2n matrix A is defined as:
$$\operatorname{haf}(A)=\frac{1}{n ! 2^n} \sum_{\sigma \in S_{2 n}} \prod_{j=1}^n A_{\sigma(2 j-1), \sigma(2 j)}$$
Here \$ S_{2 n} \$ represents the set of all permutations of the integers from 1 to 2n, that is [1, 2n].
The wikipedia link also gives a different looking formula which may be of interest (and even faster methods exist if you look further on the web). The same wiki page talks about adjacency matrices but your code should work for other matrices as well.  You can assume the values will all be integers but not that that they are all positive.
There is also a faster algorithm but it seems hard to understand. and Christian Sievers was the first to implement it (in Haskell).
In this question matrices are all square and symmetric with even dimension.
Reference implementation (note this is using the slowest possible method).
Here is some example python code from Mr. Xcoder.
from itertools import permutations
from math import factorial

def hafnian(matrix):
    my_sum = 0
    n = len(matrix) // 2
    for sigma in permutations(range(n*2)):
        prod = 1
        for j in range(n):
            prod *= matrix[sigma[2*j]][sigma[2*j+1]]
        my_sum += prod
    return my_sum / (factorial(n) * 2 ** n)

print(hafnian([[-1, 1, 1, -1, 0, 0, 1, -1], [1, 0, 1, 0, -1, 0, -1, -1], [1, 1, -1, 1, -1, -1, 0, -1], [-1, 0, 1, -1, -1, 1, -1, 0], [0, -1, -1, -1, -1, 0, 0, -1], [0, 0, -1, 1, 0, 0, 1, 1], [1, -1, 0, -1, 0, 1, 1, 0], [-1, -1, -1, 0, -1, 1, 0, 1]]))
4

M = [[1, 1, 0, 0, 0, 0, 0, 1, 0, 0], [1, 1, -1, 0, -1, 1, 1, 1, 0, -1], [0, -1, -1, -1, 0, -1, -1, 0, -1, 1], [0, 0, -1, 1, -1, 1, -1, 0, 1, -1], [0, -1, 0, -1, -1, -1, -1, 1, -1, 1], [0, 1, -1, 1, -1, 1, -1, -1, 1, -1], [0, 1, -1, -1, -1, -1, 1, 0, 0, 0], [1, 1, 0, 0, 1, -1, 0, 1, 1, -1], [0, 0, -1, 1, -1, 1, 0, 1, 1, 1], [0, -1, 1, -1, 1, -1, 0, -1, 1, 1]]

print(hafnian(M))
-13

M = [[-1, 0, -1, -1, 0, -1, 0, 1, -1, 0, 0, 0], [0, 0, 0, 0, 0, -1, 0, 1, -1, -1, -1, -1], [-1, 0, 0, 1, 0, 0, 0, 1, -1, 1, -1, 0], [-1, 0, 1, -1, 1, -1, -1, -1, 0, -1, -1, -1], [0, 0, 0, 1, 0, 0, 0, 0, 0, 1, -1, 0], [-1, -1, 0, -1, 0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 0, -1, 0, 1, 1, -1, -1, 0, 1, 0], [1, 1, 1, -1, 0, 1, -1, 1, -1, -1, -1, -1], [-1, -1, -1, 0, 0, 1, -1, -1, -1, 1, -1, 0], [0, -1, 1, -1, 1, 1, 0, -1, 1, -1, 1, 1], [0, -1, -1, -1, -1, 1, 1, -1, -1, 1, 0, -1], [0, -1, 0, -1, 0, 0, 0, -1, 0, 1, -1, 1]]

print(hafnian(M))
13

M = [[-1, 1, 0, 1, 0, -1, 0, 0, -1, 1, -1, 1, 0, -1], [1, -1, 1, -1, 1, 1, -1, 0, -1, 1, 1, 0, 0, -1], [0, 1, 1, 1, -1, 1, -1, -1, 0, 0, -1, 0, -1, -1], [1, -1, 1, -1, 1, 0, 1, 1, -1, -1, 0, 0, 1, 1], [0, 1, -1, 1, 0, 1, 0, 1, -1, -1, 1, 1, 0, -1], [-1, 1, 1, 0, 1, 1, -1, 0, 1, -1, -1, -1, 1, -1], [0, -1, -1, 1, 0, -1, -1, -1, 0, 1, -1, 0, 1, -1], [0, 0, -1, 1, 1, 0, -1, 0, 0, -1, 0, 0, 0, 1], [-1, -1, 0, -1, -1, 1, 0, 0, 1, 1, 0, 1, -1, 0], [1, 1, 0, -1, -1, -1, 1, -1, 1, 1, 1, 0, 1, 0], [-1, 1, -1, 0, 1, -1, -1, 0, 0, 1, -1, 0, -1, 0], [1, 0, 0, 0, 1, -1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, -1, 1, 0, 1, 1, 0, -1, 1, -1, 1, 1, -1], [-1, -1, -1, 1, -1, -1, -1, 1, 0, 0, 0, 1, -1, -1]]

print(hafnian(M))
83

The task
You should write code that, given an 2n by 2n matrix, outputs its Hafnian.
As I will need to test your code it would be helpful if you could give a simple way for me to give a matrix as input to your code, for example by reading from standard in.  I will test your code in randomly chosen matrices with elements selected from {-1, 0, 1}. The purpose of testing like this is to reduce the chance the Hafnian will be a very large value.
Ideally your code will be able to read in matrices exactly as I have them in the examples in this question straight from standard in. That is the input would look like [[1,-1],[-1,-1]] for example.  If you want to use another input format, please ask and I will do my best to accommodate.
Scores and ties
I will test your code on random matrices of increasing size and stop the first time your code takes more than 1 minute on my computer.  The scoring matrices will be consistent for all submissions in order to ensure fairness.
If two people get the same score then the winner is the one which is fastest for that value of n. If those are within 1 second of each other then it is the one posted first.
Languages and libraries
You can use any available language and libraries you like but no pre-existing function to compute the Hafnian. Where feasible, it would be good to be able to run your code so please include a full explanation for how to run/compile your code in Linux if at all possible.`
My Machine The timings will be run on my 64-bit machine. This is a standard ubuntu install with 8GB RAM, AMD FX-8350 Eight-Core Processor and Radeon HD 4250.  This also means I need to be able to run your code.
Call for answers in more languages
It would be great to get answers in your favorite super fast programming language. To start things off, how about fortran, nim and rust?
Leaderboard

52 by miles using C++. 30 seconds.
50 by ngn using C. 50 seconds.
46 by Christian Sievers using Haskell. 40 seconds.
40 by miles using Python 2 + pypy. 41 seconds.
34 by ngn using Python 3 + pypy.  29 seconds.
28 by Dennis using Python 3.  35 seconds.  (Pypy is slower)

Is there a limit for the absolute values of the matrix entries? Can we return a floating point approximation? Do we have to use arbitrary precision integers?

@Dennis In practice I will only use -1,0,1 to test (chosen at random). I don't want it to be a big int challenge.  In all honesty I don't know if we will hit the limits of 64 bit ints before the code gets too slow to run but my guess is that we won't. Currently we are nowhere near that.

If the entries are limited to -1,0,1, that should be mentioned on the question. Does our code have to work at all for other matrices?

@Dennis An old version used to say that but I must have written over it.  I would prefer it if the code weren't specialised for -1,0,1 entries but I suppose I can't stop that.

Do you have more test cases? perhaps for larger n?

@miles Added a slightly bigger example.

I think that to be fair the randomly generated matrices should be the same for all submissions.

@user202729 Yes they will be

Recently Andreas Bjorklund, Brajesh Gupt and myself published a new algorithm for Hafnians of complex matrices: https://arxiv.org/pdf/1805.12498.pdf .
For an n \times n matrix it scales like n^3 2^{n/2}. If I understand correctly Andreas' original algorithm from https://arxiv.org/pdf/1107.4466.pdf it scales like n^4 2^{n/2} or n^3 log(n) 2^{n/2} if you used Fourier transforms to do polynomial multiplications. Our algorithm is specifically taylored for complex matrices so it will not be as fast as the ones developed here for {-1,0,1} matrices.
I wonder however if one can use some of the trick

Haskell
import Control.Parallel.Strategies
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector as VB

type Poly = V.Vector Int

type Matrix = VB.Vector ( VB.Vector Poly )

constpoly :: Int -> Int -> Poly
constpoly n c = V.generate (n+1) (\i -> if i==0 then c else 0)

add :: Poly -> Poly -> Poly
add = V.zipWith (+)

shiftmult :: Poly -> Poly -> Poly
shiftmult a b = V.generate (V.length a)
                           (\i -> sum [ a!j * b!(i-1-j) | j<-[0..i-1] ])
  where (!) = V.unsafeIndex

x :: Matrix -> Int -> Int -> Int -> Poly -> Int
x  _    0  _ m p = m * V.last p
x mat n c m p =
  let mat' = VB.generate (2*n-2) $ \i ->
             VB.generate i       $ \j ->
                 shiftmult (mat!(2*n-1)!i) (mat!(2*n-2)!j) `add`
                 shiftmult (mat!(2*n-1)!j) (mat!(2*n-2)!i) `add`
                 (mat!i!j)
      p' = p `add` shiftmult (mat!(2*n-1)!(2*n-2)) p
      (!) = VB.unsafeIndex
      r = if c>0 then parTuple2 rseq rseq else r0
      (a,b) = (x mat (n-1) (c-1) m p, x mat' (n-1) (c-1) (-m) p')
              `using` r
  in a+b

haf :: [[Int]] -> Int
haf m = let n=length m `div` 2
        in x (VB.fromList $ map (VB.fromList . map (constpoly n)) m)
             n  5  ((-1)^n)  (constpoly n 1)

main = getContents >>= print . haf . read

This implements a variation of Algorithm 2 of Andreas Björklund: Counting Perfect Matchings as Fast as Ryser.
Compile using ghc with compile time options -O3 -threaded and use run time options +RTS -N for parallelization. Takes input from stdin.

Maybe note that parallel and vector must be installed?

@H.PWiz Nobody complained here, but sure, noting it won't hurt. Well, now you did.

@ChristianSievers I don't think they're complaining. The OP might not be familiar with Haskell, so explicitly stating what must be installed to be able to time the code is a good idea.

@Dennis I didn't mean "you did complain" but "you did note it". And I didn't think of complaining as a negative thing. The OP is the same as in the challenge I linked to, so there should be no problem.

N = 40 in 7.5 seconds on TIO... Man, this is fast!

This answer is particularly impressive.

It seems that you can get a minor speed-up just by extracting mat!(2*n-1) and mat!(2*n-2) into their own variables. I doubt it increase the matrix size though

@H.PWiz Did you try? I don't expect any noticable improvement from such changes. (I tried several others.)

I did try, it was saving around 2 seconds consistently. Although now, there is no difference. Perhaps I was using different matrices by mistake

Can this be made faster by compiling with LLVM?

@Potato44 I got no gain from using -fllvm, but depending on versions and maybe architecture you may have more luck.

Python 3
from functools import lru_cache

@lru_cache(maxsize = None)
def haf(matrix):
	n = len(matrix)
	if n == 2: return matrix[0][1]
	h = 0
	for j in range(1, n):
		if matrix[0][j] == 0: continue
		copy = list(matrix)
		del copy[:j+1:j]
		copy = list(zip(*copy))
		del copy[:j+1:j]
		h += matrix[0][j] * haf(tuple(copy))
	return h

print(haf(tuple(map(tuple, eval(open(0).read())))))

Try it online!

C++ (gcc)
#define T(x) ((x)*((x)-1)/2)
#define S 1
#define J (1<<S)
#define TYPE int

#include <iostream>
#include <vector>
#include <string>
#include <pthread.h>

using namespace std;

struct H {
    int s, w, t;
    TYPE *b, *g;
};

void *solve(void *a);
void hafnian(TYPE *b, int s, TYPE *g, int w, int t);

int n, m, ti = 0;
TYPE r[J] = {0};
pthread_t pool[J];

int main(void) {
    vector<int> a;
    string s;
    getline(cin, s);

    for (int i = 0; i < s.size(); i++)
        if (s[i] == '0' || s[i] == '1')
            a.push_back((s[i-1] == '-' ? -1 : 1)*(s[i] - '0'));

    for (n = 1; 4*n*n < a.size(); n++);
    m = n+1;

    TYPE z[T(2*n)*m] = {0}, g[m] = {0};

    for (int j = 1; j < 2*n; j++)
        for (int k = 0; k < j; k++)
            z[(T(j)+k)*m] = a[j*2*n+k];
    g[0] = 1;

    hafnian(z, 2*n, g, 1, -1);

    TYPE h = 0;
    for (int t = 0; t < ti; t++) {
        pthread_join(pool[t], NULL);
        h += r[t];
    }

    cout << h << endl;

    return 0;
}

void *solve(void *a) {
    H *p = reinterpret_cast<H*>(a);
    hafnian(p->b, p->s, p->g, p->w, p->t);
    delete[] p->b;
    delete[] p->g;
    delete p;
    return NULL;
}

void hafnian(TYPE *b, int s, TYPE *g, int w, int t) {
    if (t == -1 && (n < S || s/2 == n-S)) {
        H *p = new H;
        TYPE *c = new TYPE[T(s)*m], *e = new TYPE[m];
        copy(b, b+T(s)*m, c);
        copy(g, g+m, e);
        p->b = c;
        p->s = s;
        p->g = e;
        p->w = w;
        p->t = ti;
        pthread_create(pool+ti, NULL, solve, p);
        ti++;
    }
    else if (s > 0) {
        TYPE c[T(s-2)*m], e[m];
        copy(b, b+T(s-2)*m, c);
        hafnian(c, s-2, g, -w, t);
        copy(g, g+m, e);

        for (int u = 0; u < n; u++) {
            TYPE *d = e+u+1,
                  p = g[u], *x = b+(T(s)-1)*m;
            for (int v = 0; v < n-u; v++)
                d[v] += p*x[v];
        }

        for (int j = 1; j < s-2; j++)
            for (int k = 0; k < j; k++)
                for (int u = 0; u < n; u++) {
                    TYPE *d = c+(T(j)+k)*m+u+1,
                          p = b[(T(s-2)+j)*m+u], *x = b+(T(s-1)+k)*m,
                          q = b[(T(s-2)+k)*m+u], *y = b+(T(s-1)+j)*m;
                    for (int v = 0; v < n-u; v++)
                        d[v] += p*x[v] + q*y[v];
                }

        hafnian(c, s-2, e, w, t);
    }
    else
        r[t] += w*g[n];
}

Try it online! (13s for n = 24)
Based on the faster Python implementation in my other post. Edit the second line to #define S 3 on your 8-core machine and compile with g++ -pthread -march=native -O2 -ftree-vectorize.
The splits the work in half, so the value of S should be  log2(#threads). The types can easily be changed between int, long, float, and double by modifying the value of #define TYPE.

This is the leading answer so far. Your code doesn't actually read in the input as specified as it can't cope with spaces. I had to do e.g. tr -d \  < matrix52.txt > matrix52s.txt

@Lembik Sorry, only used it against the spaceless matrix of size 24. Fixed now to work with spaces though.

C
Another impl of Andreas Björklund's paper, which is much easier to understand if you also look at Christian Sievers's Haskell code. For the first few levels of the recursion, it distributes round-robin threads over available CPUs. The last level of the recursion, which accounts for half of the invocations, is optimised by hand.
Compile with: gcc -O3 -pthread -march=native; thanks @Dennis for a 2x speed-up
n=24 in 24s on TIO
#define _GNU_SOURCE
#include<sched.h>
#include<stdio.h>
#include<stdlib.h>
#include<memory.h>
#include<unistd.h>
#include<pthread.h>
#define W while
#define R return
#define S static
#define U (1<<31)
#define T(i)((i)*((i)-1)/2)
typedef int I;typedef long L;typedef char C;typedef void V;
I n,ncpu,icpu;
S V f(I*x,I*y,I*z){I i=n,*z1=z+n;W(i){I s=0,*x2=x,*y2=y+--i;W(y2>=y)s+=*x2++**y2--;*z1--+=s;}}
typedef struct{I m;V*a;V*p;pthread_barrier_t*bar;I r;}A;S V*(h1)(V*);
I h(I m,I a[][n+1],I*p){
 m-=2;I i,j,k=0,u=T(m),v=u+m,b[u][n+1],q[n+1];
 if(!m){I*x=a[v+m],*y=p+n-1,s=0;W(y>=p)s-=*x++**y--;R s;}
 memcpy(b,a,sizeof(b));memcpy(q,p,sizeof(q));f(a[v+m],p,q);
 for(i=1;i<m;i++)for(j=0;j<i;j++){f(a[u+i],a[v+j],b[k]);f(a[u+j],a[v+i],b[k]);k++;}
 if(2*n-m>8)R h(m,a,p)-h(m,b,q);
 pthread_barrier_t bar;pthread_barrier_init(&bar,0,2);pthread_t th;
 cpu_set_t cpus;CPU_ZERO(&cpus);CPU_SET(icpu++%ncpu,&cpus);
 pthread_attr_t attr;pthread_attr_init(&attr);
 pthread_attr_setaffinity_np(&attr,sizeof(cpu_set_t),&cpus);
 A arg={m,a,p,&bar};pthread_create(&th,&attr,h1,&arg);
 I r=h(m,b,q);pthread_barrier_wait(&bar);pthread_join(th,0);pthread_barrier_destroy(&bar);
 R arg.r-r;
}
S V*h1(V*x0){A*x=(A*)x0;x->r=h(x->m,x->a,x->p);pthread_barrier_wait(x->bar);R 0;}
I main(){
 ncpu=sysconf(_SC_NPROCESSORS_ONLN);
 S C s[200000];I i=0,j=0,k,l=0;W((k=read(0,s+l,sizeof(s)-l))>0)l+=k;
 n=1;W(s[i]!=']')n+=s[i++]==',';n/=2;
 I a[T(2*n)][n+1];memset(a,0,sizeof(a));k=0;
 for(i=0;i<2*n;i++)for(j=0;j<2*n;j++){
  W(s[k]!='-'&&(s[k]<'0'||s[k]>'9'))k++;
  I v=0,m=s[k]=='-';k+=m;W(k<l&&('0'<=s[k]&&s[k]<='9'))v=10*v+s[k++]-'0';
  if(i>j)*a[T(i)+j]=v*(1-2*m);
 }
 I p[n+1];memset(p,0,sizeof(p));*p=1;
 printf("%d\n",(1-2*(n&1))*h(2*n,a,p));
 R 0;
}

Algorithm:
The matrix, which is symmetric, is stored in lower-left triangular form. Triangle indices i,j correspond to linear index T(max(i,j))+min(i,j) where T is a macro for i*(i-1)/2.
Matrix elements are polynomials of degree n. A polynomial is represented as an array of coefficients ordered from the constant term (p[0]) to xn's coefficient (p[n]).
The initial -1,0,1 matrix values are first converted to const polynomials.
We perform a recursive step with two arguments: the half-matrix (i.e. triangle) a of polynomials and a separate polynomial p (referred to as beta in the paper).
We reduce the size-m problem (initially m=2*n) recursively to two problems of size m-2 and return the difference of their hafnians. One of them is to use the same a without its last two rows, and the very same p. Another is to use the triangle b[i][j] = a[i][j] + shmul(a[m-1][i],a[m-2][j]) + shmul(a[m-1][j],a[m-2][i]) (where shmul is the shift-multiply operation on polynomials - it's like polynomial product as usual, additionally multiplied by the variable "x"; powers higher than x^n are ignored), and the separate polynomial q = p + shmul(p,a[m-1][m-2]). When recursion hits a size-0 a, we return the major coefficient of p: p[n].
The shift-and-multiply operation is implemented in function f(x,y,z). It modifies z in-place. Loosely speaking, it does z += shmul(x,y). This seems to be the most performance-critical part.
After the recursion has finished, we need to fix the sign of the result by multiplying by (-1)n.

Could you show an explicit example of the input your code accepts? Say for a 2 by 2 matrix.  Also, you seem to have golfed your code! (This is a fastest-code challenge, not a golf challenge.)

@Lembik For the record, as I said in chat, the input is in the same format as the examples - json (actually, it only reads the numbers and uses n=sqrt(len(input))/2). I usually write short code, even when golfing is not a requirement.

What's the largest size matrix this new code should support?

@Lembik the only hard-coded limit is the size of the input buffer, in which I left plenty of room for 100x100 matrix (n=50), so it should be practically unlimited

-march=native will make a big difference here. At least on TIO, it nearly cuts the wall time in half.

Also, at least on TIO, the executable produced by gcc will be even faster.

@Dennis I used -march=native when testing.

Python 3
This computes haf(A) as a memoised sum(A[i][j] * haf(A without rows and cols i and j)).
#!/usr/bin/env python3
import json,sys
a=json.loads(sys.stdin.read())
n=len(a)//2
b={0:1}
def haf(x):
 if x not in b:
  i=0
  while not x&(1<<i):i+=1
  x1=x&~(1<<i)
  b[x]=sum(a[i][j]*haf(x1&~(1<<j))for j in range(2*n)if x1&(1<<j)and a[i][j])
 return b[x]
print(haf((1<<2*n)-1))

Python
This is pretty much a straight-forward, reference implementation of Algorithm 2 from the mentioned paper. The only changes were to only keep the current value of B, dropping the values of β by only updating g when i ∈ X, and truncated polynomial multiplication by only calculating the values up to degree n.
from itertools import chain,combinations

def powerset(s):
    return chain.from_iterable(combinations(s, k) for k in range(len(s)+1))

def padd(a, b):
    return [a[i]+b[i] for i in range(len(a))]

def pmul(a, b):
    n = len(a)
    c = [0]*n
    for i in range(n):
        for j in range(n):
            if i+j < n:
                c[i+j] += a[i]*b[j]
    return c

def hafnian(m):
    n = len(m) / 2
    z = [[[c]+[0]*n for c in r] for r in m]
    h = 0
    for x in powerset(range(1, n+1)):
        b = z
        g = [1] + [0]*n
        for i in range(1, n+1):
            if i in x:
                g = pmul(g, [1] + b[0][1][:n])
                b = [[padd(b[j+2][k+2], [0] + padd(pmul(b[0][j+2], b[1][k+2]), pmul(b[0][k+2], b[1][j+2]))[:n]) if j != k else 0 for k in range(2*n-2*i)] for j in range(2*n-2*i)]
            else:
                b = [r[2:] for r in b[2:]]
        h += (-1)**(n - len(x)) * g[n]
    return h

Try it online!
Here is a faster version with some of the easy optimizations.
def hafnian(m):
  n = len(m)/2
  z = [[0]*(n+1) for _ in range(n*(2*n-1))]
  for j in range(1, 2*n):
    for k in range(j):
      z[j*(j-1)/2+k][0] = m[j][k]
  return solve(z, 2*n, 1, [1] + [0]*n, n)

def solve(b, s, w, g, n):
  if s == 0:
    return w*g[n]
  c = [b[(j+1)*(j+2)/2+k+2][:] for j in range(1, s-2) for k in range(j)]
  h = solve(c, s-2, -w, g, n)
  e = g[:]
  for u in range(n):
    for v in range(n-u):
      e[u+v+1] += g[u]*b[0][v]
  for j in range(1, s-2):
    for k in range(j):
      for u in range(n):
        for v in range(n-u):
          c[j*(j-1)/2+k][u+v+1] += b[(j+1)*(j+2)/2][u]*b[(k+1)*(k+2)/2+1][v] + b[(k+1)*(k+2)/2][u]*b[(j+1)*(j+2)/2+1][v]
  return h + solve(c, s-2, w, e, n)

Try it online!
For added fun, here is a reference implementation in J.

This is pretty slow from all the list comprehensions and from computing equivalent values across the diagonal, so there's no need to benchmark this.

Pretty awesome!

Very nice! I tried a similar thing with sympy which was shockingly slow and, while being correct for the small examples, returned - after a long time - a wrong result for the 24*24 matrix. I have no idea what's going on there. - By the description above Algorithm 2, the polynomial multiplication there is already meant to be truncated.

This code is actually strangely slow. Even for n = 20 it takes 22 seconds compared to essentially instant for ngn's python code.  Are you sure it isn't doing too much work somewhere?

In pmul, use for j in range(n-i): and avoid the if

It also helps to replace range (returns a list) with xrange (returns a generator), as its arguments are rather large.

Just squeezes n = 28 with those improvement + pypy.

I still don't understand why this is so much slower than the other implementations of the same algorithm. Any ideas?

@Lembik It computes the whole matrix; for a factor of about two replace j != k with j < k. It copies a submatrix in the else case which can be avoided when we handle and delete the last two instead of the first two rows and columns. And when it computes with x={1,2,4} and later with x={1,2,4,6} then it repeats its computations up to i=5. I  replaced the structure of the two outer loops with first looping on i and then recursively assuming i in X and i not in X. - BTW, It might be interesting to look at the growth of the time needed compared to the other slower programs.

@Lembik I improved it a bit with some of the easy optimizations. You can cut the calculations in half by only using the values in either the upper or lower part across the diagonal since each submatrix will be symmetric. Using the lower triangle makes indexing easy since each row will start at a triangle number. As already implemented by others, recursion instead of iterating over 2^n binary numbers will keep track of previous states at each bit. And instead of counting the zeros in each bit, i just keep track of the sign and negate it accordingly at each recursive call.

That's a huge improvement!

What are the dimension of c? I can see that c is a list of lists and there are sum_{i=1}^{s-2} i = (s-2)(s-1)/2 lists in it I think. But how long is each list?

Actually, would you be able (please) to write out c = [b[(j+1)*(j+2)/2+k+2][:] for j in range(1, s-2) for k in range(j)] as nested for loops? I am trying to convert your code to cython and am stuck on that line.

@Anush c is the concatenation of the rows of the lower half of a matrix, hence the triangle number of entries. Each entry represents a polynomial of degree at most n, so they are lists of length n+1. The code line should be equivalent to something like c=[]; for j in...: for k in...: c+= b[...][:] (no idea if that's the best way...)

@Anush Oh that was wrong, it should be c+=[b[...][:]] or maybe better c.append(b[...][:])

@ChristianSievers. Thank you. One issue is that c is sometimes the empty list. That is not a list of lists at all.

@Anush Yes, when s=2, one step before the end of the recursion, c is a list of zero lists. That is as expected.

@Anush Christian explained it all.

Octave
This is basically a copy of Dennis' entry, but optimized for Octave. The main optimization is done by using the full input matrix (and its transpose) and recursion using only matrix indices, rather than creating reduced matrices.
The main advantage is reduced copying of matrices. While Octave does not have a difference between pointers/references and values and functionally only does pass-by-value, it's a different story behind the scenes. There, copy-on-write (lazy copy) is used. That means, for the code a=1;b=a;b=b+1, the variable b is only copied to a new location at the last statement, when it is changed. Since matin and matransp are never changed, they will never by copied. The disadvantage is that the function spends more time calculating the correct indices. I may have to try different variations between numerical and logical indices to optimize this.
Important note: input matrix should be int32! Save the function in a file called haf.m
function h=haf(matin,indices,matransp,transp)

    if nargin-4
        indices=int32(1:length(matin));
        matransp=matin';
        transp=false;
    end
    if(transp)
        matrix=matransp;
    else
        matrix=matin;
    end
    ind1=indices(1);
    n=length(indices);
    if n==2
        h=matrix(ind1,indices(2));
        return
    end
    h=0*matrix(1);
    for j=1:(n-1)
        indj=indices(j+1);
        k=matrix(ind1,indj);
        if logical(k)
            indicestemp=true(n,1);
            indicestemp(1:j:j+1)=false;
            h=h+k.*haf(matin,indices(indicestemp),matransp,~transp);
        end
    end
end

Example test script:
matrix = int32([0 0 1 -1 1 0 -1 -1 -1 0 -1 1 0 1 1 0 0 1 0 0 1 0 1 1;0 0 1 0 0 -1 -1 -1 -1 0 1 1 1 1 0 -1 -1 0 0 1 1 -1 0 0;-1 -1 0 1 0 1 -1 1 -1 1 0 0 1 -1 0 0 0 -1 0 -1 1 0 0 0;1 0 -1 0 1 1 0 1 1 0 0 0 1 0 0 0 1 -1 -1 -1 -1 1 0 -1;-1 0 0 -1 0 0 1 -1 0 1 -1 -1 -1 1 1 0 1 1 1 0 -1 1 -1 -1;0 1 -1 -1 0 0 1 -1 -1 -1 0 -1 1 0 0 0 -1 0 0 1 0 0 0 -1;1 1 1 0 -1 -1 0 -1 -1 0 1 1 -1 0 1 -1 0 0 1 -1 0 0 0 -1;1 1 -1 -1 1 1 1 0 0 1 0 1 0 0 0 0 1 0 1 0 -1 1 0 0;1 1 1 -1 0 1 1 0 0 -1 1 -1 1 1 1 0 -1 -1 -1 -1 0 1 1 -1;0 0 -1 0 -1 1 0 -1 1 0 1 0 0 0 0 0 1 -1 0 0 0 1 -1 -1;1 -1 0 0 1 0 -1 0 -1 -1 0 0 1 0 0 -1 0 -1 -1 -1 -1 -1 1 -1;-1 -1 0 0 1 1 -1 -1 1 0 0 0 -1 0 0 -1 0 -1 -1 0 1 -1 0 0;0 -1 -1 -1 1 -1 1 0 -1 0 -1 1 0 1 -1 -1 1 -1 1 0 1 -1 1 -1;-1 -1 1 0 -1 0 0 0 -1 0 0 0 -1 0 0 -1 1 -1 -1 0 1 0 -1 -1;-1 0 0 0 -1 0 -1 0 -1 0 0 0 1 0 0 1 1 1 1 -1 -1 0 -1 -1;0 1 0 0 0 0 1 0 0 0 1 1 1 1 -1 0 0 1 -1 -1 -1 0 -1 -1;0 1 0 -1 -1 1 0 -1 1 -1 0 0 -1 -1 -1 0 0 -1 1 0 0 -1 -1 1;-1 0 1 1 -1 0 0 0 1 1 1 1 1 1 -1 -1 1 0 1 1 -1 -1 -1 1;0 0 0 1 -1 0 -1 -1 1 0 1 1 -1 1 -1 1 -1 -1 0 1 1 0 0 -1;0 -1 1 1 0 -1 1 0 1 0 1 0 0 0 1 1 0 -1 -1 0 0 0 1 0;-1 -1 -1 1 1 0 0 1 0 0 1 -1 -1 -1 1 1 0 1 -1 0 0 0 0 0;0 1 0 -1 -1 0 0 -1 -1 -1 1 1 1 0 0 0 1 1 0 0 0 0 1 0;-1 0 0 0 1 0 0 0 -1 1 -1 0 -1 1 1 1 1 1 0 -1 0 -1 0 1;-1 0 0 1 1 1 1 0 1 1 1 0 1 1 1 1 -1 -1 1 0 0 0 -1 0])

tic
i=1;
while(toc<60)
    tic
    haf(matrix(1:i,1:i));
    i=i+1;
end

I have tried this out using TIO and MATLAB (I've actually never installed Octave). I imagine getting it to work is as simple as sudo apt-get install octave. The command octave will load the Octave GUI. If it's any more complicated than this, I will delete this answer until I've provided more detailed installation instructions.

Rust
A port of Mr. Xcoder's example Python code. Naive brute force, so slow.
It needs much optimization.
src/main.rs
extern crate permutohedron;
extern crate num_bigint;
extern crate num_traits;

use permutohedron::Heap;
use num_bigint::BigInt;
use num_traits::pow::Pow;
use num_traits::identities::One;
use num_traits::identities::Zero;

fn hafnian(matrix: Vec<Vec<i32>>) -> BigInt {
    let mut my_sum = BigInt::zero();
    let n = matrix.len() / 2;
    let mut data: Vec<usize> = (0..n*2).collect();
    let heap: Heap<'_, Vec<usize>, usize> = Heap::new(&mut data);

    for permutation in heap {
        let mut prod = BigInt::one();
        for j in 0..n {
            prod *= BigInt::from(matrix[permutation[2*j]][permutation[2*j+1]]);
        }
        my_sum += prod;
    }

    let factorial_n = (1..=n).fold(BigInt::one(), |f, i| f * BigInt::from(i));
    my_sum / (factorial_n * BigInt::from(2).pow(n as u32))
}

fn main() {
    println!("{:?}", hafnian(vec![
        vec![-1, 1, 1, -1, 0, 0, 1, -1],
        vec![1, 0, 1, 0, -1, 0, -1, -1],
        vec![1, 1, -1, 1, -1, -1, 0, -1],
        vec![-1, 0, 1, -1, -1, 1, -1, 0],
        vec![0, -1, -1, -1, -1, 0, 0, -1],
        vec![0, 0, -1, 1, 0, 0, 1, 1],
        vec![1, -1, 0, -1, 0, 1, 1, 0],
        vec![-1, -1, -1, 0, -1, 1, 0, 1]
    ]));

    println!("{:?}", hafnian(vec![
        vec![1, 1, 0, 0, 0, 0, 0, 1, 0, 0],
        vec![1, 1, -1, 0, -1, 1, 1, 1, 0, -1],
        vec![0, -1, -1, -1, 0, -1, -1, 0, -1, 1],
        vec![0, 0, -1, 1, -1, 1, -1, 0, 1, -1],
        vec![0, -1, 0, -1, -1, -1, -1, 1, -1, 1],
        vec![0, 1, -1, 1, -1, 1, -1, -1, 1, -1],
        vec![0, 1, -1, -1, -1, -1, 1, 0, 0, 0],
        vec![1, 1, 0, 0, 1, -1, 0, 1, 1, -1],
        vec![0, 0, -1, 1, -1, 1, 0, 1, 1, 1],
        vec![0, -1, 1, -1, 1, -1, 0, -1, 1, 1]
    ]));

    println!("{:?}", hafnian(vec![
        vec![-1, 0, -1, -1, 0, -1, 0, 1, -1, 0, 0, 0],
        vec![0, 0, 0, 0, 0, -1, 0, 1, -1, -1, -1, -1],
        vec![-1, 0, 0, 1, 0, 0, 0, 1, -1, 1, -1, 0],
        vec![-1, 0, 1, -1, 1, -1, -1, -1, 0, -1, -1, -1],
        vec![0, 0, 0, 1, 0, 0, 0, 0, 0, 1, -1, 0],
        vec![-1, -1, 0, -1, 0, 0, 1, 1, 1, 1, 1, 0],
        vec![0, 0, 0, -1, 0, 1, 1, -1, -1, 0, 1, 0],
        vec![1, 1, 1, -1, 0, 1, -1, 1, -1, -1, -1, -1],
        vec![-1, -1, -1, 0, 0, 1, -1, -1, -1, 1, -1, 0],
        vec![0, -1, 1, -1, 1, 1, 0, -1, 1, -1, 1, 1],
        vec![0, -1, -1, -1, -1, 1, 1, -1, -1, 1, 0, -1],
        vec![0, -1, 0, -1, 0, 0, 0, -1, 0, 1, -1, 1]
    ]));

    println!("{:?}", hafnian(vec![
        vec![-1, 1, 0, 1, 0, -1, 0, 0, -1, 1, -1, 1, 0, -1],
        vec![1, -1, 1, -1, 1, 1, -1, 0, -1, 1, 1, 0, 0, -1],
        vec![0, 1, 1, 1, -1, 1, -1, -1, 0, 0, -1, 0, -1, -1],
        vec![1, -1, 1, -1, 1, 0, 1, 1, -1, -1, 0, 0, 1, 1],
        vec![0, 1, -1, 1, 0, 1, 0, 1, -1, -1, 1, 1, 0, -1],
        vec![-1, 1, 1, 0, 1, 1, -1, 0, 1, -1, -1, -1, 1, -1],
        vec![0, -1, -1, 1, 0, -1, -1, -1, 0, 1, -1, 0, 1, -1],
        vec![0, 0, -1, 1, 1, 0, -1, 0, 0, -1, 0, 0, 0, 1],
        vec![-1, -1, 0, -1, -1, 1, 0, 0, 1, 1, 0, 1, -1, 0],
        vec![1, 1, 0, -1, -1, -1, 1, -1, 1, 1, 1, 0, 1, 0],
        vec![-1, 1, -1, 0, 1, -1, -1, 0, 0, 1, -1, 0, -1, 0],
        vec![1, 0, 0, 0, 1, -1, 0, 0, 1, 0, 0, 1, 1, 1],
        vec![0, 0, -1, 1, 0, 1, 1, 0, -1, 1, -1, 1, 1, -1],
        vec![-1, -1, -1, 1, -1, -1, -1, 1, 0, 0, 0, 1, -1, -1]
    ]));

}

Cargo.toml
[package]
name = "rust_hello"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
# rand = "0.8.0"
# hyper = "0.13"
# tokio = { version = "0.2", features = ["full"] }
# rayon = "1.5.1"
# ndarray = "0.15.4"
# statrs = "0.13.0"
# ndarray-stats = "0.4.0"
# ndarray-linalg = "0.15"
# bitvec = "1.0.1"
# uint = "0.9"
# pariter = "0.5.1"
# rug = { version = "1.19.0", features = ["integer"], default-features = false }
# kd-tree = "0.5.1"
# time = "0.3"

permutohedron = "0.2.4"
num-bigint = "0.3.3"
num-traits = "0.2.14"

Build and running
# win10 environment

$ cargo  build
$ target\debug\rust_hello.exe
BigInt { sign: Plus, data: BigUint { data: [4] } }
BigInt { sign: Minus, data: BigUint { data: [13] } }
......

Mathematica
Use the recursive formula.
Try it online!
haf[matrix_?MatrixQ] :=
  haf[matrix] = Module[{n, h, j, copy}, n = Length[matrix];
    If[n == 2, Return[matrix[[1, 2]]]];
    h = 0;
    For[j = 2, j <= n, j++, If[matrix[[1, j]] == 0, Continue[]];
     copy = Delete[matrix, {{1}, {j}}];
     copy = Transpose[copy];
     copy = Delete[copy, {{1}, {j}}];
     h += matrix[[1, j]]*haf[copy];];
    h];

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


text:
Count stacking sequences
Given a list of stack heights, calculate the number of ways those heights could have been arrived at by stacking blocks one at a time. Shortest code wins.
Test cases:
[2, 2] 6
[3,3,3] 1680
[1,5,9,1] 480480
[] 1
[10] 1
[2,2,2,10] 720720

Reference Python implementation:
def stacking_count(stacks):
     if sum(stacks) == 0:
         return 1
     count = 0
     for i, n in enumerate(stacks):
         if n == 0:
             continue
         stacks[i] -= 1
         count += stacking_count(stacks)
         stacks[i] += 1
     return count

Python 3, 85 bytes
f=lambda a:sum(f(a[:i]+[a[i]-1]+a[i+1:])for i in range(len(a))if a[i])if sum(a)else 1

Try it online!

Jelly, 6 bytes
;@S!:/

Try it online!
-7 bytes thanks to Jonathan Allan

...and hence 6 bytes

@JonathanAllan oh wait there is a mathematical approach lol

How about one with only ASCII and what looks almost like a list of emoticons? ;@S!:/

@JonathanAllan Ooh cool, sure. Thanks!

Golfier TIO link as well :P