text:
Is it a valid chess move?
Alternate name: ChessMoveQ
Given a list of up to 32 elements, each consisting of 4 elements, and a second list with 4 elements, determine whether the move detailed in the second input is a valid chess move.
The first list indicates the position of all 32 pieces on the board. Each element will follow the structure <colour>, <piece-name>, <x-coord>, <y-coord>, such as ["W", "K", 5, 1], which indicates that the white king is on 5, 1 (e1 on a normal chess board). All elements of the first input will be unique. <x-coord> and <y-coord> will always be between 1 and 8. One example would be:
[["B", "K", 3, 8], ["B", "Q", 1, 5], ["B", "N", 4, 7], ["B", "N", 7, 8],
 ["B", "B", 2, 4], ["B", "R", 4, 8], ["B", "R", 8, 8], ["B", "P", 1, 7],
 ["B", "P", 2, 7], ["B", "P", 3, 6], ["B", "P", 5, 6], ["B", "P", 6, 7],
 ["B", "P", 7, 7], ["B", "P", 8, 7], ["W", "K", 5, 1], ["W", "Q", 6, 3],
 ["W", "N", 3, 3], ["W", "B", 5, 2], ["W", "B", 6, 4], ["W", "R", 1, 1],
 ["W", "R", 8, 1], ["W", "P", 1, 3], ["W", "P", 2, 2], ["W", "P", 3, 2],
 ["W", "P", 4, 4], ["W", "P", 6, 2], ["W", "P", 7, 2], ["W", "P", 8, 3]]

which would represent the board:

The second input will consist of the same structures as the sublists of the first one, but rather than the x and y coordinates indicating where the piece is, they are indicating where it is trying to move to.
For the above example, a valid move could be ["W", "B", 4, 3] (bishop moves one square forward and to the left), and an invalid move could be ["B", "R", 4, 1] as the rook would have to move through the knight, and the pawn to get to the square. As the move could refer to multiple pieces at times, you must test whether any of the specified pieces can make the move, not just one of them. For instance, the first example is valid for only one bishop, but it is still a valid move. However, neither black rook can perform the second move, so it is invalid.
Your task is to determine whether the move detailed in the second input is a valid chess move. The validity of a rule varies, depending on the piece trying to move (click on the name of the piece for a diagram of valid moves):

Any piece: No pieces can move onto an already occupied square, or off the board, unless that square is occupied by a piece from the other colour. For example, a white piece may move onto a square occupied by a black piece, but not a white piece. Additionally, no pieces, except for Knights, can move to squares which are directly obstructed by another piece.

A move by piece B to square C is "directly obstructed" by piece A if A is directly, in a straight (orthogonal or diagonal) line, between B and C.

Any piece: The position of the king can also affect the validity of a piece's move. If either of these two conditions are met, the move is invalid:

Exposing the king to check, by moving a piece on the same side as the endangered king. This only applies if a non-opposing piece makes the move, rather than an opposing piece moving to place the king into check.
Leaving the king in check, in which case it has to move out of check. Therefore, if the king is in check and the move dictates that another piece moves, it is an invalid move, unless the other piece is preventing check. A piece can prevent check in one of two ways: either it takes the piece performing check, or it obstructs the path between the piece performing check and the king.
A "check" is a situation in which the king's opponent could (if it was their turn to move) legally move a piece onto that king. This rule does not apply recursively, i.e. a king is in check even if the move by the opponent onto that king would leave their own king in check.

Pawns: A pawn can move forwards (i.e. upwards if white, downwards if black) one square to an unoccupied square. There are also three special situations:

If the pawn hasn't yet moved (you can determine this using the Y-coordinate; white pawns haven't moved if their Y-coordinate is 2, black pawns haven't moved if their Y-coordinate is 7), the pawn is allowed to move two squares forward to an unoccupied square.
If there is an opponent's piece diagonally in front of the pawn (i.e. on the square to the north-west or north-east of the pawn if it is white, or to the south-west or south-east if it is black), the pawn is allowed to move onto the occupied square in question.
If a pawn moves to the final Y-coordinate (8 for white, or 1 for black) in normal chess rules it must be promoted to a queen, rook, knight, or bishop of the same color. For the purposes of this question, the choice of promotion is irrelevant to whether the move is valid or not (and cannot be expressed in the input format), but pawn moves that would result in promotion must be allowed.

Bishops: Bishops can move between 1 and 8 squares along any continuous non-obstructed intercardinal (i.e. diagonal) path.
Knights: Knights can move in an L shape, consisting of either of the following (equivalent) moves:A single square in any cardinal direction, followed by a 90/270° turn, followed by a final move of 2 squares forward.2 squares in any cardinal direction, followed by a 90/270° turn, followed by a final move of a single square forward.
(Remember that the path of a knight cannot be blocked by intervening pieces, although its final square must still be legal.)
Rooks: Rooks can move between 1 and 8 squares along any continuous non-obstructed cardinal path.
Queens: Queens can move between 1 and 8 squares along any continuous cardinal or intercardinal (i.e. diagonal) non-obstructed path.
Kings: Kings move like queens, except that they are limited to moving only one square per move (i.e. a king can only move to cardinally or diagonally adjacent squares). As a reminder, you cannot make a move that leaves your king in check; thus you cannot move your king into check, either.

The rules of chess also contain special moves called "castling" and "en passant". However, because the legality of these moves depend on the history of the game, not just the current position (and because castling requires moving two pieces at once, which doesn't fit with the input format), you should consider neither of these moves to exist (i.e. a move that would be castling or en passant should be considered illegal).
You may output any two distinct results to indicate the validity of a move, and you may take input in a method you want. You may also choose 0-indexing rather than 1-indexing for the positions if you prefer. This is a code-golf, so shortest code wins!
Test cases
Board
Move => Output (Reason)

[["B", "K", 3, 8], ["B", "Q", 1, 5], ["B", "N", 4, 7], ["B", "N", 7, 8], ["B", "B", 2, 4], ["B", "R", 4, 8], ["B", "R", 8, 8], ["B", "P", 1, 7], ["B", "P", 2, 7], ["B", "P", 3, 6], ["B", "P", 5, 6], ["B", "P", 6, 7], ["B", "P", 7, 7], ["B", "P", 8, 7], ["W", "K", 5, 1], ["W", "Q", 6, 3], ["W", "N", 3, 3], ["W", "B", 5, 2], ["W", "B", 6, 4], ["W", "R", 1, 1], ["W", "R", 8, 1], ["W", "P", 1, 3], ["W", "P", 2, 2], ["W", "P", 3, 2], ["W", "P", 4, 4], ["W", "P", 6, 2], ["W", "P", 7, 2], ["W", "P", 8, 3]]
["W", "R", 8, 2] => True (The rook on h1 can move forward one)

[['B', 'K', 6, 8], ['B', 'Q', 1, 7], ['B', 'N', 1, 3], ['B', 'N', 7, 1], ['B', 'B', 8, 8], ['B', 'B', 2, 5], ['B', 'R', 4, 3], ['B', 'R', 1, 5], ['B', 'P', 5, 5], ['B', 'P', 7, 2], ['B', 'P', 5, 7], ['B', 'P', 5, 6], ['B', 'P', 4, 4], ['W', 'K', 7, 3], ['W', 'Q', 3, 2], ['W', 'N', 4, 8], ['W', 'N', 7, 5], ['W', 'B', 1, 1], ['W', 'B', 8, 1], ['W', 'R', 1, 8], ['W', 'R', 3, 7], ['W', 'P', 8, 2], ['W', 'P', 6, 3], ['W', 'P', 4, 2], ['W', 'P', 1, 4], ['W', 'P', 8, 7]]
['W', 'N', 1, 5] => False (Neither knight to move to a5 from where they are)

[['B', 'K', 7, 3], ['B', 'Q', 2, 4], ['B', 'N', 5, 2], ['B', 'N', 1, 6], ['B', 'B', 7, 7], ['B', 'B', 1, 8], ['W', 'K', 7, 1], ['W', 'Q', 6, 1], ['W', 'N', 5, 6], ['W', 'N', 3, 3], ['W', 'B', 2, 2], ['W', 'B', 6, 5]]
['B', 'K', 8, 3] => False (The white bishop would put the king in check)

[['B', 'K', 7, 6], ['B', 'Q', 8, 3], ['B', 'N', 7, 7], ['B', 'N', 8, 7], ['B', 'B', 2, 2], ['B', 'B', 3, 8], ['B', 'R', 1, 1], ['B', 'R', 1, 6], ['B', 'P', 8, 5], ['B', 'P', 4, 3], ['B', 'P', 8, 6], ['W', 'K', 7, 8], ['W', 'Q', 7, 2], ['W', 'N', 5, 1], ['W', 'N', 4, 6], ['W', 'B', 1, 2], ['W', 'B', 2, 6], ['W', 'R', 4, 4], ['W', 'R', 3, 6], ['W', 'P', 5, 2], ['W', 'P', 6, 2]]
['B', 'N', 5, 8] => False (The white queen currently has the king in check, and this move doesn't prevent that)

[['B', 'K', 7, 6], ['B', 'Q', 8, 3], ['B', 'N', 7, 7], ['B', 'N', 8, 7], ['B', 'B', 2, 2], ['B', 'B', 3, 8], ['B', 'R', 1, 1], ['B', 'R', 1, 6], ['B', 'P', 8, 5], ['B', 'P', 4, 3], ['B', 'P', 8, 6], ['W', 'K', 7, 8], ['W', 'Q', 7, 2], ['W', 'N', 5, 1], ['W', 'N', 4, 6], ['W', 'B', 1, 2], ['W', 'B', 2, 6], ['W', 'R', 4, 4], ['W', 'R', 3, 6], ['W', 'P', 5, 2], ['W', 'P', 6, 2]]
['B', 'N', 7, 5] => True (The king is in check, and the knight blocks that)

[['B', 'K', 8, 3], ['B', 'Q', 6, 5], ['B', 'N', 7, 8], ['B', 'N', 3, 7], ['B', 'B', 4, 1], ['B', 'B', 1, 1], ['W', 'K', 7, 7], ['W', 'Q', 7, 1], ['W', 'N', 2, 2], ['W', 'N', 1, 3], ['W', 'B', 3, 5]]
['B', 'B', 2, 2] => True (takes the white knight)

[['B', 'K', 6, 1], ['B', 'Q', 6, 2], ['W', 'K', 8, 1]]
['B', 'Q', 7, 1] => True (Smallest checkmate possible, in terms of bounding box)

This challenge was sandboxed. It received downvotes, without any explanation, so I decided to post it anyway

"A piece on the same side moves, exposing the king to check." - this wording doesn't seem to fit now that you've moved the heading it goes under. I'd change it to something such as "Moving this piece will expose the king to check"

"you may take input in a method you want" - does this mean we can move away from the specified array of [up to] 32 arrays, or just that we may, for example, take <colour> as a boolean?

@JonathanAllan you may take input in any such way in which it is clear what the inputs are, and that it follows the rules on meta. You could take colour as a boolean if you want, or you could take the first input as a flat list, or any other similarly flexible way.

So, would the first field of a FEN record be acceptable as the first of the two inputs?

@JonathanAllan I think that's an acceptable way to take input, yes.

So en passant and castling should be treated as an invalid move?

@SebastianLamerichs Yes, because it requires more information than simply one move (such as the previous moves)

Just so I understand it correctly: If I get a second input for a white knight and a target position, and there are two white knights on the board, I have to check whether that target position is valid for any of them?

@FelixPalmen Correct.

Can we get a 2d array of pieces as input?

@ovs could you give an example? I'm not sure I understand

this for your example board.

@ovs Yes, that seems to be acceptable

Regex (PCRE2), 931 925 837 bytes
This solution departs from the problem statement in that two board states are passed to the regex, instead of one board state and a move. The move is inferred from the difference between the two board states. So I made it the job of the TIO program to take the test cases in the format provided by this question, find all instances of the described piece on the board, and with each one, try moving it to the destination position and evaluating the regex with that possibility, finding if any are reported by the regex as valid. If this is not okay, let me know; it's possible to implement a regex as position + move, but would be much less elegant and require serious refactoring.
The board is represented in 8×8 ASCII where white pieces are uppercase and black are lowercase: Pawn, kNight, Bishop, Rook, Queen, King. Black's side (the 8th rank) is on the top and white's side (the 1st rank) is on the bottom. Each rank is separated by a newline, and empty squares are marked as -. The two board positions are separated by an extra newline.
The actual aim of this project is to validate entire games, not just single moves. See below for the current state of progress.
()?(?>|((.|
(?=.)){2})((?=(\X{72})-))((?=(?(1)[-a-z]|[-A-Z])))((?5)(?(?=(.*
)
)[qnrb]|p))((?5)(?(?=(?8){8}
)[QNRB]|P)))(?>((.)(?=(?5)\11)|(?(m)$)((?(1)(-(?=(?9))(?=(?3){8}((?3){9})?P(?4))(?(-1)(?=(?8){4}
))|[a-z](?=(?9))(?=(?3){7}(?2)?P(?4)))|(p(?4)((?=(?3){8}((?3){9})?-(?7))(?(-1)(?=(?8){7}
))|(?=(?3){7}(?2)?[A-Z](?7)))))|(?<e>(?6).)?(?=(?i:(?|(?(e)|(B|Q))(?27)(?(e)(B|Q))|(?(e)|(R|Q))(?31)(?(e)(R|Q))|(?(e)|(N))(?34)(?(e)(N))|(?(e)|(K))(?35)?(?(e)(K))))(?(e)(?<=(?!(?6)).)(?4)|(?6).(?5)\19))(?(e)(?=(?5)\20)|(?!(?6)).(?4)))(?<m>)|(?(+1)$)(.))+
)+\k<m>
(?!\X{0,70}((?(1)p|k)(?=(?3){7}(?2)?(?(1)K|P))|(?i:(?<E>(?!(?6))K)?((?(E)|((?6)[BQ]))(()?((?(-1)-)(?3){7}(?(-2)(?2)))+)(?(E)(?-4))|(?(E)|((?6)[RQ]))(-*|((?(-1)-)(?3){8})+)(?(E)(?-3))|(?(E)|((?6)N))((?<=..)(?2){3}|(?=.)(?2){5}|(?2){8}(?2)?)(?(E)(?-2)))(?(E)|(?&E))|K((?3){7,9})?K)))

Try it online!
Pretty-printed, and partially ungolfed (absolute backrefs changed to relative, and capturing groups changed to non-capturing, or in some cases atomic for speed):
# Chess move validation regex (PCRE)
()?                 # decide whether to evaluate this as white's or black's move; \1 set = white, \1 unset (NPCG) = black
(?>|                # subroutines:
  ((.|\n(?=.)){2})                  # (?3) = for moving within the board, without wrapping to the next board, (?2) = (?3){2}
  ((?=                              # (?4) = assert that position of just-consumed piece is vacated on the next turn
    (\X{72})                        # (?5) = skip to the position of the just-consumed piece on the next turn
  -))
  ((?=(?(1)[-a-z]|[-A-Z])))         # (?6) = assert that the piece at the current position belongs to the current player's opponent or is empty
  ((?5)(?(?=(.*\n)\n)[qnrb]|p))     # (?7) = black pawn that might be promoted, (?8) = .*\n
  ((?5)(?(?=(?8){8}\n)[QNRB]|P))    # (?9) = white pawn that might be promoted
)
(?>
  (?>
    # Handle squares that don't change (empty->empty or pieces that doesn't move)
    (.)(?=(?5)\g{-1}) |
    # Handle a piece that moves (and optionally captures an enemy piece)
    (?(m)$)  # allow only one move to be made per turn
    (?>
      (?(1)
        (?:                                                         # white pawn
            -  (?=(?9))(?=(?3){8}((?3){9})?P(?4))(?(-1)(?=(?8){4}\n)) |   # move 1 or 2 spaces forward
          [a-z](?=(?9))(?=(?3){7}(?2)?     P(?4))                     )   # capture diagonally
      |
        (?:p(?4)(?:                                                 # black pawn
          (?=(?3){8}((?3){9})?  -  (?7))(?(-1)(?=(?8){7}\n)) |            # move 1 or 2 spaces forward
          (?=(?3){7}(?2)?     [A-Z](?7)) )                   )            # capture diagonally
      ) |
      # bishops, rooks, queens, knights, or kings
      (?<e>(?6).)?   # decide between scanning forward (<e> is unset) or backwards (<e> is captured)
      (?=
        (?i:
          (?|
            (?(e)|(B|Q)) (?&B)  (?(e)(B|Q)) | # bishops or queens
            (?(e)|(R|Q)) (?&R)  (?(e)(R|Q)) | # rooks or queens
            (?(e)|(N  )) (?&N)  (?(e)(N  )) | # knights
            (?(e)|(K  )) (?&K)? (?(e)(K  ))   # kings
          )
        )
        (?(e)(?<=(?!(?6)).)(?4)|(?6).(?5)\g{-2})   # verify that the piece moved, and optionally captured piece, are of the correct color
      )
      (?(e)(?=(?5)\g{-1})|(?!(?6)).(?4))   # verify that the piece moved is the same type and color at its destination in the next turn's board position
    )(?<m>) |
    (?(+1)$)(.)  # handle the destination/source square that a piece moved to/from (only allow matching one of these per turn)
  )+\n
)+
\k<m>         # assert that a move has taken place
\n
# don't allow moving into check
(?!
  \X{0,70}
  (?:
    # pawns (capture diagonally)
    (?(1)p|k)(?=(?3){7}(?2)?(?(1)K|P)) |
    # bishops, rooks, queens, knights, or kings
    (?i:
      (?<E>(?!(?6))K)?   # decide between scanning forward (<E> is unset) or backwards (<E> is captured)
      (?:
        (?(E)|((?6)[BQ])) (?<B>()?((?(-1)-)(?3){7}(?(-2)(?2)))+)         (?(E)(?-4)) | # bishops or queens
        (?(E)|((?6)[RQ])) (?<R>-*|((?(-1)-)(?3){8})+)                    (?(E)(?-3)) | # rooks or queens
        (?(E)|((?6) N  )) (?<N>(?<=..)(?2){3}|(?=.)(?2){5}|(?2){8}(?2)?) (?(E)(?-2))   # knights
      )
      (?(E)|(?&E)) |
      K(?<K>(?3){7,9})?K   # kings
    )
  )
)

-88 bytes by using non-atomic subroutine calls, thus retargeting from PCRE1 to PCRE2
The version above has been modified not to allow en passant or castling, but the full project is currently at a state where it validates every type of move, starting at the initial board state (which must be the standard chess starting position – Chess960 is not supported, yet at least). The full rules of en passant and castling are enforced.
Here is a sample game validated by the full regex [regex101.com].
An invalid move will result in every subsequent board position not being matched/highlighted. Checkmate/stalemate detection, and thus detection of who the winner is (or if it's a draw), is not yet implemented; that's why the final board state in this example is not highlighted.
Here is a C/C++ program that converts algebraic notation into the format recognized by this regex. The algebraic notation currently must be put in the form of an array inline in the source code, with separate strings for each move, but reading it as single string from stdin or a command-line argument, with the entire sequence of moves separated by spaces and dot-terminated move numbers, is planned.
I also started on a regex that validates a full game purely in algebraic chess notation, with the standard initial position being implied. All it needs is an empty "scratch board" appended at the end of the input (after the list of moves). I'm pretty sure it's possible to implement this in full, and plan on finishing it sometime.

I haven't been filled with this much dread since the time I coughed up a 3000-byte regex monstrosity for a Sudoku validation question (a massive mistake, considering the winning answer got it in less than 75). Truly proves the point that sometimes when you use regex to solve a problem, you end up with two problems

@ValueInk Heh, maybe you're right, but I enjoy it regardless of (or maybe because of) its utter impracticality. Your comment inspired me to attempt answering that Sudoku question, but I only managed 200 bytes. Oh well.

JavaScript (Node.js), 693 bytes
(b,M,[c,p,x,y]=M,m=Math.abs,J='some',F=(C,X,Y,W,T,Q=P=>P[2]==X&P[3]==Y)=>W.filter(([i,j,k,l])=>i==C&j==(T||j)&[B=m(H=k-X)==m(V=l-Y)&!W[J](([I,J,K,L])=>(K-k)/H==(L-l)/V&(k>X?K<k&K>X:K>k&K<X)&(l>Y?L<l&L>Y:L>l&L<Y)),R=!(k-X&&l-Y)&!W[J](([I,J,K,L])=>k-X?L==Y&(k>X?K<k&K>X:K>k&K<X):K==X&(l>Y?L<l&L>Y:L>l&L<Y)),B|R,k==X?!W[J](Q)&(l-Y==1-2*(C<'E')|l-Y==2-4*(C<'E')&!W[J](E=>E[2]==X&E[3]==Y+1-2*(C<'E'))):m(k-X)==1&l-Y==1-2*(C<'E')&W[J](E=>Q(E)&E[0]!=i),(k-X)**2+(l-Y)**2==5,(k-X)**2+(l-Y)**2<3]['BRQPNK'.search(j)]))=>x>0&x<9&y>0&y<9&!b[J](([i,j,k,l])=>k==x&l==y&(i==c|j=='K'))&F(c,x,y,b,p).some(e=>!F(c<'E'?'W':'B',...(W=b.map(E=>E[J]((a,i)=>a!=e[i])?E:M)).find(Z=>Z[0]==c&Z[1]=='K').slice(2),W)[0])

Try it online!
I sought out this challenge with the aim of combining CodeGolf with a project idea for a chess app. I realized that most of the functionality of a chess app hinges on the ability to validate a chess move, and while the challenge's input format does not explicitly include which piece in particular (which white bishop?) is moving, I still found this fun to write. My original working code was 1200 bytes, so I'm proud I managed to cut it down to 693. It takes input in the same format as the spec and outputs 0 for invalid, 1 for valid.
Explanation
Really simple when you get down to it. We call a huge function F which returns the list of pieces that can move to an X,Y coordinate with color C and type T within a board W. This is called to retrieve the list of eligible pieces based on the [c,p,x,y] input, and again to determine whether there is check or not. Here we do not call with a type parameter as we want to consider every piece.
The large list in the filter function body is simply a list of booleans which check Xs and Ys, the code is too unreadable for me to explain how that works... but it should be easy to figure it out by reading the code. Notably, all a queen needs is either bishop eligibility or rook eligibility. The pawn code was what took the longest to write.
Then we have a simple some call which operates on the filtered list, checking if there is any piece where, after recalling F with a slightly modified board (that particular piece is moved to the target), we get an empty list (no eligible pieces of the opposite color) or in other words there is no first element.
Here's an expanded version of my code (thanks Emanresu A!):
(b,M,
  [c,p,x,y]=M,
  m=Math.abs,
  J='some',
  F=(C,X,Y,W,T,
    Q=P=>
      P[2]==X&
      P[3]==Y
  )=>W.filter(
    ([i,j,k,l])=>
      i==C&
      j==(T||j)&
      [
        B=m(H=k-X)==m(V=l-Y)
        &!W[J](
          ([I,J,K,L])=>
            (K-k)/H==(L-l)/V
            &(
              k>X?
              K<k&K>X
             :K>k&K<X
            )
            &(
              l>Y?
              L<l&L>Y
              :L>l&L<Y
            )
        ),
        R=
          !(k-X&&l-Y)
          &!W[J](
            ([I,J,K,L])=>
              k-X?
                L==Y
                &(
                  k>X?
                  K<k&K>X
                  :K>k&K<X
                )
              :K==X
                &(
                  l>Y?
                  L<l&L>Y
                  :L>l&L<Y
               )
          ),
        B|R,
        k==X?
          !W[J](Q)
          &(
            l-Y==1-2*(C<'E')
            |l-Y==2-4*(C<'E')
            &!W[J](
              E=>
                E[2]==X
                &E[3]==Y+1-2*(C<'E')
            )
          )
        :m(k-X)==1
          &l-Y==1-2*(C<'E')
          &W[J](E=>Q(E)&E[0]!=i),
        (k-X)**2+(l-Y)**2==5,
        (k-X)**2+(l-Y)**2<3
      ]['BRQPNK'.search(j)]
    )
  )=>
    x>0
    &x<9
    &y>0
    &y<9
    &!b[J](
      ([i,j,k,l])=>
        k==x
        &l==y
        &(
          i==c
          |j=='K'
        )
    )
    &F(c,x,y,b,p).some(
      e=>!F(
        c<'E'?
        'W'
        :'B',
        ...(
          W=b.map(
            E=>E[J](
              (a,i)=>
                a!=e[i]
            )
            ?E
            :M
          )
        ).find(
          Z=>
            Z[0]==c
            &Z[1]=='K'
        ).slice(2),
      W)[0]
    )

I'm too tired to try and golf this, but here's a more expanded version.

@emanresuA Thanks! I'll paste that into the answer later, gotta go for now...

Python 2 (with python-chess),  141 138 134 133  132 bytes
Without doing any of the really interesting code - but maybe this can compete with golfing languages or (dare I mention it) Mathematica?
Note: python-chess is a Pypi package install it on Python 2.7.9+ with:
python -m pip install python-chess)
import chess
a,p,n=input()
S=chess.Board(a+' - - 0 1')
for m in S.legal_moves:1/(m.to_square!=n)**(`p`in`S.piece_at(m.from_square)`)

A full-program accepting input of three items:

the beginning of a FEN record - the string containing the first two fields. This is to define the board state AND which colour is moving (since this is the information in the input in the OP, whereas fields three through six are "fixed" by the OP hence should not be a part of the input)
the piece-name attempting to move (as given in the OP -- one of PRNBQK)
the square to which the named piece is attempting to move where a1 is 0, b1 is 1, ... a2 is 8, ..., h8 is 63,

The program outputs via its exit-code given valid input:

1 if the move is a valid one (the program raised an error - due to division by
zero);
0 it it is not (the program exited normally)

(Don't) Try it online! (because the python-chess package is not installed there and TIO does not allow internet connectivity so the pip-install code in the header wont work).
Note that the power operator in Python makes 1**1 == 1**0 == 0**0 == 1 but 0**1 == 0
...hence 1/0**1 raises a division by zero error while 1/1**1, 1/1**0, and 1/0**0 all succeed
(...and that in Python False and True equate to 0 and 1 respectively).

It's a perfectly valid answer, but it feels a little like cheating, similar to a builtin-only Mathematica answer.

Yes, hence the comment I put at the top "Without doing any of the really interesting code..." maybe when I have some more time I'll do a Jelly one (which cannot import this module :))

...mind you it still took some effort.

Rearrange str(S.piece_at(m.from_square))==p for to p==str(S.piece_at(m.from_square))for, that should save one byte.

Ah, yes - thanks @Zacharý I was just looking to see if I could parse from the repr using backticks to replace str to save...

@Zacharý turns out there was a way to save more there. Thanks though!

@cairdcoinheringaahing ...Actually I suppose Jelly could do this same thing by executing the Python code along with a leading import pip;pip.main(['install','python-chess']);. I wonder if that'd be shorter than an "interesting" implementation!

Hmm well 159 bytes = 157 + 2 for the ŒV that goes on the end to execute the Python code in the compressed string (tested locally).

...146.

The input specification is missing the fact that the piece-name must be uppercase for white's moves, and lowercase for black's moves. Examples: 'rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R b','n',45, 'rnbqkb1r/pppppppp/5n2/8/8/5N2/PPPPPPPP/RNBQKB1R w','P',26

@Deadcode oh does it, I don't have python-chess installed anywhere I can run via this mobile... I imagine that's fine given it's just boilerplate to fix up the all-upper input (maybe there are some exceptions like castling or promotion??)

Here's a link for running your program online: https://repl.it/repls/ChillyMadAddresses - I don't know how to show the exit code in repl.it, but that's not necessary because the division by zero error is printed, and lack of it indicates an invalid move. To re-run it without clicking repl.it's Run button, enter import os,sys;os.execv(sys.executable,['','main.py']).

-5 bytes for using for m in S.legal_moves:p[p+n in str(S.piece_at(m.from_square))+\m`[17:]]and changing the input spec for "move where" to standarda1, b1, ... a2, ... h8format. Relies on internals of python-chess, but since the last version to support Python 2 is frozen at 0.23.11, that shouldn't be a problem... and thereprversion of this still works with v0.29.0 anyway. (The portable equivalent would befor m in S.legal_moves:p[p+n==str(S.piece_at(m.from_square))+str(m)[2:4]]` which is 1 byte longer, meaning only -4 bytes relative to the current answer.)

for m in S.legal_moves:p[p+n in str(S.piece_at(m.from_square)).upper()+\m`[17:]]` to allow the piece to be inputted always in uppercase. Costs only 8 bytes. Input can't be all-uppercase though, because FEN is case-sensitive.

And if you want to stick with the existing input scheme (though I don't know why you would... either way it's different than the question's), save 1 byte by changing m.to_square!=n to m.to_square-n.

Python 2 (with python-chess), 127 125 124 bytes
import chess
a,m=input()
S=chess.Board(a+' - - 0 1')
for l in S.legal_moves:1/(m!=str(S.piece_at(l.from_square))+`l`[17:19])

Try it on replit.com - test cases
Jonathan Allan never responded to the golf optimization and other comments I provided under his answer. So I'm finally doing that here. This program is based on his.
Input consists of two items:

The board state, in the form of a FEN record. As per the challenge's specifications, this is abbreviated not to include extra information about the state (castling, en passant, halfmove clock, or fullmove number) but it must include the color whose turn is next to move.
The move whose legality is being queried; this is a 3-character string. The first character is the piece type; as in the challenge's input specification, this is one of PRNBQK, except that a white piece must be in uppercase, and a black piece must be in lowercase. The next two characters are the destination square for the move. This is given in standard chess column,row format, where the column is one of abcdefgh and the row is one of 12345678.

Python 2 automatically runs eval() on input(), so the input is taken in the form of comma-delimited Python string literals. Examples:
'rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R b','nf6'
'rnbqkb1r/pppppppp/5n2/8/8/5N2/PPPPPPPP/RNBQKB1R w','Pc4'
Here is a C++ program that converts the test cases.
The program outputs via its exit-code given valid input:

1 if the move is legal (the program raised a ZeroDivisionError)
0 it the move is illegal (the program exited normally)

Try it on replit.com
Can't Try it online! (python-chess is not installed on TIO, nor is internet connectivity allowed, and even if it were, Pypi and the latest version of python-chess no longer support Python 2)
python-chess v0.23.11 was the last version to support Python 2. To install it for use with this program, you may run the following git command:
git clone --branch 0.23.x https://github.com/niklasf/python-chess.git

And then symlink, copy, or move its chess subdirectory to the directory from where you are running this CGCC program.
Python 3 (with python-chess), 134 132 121 120 bytes
import chess
b,m=eval(input())
S=chess.Board(b)
for l in S.legal_moves:1/(m!=str(S.piece_at(l.from_square))+str(l)[2:4])

This is a straight port of the Python 2 version. Python 3 dropped support for the backtick alias for repr, so str is used instead. We can't use str(l)[2:] because an extra character is appended to str(l) in the case of pawn promotions, specifying what it is to be promoted to.
We save 11 bytes by using the latest python-chess, more than making up for the 7 bytes sacrificed by using Python 3, because python-chess v0.27 added support for omitting the last 5 parts of the FEN string. This still accomplishes exactly what the challenge requires – it defaults to treating castling and en passant as impossible moves. (We still need to include the current turn, because otherwise it defaults to white's turn.)
Attempt This Online!
Attempt This Online! - test cases
To install the latest release of python-chess:
pip install chess

Python 3 (with python-chess), 158 152 141 138 bytes
import chess
b,p,n=input().split()
S=chess.Board(b)
S.turn=p<'a'
for m in S.legal_moves:p[p+n==str(S.piece_at(m.from_square))+str(m)[2:4]]

The 132 byte, 124 byte, and 120 byte versions of this program have a problem. Their input is not bijective to the input specification given by the challenge – the color to move next must be given in two places, and if they disagree, the move is considered illegal.
This version solves that in the most natural way, by taking the color of the piece to move in the same place as the move itself is specified (i.e., whether the the piece identifier is in uppercase).
Also, evaluating the input as Python code is bad; there's a reason that was dropped in Python 3. So this answer uses split instead of eval on the input.
For optimal golf, the piece type and its destination coordinates are to be separated by a space in the move to be queried. Examples:
rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R n f6
rnbqkb1r/pppppppp/5n2/8/8/5N2/PPPPPPPP/RNBQKB1R P c4
Here is a C++ program that converts the test cases.
Unlike the others, the error used to trigger an exit code of 1 in this version is IndexError, by attempting to access the second character of a single-character string.
Attempt This Online!
Attempt This Online! - test cases
Python 2 (with python-chess), 294 278 276 270 197 bytes
from chess import*
b,m=input()
S=Board()
S.clear()
S.turn=m[0]<'a'
for P in b:S.set_piece_at(P[1],Piece.from_symbol(P[0]))
for l in S.legal_moves:1/(m!=[str(S.piece_at(l.from_square)),l.to_square])

Even the 138 byte program's input is not quite bijective to the input specification given by the challenge, in which the board's pieces can be listed in any order.
In this version, the board is provided as a list of pieces, as in the challenge's specification. Each piece's type (one of PRNBQK) is specified in lowercase for black or uppercase for white, instead of providing the color as a separate element. The coordinates are specified as single numbers, where a1 is 0, b1 is 1, …, a2 is 8, …, and h8 is 63. Following this list is a comma, followed by the move to be queried (in the same format as the pieces already on the board). Examples:
[['r', 56], ['n', 57], ['b', 58], ['q', 59], ['k', 60], ['b', 61], ['n', 62], ['r', 63], ['p', 48], ['p', 49], ['p', 50], ['p', 51], ['p', 52], ['p', 53], ['p', 54], ['p', 55], ['P', 8], ['P', 9], ['P', 10], ['P', 11], ['P', 12], ['P', 13], ['P', 14], ['P', 15], ['R', 0], ['N', 1], ['B', 2], ['Q', 3], ['K', 4], ['B', 5], ['N', 21], ['R', 7]], ['n', 45]
[['r', 56], ['n', 57], ['b', 58], ['q', 59], ['k', 60], ['b', 61], ['n', 45], ['r', 63], ['p', 48], ['p', 49], ['p', 50], ['p', 51], ['p', 52], ['p', 53], ['p', 54], ['p', 55], ['P', 8], ['P', 9], ['P', 10], ['P', 11], ['P', 12], ['P', 13], ['P', 14], ['P', 15], ['R', 0], ['N', 1], ['B', 2], ['Q', 3], ['K', 4], ['B', 5], ['N', 21], ['R', 7]], ['P', 19]

In this way, the input is fully bijective with the challenge's specification, but optimally golfy.
Here is a Python program that converts the test cases.
Try it on replit.com
Try it on replit.com - test cases
Can't Try it online!
Python 3 (with python-chess), 309 306 290 288 282 271 203 bytes
from chess import*
b,m=eval(input())
S=Board()
S.clear()
S.turn=m[0]<'a'
for P in b:S.set_piece_at(P[1],Piece.from_symbol(P[0]))
for l in S.legal_moves:1/(m!=[str(S.piece_at(l.from_square)),l.to_square])

This is a straight port of the Python 2 fully-bijective-input version.
Attempt This Online!
Attempt This Online! - test cases
It's almost a shame there turned out to be an interface in python-chess whereby the direct placing of the pieces and setting of the current turn could be done concisely, because there was some fun golf in converting the board to FEN in the 271 byte version:
import chess
b,m=eval(input())
B=['1']*64
for P in b:B[P[1]]=P[0]
B='/'.join(map(''.join,[*zip(*[iter(B)]*8)][::-1]))
i=8
while i:B=B.replace('1'*i,str(i));i-=1
S=chess.Board(B+' '+'bw'[m[0]<'a'])
for l in S.legal_moves:1/(m!=[str(S.piece_at(l.from_square)),l.to_square])

Attempt This Online!
Attempt This Online! - test cases
Python 3 (with python-chess), 163 bytes
from chess import*
b,m=eval(input())
S=Board()
S.clear()
S.turn=m[0].color
S.set_piece_map(b)
for l in S.legal_moves:1/(m!=[S.piece_at(l.from_square),l.to_square])

An even smaller code size is achieved here by setting a rather ridiculously specific input specification. Examples:
{56: Piece(ROOK, BLACK), 57: Piece(KNIGHT, BLACK), 58: Piece(BISHOP, BLACK), 59: Piece(QUEEN, BLACK), 60: Piece(KING, BLACK), 61: Piece(BISHOP, BLACK), 62: Piece(KNIGHT, BLACK), 63: Piece(ROOK, BLACK), 48: Piece(PAWN, BLACK), 49: Piece(PAWN, BLACK), 50: Piece(PAWN, BLACK), 51: Piece(PAWN, BLACK), 52: Piece(PAWN, BLACK), 53: Piece(PAWN, BLACK), 54: Piece(PAWN, BLACK), 55: Piece(PAWN, BLACK), 8: Piece(PAWN, WHITE), 9: Piece(PAWN, WHITE), 10: Piece(PAWN, WHITE), 11: Piece(PAWN, WHITE), 12: Piece(PAWN, WHITE), 13: Piece(PAWN, WHITE), 14: Piece(PAWN, WHITE), 15: Piece(PAWN, WHITE), 0: Piece(ROOK, WHITE), 1: Piece(KNIGHT, WHITE), 2: Piece(BISHOP, WHITE), 3: Piece(QUEEN, WHITE), 4: Piece(KING, WHITE), 5: Piece(BISHOP, WHITE), 21: Piece(KNIGHT, WHITE), 7: Piece(ROOK, WHITE)}, [Piece(KNIGHT, BLACK), 45]
{56: Piece(ROOK, BLACK), 57: Piece(KNIGHT, BLACK), 58: Piece(BISHOP, BLACK), 59: Piece(QUEEN, BLACK), 60: Piece(KING, BLACK), 61: Piece(BISHOP, BLACK), 45: Piece(KNIGHT, BLACK), 63: Piece(ROOK, BLACK), 48: Piece(PAWN, BLACK), 49: Piece(PAWN, BLACK), 50: Piece(PAWN, BLACK), 51: Piece(PAWN, BLACK), 52: Piece(PAWN, BLACK), 53: Piece(PAWN, BLACK), 54: Piece(PAWN, BLACK), 55: Piece(PAWN, BLACK), 8: Piece(PAWN, WHITE), 9: Piece(PAWN, WHITE), 10: Piece(PAWN, WHITE), 11: Piece(PAWN, WHITE), 12: Piece(PAWN, WHITE), 13: Piece(PAWN, WHITE), 14: Piece(PAWN, WHITE), 15: Piece(PAWN, WHITE), 0: Piece(ROOK, WHITE), 1: Piece(KNIGHT, WHITE), 2: Piece(BISHOP, WHITE), 3: Piece(QUEEN, WHITE), 4: Piece(KING, WHITE), 5: Piece(BISHOP, WHITE), 21: Piece(KNIGHT, WHITE), 7: Piece(ROOK, WHITE)}, [Piece(PAWN, WHITE), 19]

Here is a Python program that converts the test cases.
Attempt This Online!
Attempt This Online! - test cases


text:
Quadrants passed through by a line
Task
Given a representation of a line, output the number of quadrants that that line passes through.
Valid Representations of a Line
You can represent a line as

Three signed integers A, B, and C which share no common factor and where A and B are not both zero, representing the line Ax + By = C,
Four signed integers X1, Y1, X2, and Y2, representing the line passing through the points (X1, Y1) and (X2, Y2), or
A data type that describes a line, if your language has one (it must support vertical lines).

You may not take input in any format that does not allow for a vertical line (e.g. slope-intercept form). If you choose to take integers as input, you can assume that they lie in the inclusive range [-127, 128].
Specifications

The output will always be 0, 2, or 3 (a line can never pass through all four quadrants, nor can it pass through only a single one).
A line on an axis is considered not to pass through any quadrants. A line through the origin is considered to only pass through 2 quadrants.
You do not have to return which quadrants are being passed through (though the test cases include them for clarity).
This is code-golf, so the shortest valid answer (measured in bytes) wins.

Test Cases
You will have to convert these to a suitable format before using them.
1x + 1y = 1   ->  3  (quadrants I, II, and IV)
-2x + 3y = 1  ->  3  (quadrants I, II, and III)
2x + -3y = 0  ->  2  (quadrants III and I)
1x + 1y = 0   ->  2  (quadrants II and IV)
3x + 0y = 6   ->  2  (quadrants I and IV)
-3x + 0y = 5  ->  2  (quadrants II and III)
0x + -8y = 4  ->  2  (quadrants III and IV)
0x + 1y = 0   ->  0  (lies on the x-axis)
1x + 0y = 0   ->  0  (lies on the y-axis)

They should teach the tactic we all borrowed from Leaky Nun in school, if there was a need for it.

Python 3, 24 bytes
lambda a:3<<a.count(0)&3

Try it online!

... wow. This is more trivial than I thought.

You could maybe use a string instead of a list if the I/O permits it.

Would using '320'[a.count(0)] and returning the value in string form be acceptable?

And wow, looks like all answers will now be "based off Leaky's"

@FlipTack bithacks win :P

Jelly, 5 bytes
TL’ȧ$

Try it online!

-1 byte thanks to Challenger5
-1 byte thanks to Leaky Nun
-2 bytes thanks to H.PWiz

No longer based off Leaky's answer!

ċ0ị2,0,3 saves a byte

@Challenger5 Huh, so it does. Thanks!

7 bytes

How about TL’ȧ$. Don't know Jelly, so this might be golfable

@H.PWiz Very nice! I don't think that can be golfed, but I may be wrong.

Wait, so this computes (number of non-zeroes) && (number of non-zeroes - 1)? I don't get $ here to be honest...

@totallyhuman IIUC $ makes the previous two links into a single monadic chain so that the chain does not start with 3 dyads (as Jelly has special behavior for this).

...yep $ treats the last two links as if they were a monadic (TLµ’ȧ will do too, as would TL_Ị$ or TLµ_Ị) - although it does not create an actual chain.

Javascript (ES6), 30 24 22 bytes
This is my first time trying to golf in Javascript.  There's gotta be a better way to count zeros...
(a,b,c)=>3<<!a+!b+!c&3

-6 bytes thanks to Herman Lauenstein, -2 bytes to remembering operator precedences.
Alternate 24-bytes solution to return a string instead:
(a,b,c)=>"320"[!a+!b+!c]

That's actually fairly clever...

24 bytes by not using an array (a,b,c)=>3<<(!a+!b+!c)&3

Looks like I can't golf mine to not use an array anymore...

05AB1E, 6 bytes
ƵÜ¹0¢è

Try it online!
Based on Leaky Nun's answer.

SOGL V0.12, 8 bytes
0233{.‽X

Try it Here!
Based off Leaky Nun's answer.

Retina, 13 bytes
M`\b0
T`d`320

Try it online
Also based on Leaky Nun's answer.

This doesn't work if the input contains 10 for example. The first regex would need to be \b0.

GolfScript, 16 14 bytes
~{!!}%{+}*.1>*

Try it online!

@Challenger5 -2 bytes

This program takes an array of 3 integers representing the coefficients in the equation Ax + By = C
Example Input/Output
[1 1 1]   -> 3
[-2 3 1]  -> 3

How it Works
~                       - Eval string (input)
  {  }%                 - Map to array
   !!                   - Double not (equivalent to != 0)
        {+}*            - total array (fold addition)
            .           - Duplicate top of stack
             1>         - Greater than 1?
               *        - Multiply

This was a little tricky at first for me to figure out a mathematical way to calculate this. However there are only 8 possible configurations such that a != 0 & b != 0 & c != 0
0 0 0 = 0
a 0 0 = 0
0 b 0 = 0
0 0 c = 0
a 0 c = 2
0 b c = 2
a b 0 = 2
a b c = 3

I eventually came to the following function.
F(a,b,c) {
    var r = sign(a)+sign(b)+sign(c);
    if(r > 1)
        r;
    else
        return 0;
}

and the whole thing can be condensed to a single math problem
F(a,b,c) {
    return (sign(a)+sign(b)+sign(c)) * (sign(a)+sign(b)+sign(c) > 1);
}

I think you can use {!!}% instead of [{!!}/].

CJam translation of this submission is {:!:!:+_1>*}.

@Challenger5 lol, How did I not realize that. Also nice port, I just have to learn how to read it now.

Significant differences in this case are 1) shorthand for mapping (:! is equivalent to {!}%), 2) shorthand for reducing (:+ is equivalent to {+}*), 3) that . is changed to _ (because CJam has floats), and 4) that CJam does not have input on the stack by default, meaning that you wrap the code in {} to make it a function.

APL (Dyalog Unicode), 14 11 bytes
0⌈3-×⍨+/0=⎕

Try it online!
⎕IO is 0. Thanks to @Adám for -3 bytes!

0⌈3-×⍨+/0=⎕

JavaScript, 25 bytes
_=>3<<!_[0]+!_[1]+!_[2]&3

Based off Leaky Nun's answer.

Haskell, 22 bytes
f l="320"!!sum[1|0<-l]

Try it online!
Point-free solution, 27 bytes
("320"!!).(\l->sum[1|0<-l])

Try it online!

I was about to suggest that change... beat me to it

Perl 6, 18 bytes
{3+<@_.grep(0)+&3}

ABCR, 30 bytes
Input is in the form A,B,C where the commas can be replaced by any non-numeric, non-- character.
BBi7baxci7baxci7bax@7)A7(xxo

No online interpreter yet, but here's an explanation:
BB                                Add two values to the B queue. (Values are unimportant)
  i7 ax                           Read in a number.  If it's non-zero...
    b                             Dequeue one item from the B queue.
       c                          Read in the delimiter...
        i                         ... And promptly overwrite it with the next number.
         7baxci7bax               Repeat the whole "if 0, dequeue from B" for the
                                     other two input numbers.
                   @              Get the current length of the B queue. [2, 1, or 0]
                    7             If the length isn't 0...
                     )            ... Increment it to our required [3,2,0]
                      A           ... And enqueue it to A.
                                  (We don't need to add to A otherwise, because it defaults
                                    to 0 already if there's no value in it.
                                    I used that to exit the queue with 7_ax earlier.)
                       7(xx       Set the register to 0 to exit from loop.
                           o      Peek A and print as a number.

Deorst, 12 bytes
l0EN))A:k?Z+

Try it online!
Somewhat based off Leaky's answer; uses the same premise, but a different mapping method.
How it works
Deorst has a count occurrences builtin, but doesn't (for some reason) have an indexing command, so I had to create the following mapping, where the left is a.count(0) and the right is the wanted result
0 -> 3
1 -> 2
2 -> 0

The program itself works like this (example input of [1,1,1])
l0           - Push 0;     STACK = [[1 1 1] 0]
  EN         - Count;      STACK = [0]
    ))       - Subtract 2; STACK = [-2]
      A      - Absolute;   STACK = [2]
       :     - Duplicate;  STACK = [2 2]
        k?Z  - Positive?;  STACK = [2 1]
           + - Sum;        STACK = [3]

Add++, 23 bytes
D,f,@@@,!$!@!s2$_|d0$>+

Try it online!
Based off both my Deorst answer and Leaky's Python answer
How it works
D,f,@@@,  - Create a triadic function.
            Example arguments;   [1 1 1]
        ! - Logical NOT; STACK = [1 1 0]
        $ - Swap;        STACK = [1 0 1]
        ! - Logical NOT; STACK = [1 0 0]
        @ - Reverse;     STACK = [0 0 1]
        ! - Logical NOT; STACK = [0 0 0]
        s - Sum;         STACK = [0]
        2 - Push 2;      STACK = [0 2]
        $ - Swap;        STACK = [2 0]
        _ - Subtract;    STACK = [-2]
        | - Absolute;    STACK = [2]
        d - Duplicate;   STACK = [2 2]
        0 - Push 0;      STACK = [2 2 0]
        $ - Swap;        STACK = [2 0 2]
        > - Greater to;  STACK = [2 1]
        + - Sum;         STACK = [3]

However, I think I've been using functions too much in Add++, rather than the main code body. So I attempted to do this using both functions, and the code body, and resulted in a much nicer 50 byte piece (yes, that is the longest answer here):
# Example input: 1 1 1;
# x and y are the accumulators

D,f,@@@,!$!@!s # Count the 0s
$f>?>?>?       # Call f with the input.
-2   # Subtract 2;    x: -2;  y: 0
^2   # Square;        x: 4;   y: 0
S    # Square root;   x: 2.0; y: 0
\1   # To integer;    x: 2;   y: 0
y:x  # Assign x to y; x: 2;   y: 2
}    # Switch to y;   x: 2;   y: 2
>0   # Is positive?;  x: 2;   y: 1
}    # Switch to x;   x: 2;   y: 1
+y   # Add y to x;    x: 3;   y: 1
O    # Print x

Try it online!

source: Stack Exchange

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

sort: votes


text:
Hand patterns in a card game
A deck of cards is the Cartesian product of S suits and R ranks.
Many, though not all, card games use S=4 and R∊{6,8,13}.
A hand of H cards is dealt from the deck.
Its distribution, a.k.a. "hand pattern", is an array that describes
how many cards you got from each suit, ignoring suit order (so, it's like a multi-set).
Given a distribution D satisfying len(D)=S, 1≤sum(D)=H≤S×R, 0≤D[i]≤R, D[i]≥D[i+1],
find the probability of it occurring.
Input: an integer R and an array D.
Output: the probability with at least 5 digits after the decimal mark;
 trailing zeroes may be skipped; scientific notation is ok.
Loopholes forbidden. Shortest wins.
Tests:
R    D               probability
13   4 4 3 2     ->  0.2155117564516334148528314355068773
13   5 3 3 2     ->  0.1551684646451760586940386335649517
13   9 3 1 0     ->  0.0001004716813294328274372174524508
13   13 0 0 0    ->  0.0000000000062990780897964308603403
8    3 2 2 1     ->  0.4007096203759162602321667950144035
8    4 2 1 1     ->  0.1431105787056843786543452839337155
8    2 2 1 0     ->  0.3737486095661846496106785317018910
8    3 1 1 0     ->  0.2135706340378197997775305895439377
15   4 4 3 2 1   ->  0.1428926269185580521441708109954798
10   3 0 0       ->  0.0886699507389162561576354679802956
10   2 1 0       ->  0.6650246305418719211822660098522167
10   1 1 1       ->  0.2463054187192118226600985221674877

See also Bridge hand patterns in Wikipedia.
EDIT: dropped unnecessary restriction H≤R
EDIT: added constraint H≥1

Can we assume that D is sorted?

@orip yes, that's what I meant by D[i]≥D[i+1]

Cards I know start from 1 not from 0...

@RosLuP what do you mean?

I'm sure i didn't understand something...  If Cards are  represented from number 1,2, ...,13 all * 4; so what does it mean "13 0 0 0" in example? 0 means card 0?

@RosLuP 13 0 0 0 means you have 13 cards of one suit and none of the others. Nowhere in the challenge do I mention card indices, though if I did, of course I would choose 0...51 so that ranks/suits can be determined easily through modulo and bitshift ops.

Can we assume S>1 ie there are at least two suits in the deck?

APL (Dyalog Unicode), 30 chars
×/!⍨,z,1÷((z←!∘≢⊢)⌸⊢),×∘≢!⍨1⊥⊢

Try it online!
Using @orlp’s formula.

Excellent, well done! The "+100" button says I must wait 10 more hours before I can award the bounty. After that I'll set up another one for +200.

Yay I win! thanks @jayprich

@FrownyFrog How do you like Dyalog APL compared with J?

Python 3, 134 bytes
b=lambda n,k:k<1or n*b(n-1,k-1)/k
f=lambda R,D,i=1,s=1,t=0:D and b(R,D[0])*i/s*f(R,D[1:],i+1,(D[0]in D[1:])*s+1,t+D[0])or 1/b(~-i*R,t)

Formula is the product of binom(R, d) for each element d in D, times factorial(len(D)), divided by the product of factorial(len(S)) for each S in the groupings of D (e.g. [4, 4, 3, 2] has groupings [[4, 4], [3], [2]]), finally divided by binom(len(D) * R, sum(D)).
Or in math notation, assuming m contains the multiplicities of the n unique elements in D:
$$
\frac{|D|!}{m_1!\cdot m_2!\cdots m_n!}
\binom{|D|\cdot R}{\sum D}^{-1}
\prod_{d\in D}\binom{R}{d}
$$

for a brief moment you made me believe PPCG now supports LaTeX :)

Inlining the two functions I got 136 but maybe that can be golfed more (uses i=0 to mean b() and uses R,D for n,k).

R, 90 85 83 bytes
function(R,D,l=sum(D|1),K=choose)prod(K(R,D),1:l,1/gamma(1+table(D)))/K(R*l,sum(D))

Try it online!
I observed the same thing as orlp, but I picked a nice language that has combinatorics builtins.
Explanation:
function(R,D,             # next are optional arguments
 l=sum(D|1),              # alias for length of D, aka S
 K=choose)                # alias for choose
  prod(                   # take the product of:
    K(R,D),               # "choose" is vectorized over R and D
    1:l,                  # S!
    1/gamma(1+            # gamma(n+1) = n! for integer n
     table(D))            # multiplicities of unique elements of D
  ) /                     # divide by
  K(R*l, sum(D))          # R*S choose H
                          # return last computation (which is all the computation)

You can save a few more with this: "<"=choose (outside of function) and potentially use seq depending on ngn's answer to the comment I posted this morning.

Jelly,  22  20 bytes
-2 bytes using a new quick, ʋ, and a new monadic atom Ẉ
ĠẈ!;L×c⁸S¤ʋ
L!;c@÷çP

A dyadic link, taking the dealt-distribution, D, on the left and the number-of-ranks, R, on the right, which returns the probability of occurrence.
Try it online! or see the test-suite
How?
ĠẈ!;L×c⁸S¤ʋ - Link 1, denomParts: list, distribution (D); number, ranks (R)
                                                                 e.g. [3,3,3,2,2]; 8
Ġ           - group indices of D by their values                      [[4,5],[1,2,3]]
 Ẉ          - length of each group                                    [2,3]
  !         - factorial (vectorises)                                  [2,6]
          ʋ - last four links as a dyad
            - ... i.e. totalWaysToDeal = f(list, distribution (D); number, ranks (R)):
    L       - length of D                                             5
     ×      - multiply by R = total number of cards                   40
         ¤  - nilad followed by link(s) as a nilad:
       ⁸    -   chain's left argument, D                              [3,3,3,2,2]
        S   -   sum = total cards dealt                               13
      c     - binomial                                        40C13 = 12033222880
   ;        - concatenate                                             [2,6,12033222880]

L!;c@÷çP - Main link: list, distribution (D); number, ranks (R)
         -                                                  e.g. [3,3,3,2,2]; 8
L        - length of D = number of suits                         5
 !       - factorial                                             120
   c@    - R binomial (vectorised across) D     (8C3=56;8C2=28)  [56,56,56,28,28]
  ;      - concatenate                                           [120,56,56,56,28,28]
      ç  - call the last link (1) as a dyad = denomParts(D,R)    [2,6,12033222880]
     ÷   - divide (vectorises)                                   [120/2,56/6,56/12033222880,56,28,28]
       P - product                                               0.11441900924883391

05AB1E, 21 bytes
cP¹g!*¹γ€g!P¹gI*¹Oc*/

Try it online!
Explanation
 P                      # product of
c                       # bin(input1,input2)
     *                  # multiplied by
    !                   # fac of
  ¹g                    # length of input1
                    /   # divided by
           P            # product of
          !             # fac of each
        €g              # length of each
      ¹γ                # chunk of consecutive equal elements of input1
                   *    # multiplied by
                  c     # bin of
            ¹g          # length of input1
              I*        # times input2
                ¹O      # and sum of input1

Pyth, 32 bytes
cc*.!lQ*F.cLvzQ*F.!hMr8Q.c*vzlQs

Try it here! or Verify all the test cases!
How this works?

cc*.!lQ*F.cLvzQ*F.!hMr8Q.c*vzlQs ~ Full program. D = list, R = number.

   .!                            ~ The factorial of...
     lQ                            ~ The length of D.
  *                              ~ Multiplied by...
       *F                          ~ The product of the elements of...
         .c                          ~ The nCr between...
           L  Q                        ~ Each element of D, and...
            vz                         ~ R.
 c                               ~ Divided by...
               *F                  ~ The product of the elements of...
                 .!                  ~ The factorial of each...
                   hM                  ~ Heads. Count of adjacent elements in...
                     r8Q                 ~ The run length encoding of D.
c                                ~ Divided by...
                        .c         ~ The nCr between...
                          *          ~ The product of...
                           vz          ~ R, and...
                             lQ        ~ The length of D.
                               s   ~ And the sum of D.
                                 ~ Output implicitly.

APL (Dyalog), 42 bytes
{×/(!≢⍵),(⍵!⍺),÷((+/⍵)!⍺×≢⍵),!≢¨⍵⊂⍨1,2≠/⍵}

Try it online!
Still golfing.

challenge: 30 bytes

@ngn challenge accepted

Sorry, it's actually 30 chars. With the risk of giving away information: one of my chars is not in the Classic charset, I didn't realise that at first.

@ngn Can't you just use Adám's character set to make it 30 bytes?

@Probie yep, that's what I meant by "SBCS" in the bounty description

≢¨⍵⊂⍨1,2≠/⍵ can become ⊢∘≢⌸⍵

Clojure, 153 bytes
#(apply +(for[_(range 1e06):when(=(remove #{0}%)(reverse(sort(vals(frequencies(take(apply + %)(shuffle(for[i(range %2)j(range(count %))]j))))))))]1e-06))

Just a brute-force simulation, to get more precision increase the iteration count and the "1 / N" value at the end accordingly. First argument is the counts and 2nd argument is the number of cards in the deck per suite.

J, 57 bytes
](#@]%~[:+/[-:"1[:\:~@(#/.~)"1+/@[{."1])i.@!@(*+/)A.(##\)

Try it online!
This runs in O(golf) and will choke on many of the test cases (though works theoretically), which would be fine if it were golfier.  But I'm stuck on trimming it down, especially with avoiding those repeated "1.  If anyone wants to help, here's the parsed version...
The right side of the main fork is all possible deals of the deck, and the left side of the main fork is just the original right arg, ie, the suit mask we're matching against.
Inside, from each "shuffled" deck, we take the first hand elements, then group them using key /. and sort the result, and check if that matches the suit mask in question.  We add add up the total number that do match, and divide that into the length of all possible decks.
┌─┬─────────────────────────────────────────────────────────────────────────────────────────────────┬─────────────────────────────────────┐
│]│┌───────┬─────┬─────────────────────────────────────────────────────────────────────────────────┐│┌──────────────────────┬──┬─────────┐│
│ ││┌─┬─┬─┐│┌─┬─┐│┌──┬─────┬──────────────────────────────────────────────────────────────────────┐│││┌────────┬─┬─────────┐│A.│┌─┬─────┐││
│ │││#│@│]│││%│~│││[:│┌─┬─┐│┌─┬────────┬─────────────────────────────────────────────────────────┐│││││┌──┬─┬─┐│@│┌─┬─────┐││  ││#│┌─┬─┐│││
│ ││└─┴─┴─┘│└─┴─┘││  ││+│/│││[│┌──┬─┬─┐│┌──┬───────────────────────────┬────────────────────────┐│││││││i.│@│!││ ││*│┌─┬─┐│││  ││ ││#│\││││
│ ││       │     ││  │└─┴─┘││ ││-:│"│1│││[:│┌─────────────────────┬─┬─┐│┌───────────┬────────┬─┐│││││││└──┴─┴─┘│ ││ ││+│/││││  ││ │└─┴─┘│││
│ ││       │     ││  │     ││ │└──┴─┴─┘││  ││┌──────┬─┬──────────┐│"│1│││┌─────┬─┬─┐│┌──┬─┬─┐│]││││││││        │ ││ │└─┴─┘│││  │└─┴─────┘││
│ ││       │     ││  │     ││ │        ││  │││┌──┬─┐│@│┌──────┬─┐││ │ ││││┌─┬─┐│@│[│││{.│"│1││ ││││││││        │ │└─┴─────┘││  │         ││
│ ││       │     ││  │     ││ │        ││  ││││\:│~││ ││┌─┬──┐│~│││ │ │││││+│/││ │ ││└──┴─┴─┘│ │││││││└────────┴─┴─────────┘│  │         ││
│ ││       │     ││  │     ││ │        ││  │││└──┴─┘│ │││#│/.││ │││ │ ││││└─┴─┘│ │ ││        │ ││││││└──────────────────────┴──┴─────────┘│
│ ││       │     ││  │     ││ │        ││  │││      │ ││└─┴──┘│ │││ │ │││└─────┴─┴─┘│        │ ││││││                                     │
│ ││       │     ││  │     ││ │        ││  │││      │ │└──────┴─┘││ │ ││└───────────┴────────┴─┘│││││                                     │
│ ││       │     ││  │     ││ │        ││  ││└──────┴─┴──────────┘│ │ ││                        │││││                                     │
│ ││       │     ││  │     ││ │        ││  │└─────────────────────┴─┴─┘│                        │││││                                     │
│ ││       │     ││  │     ││ │        │└──┴───────────────────────────┴────────────────────────┘││││                                     │
│ ││       │     ││  │     │└─┴────────┴─────────────────────────────────────────────────────────┘│││                                     │
│ ││       │     │└──┴─────┴──────────────────────────────────────────────────────────────────────┘││                                     │
│ │└───────┴─────┴─────────────────────────────────────────────────────────────────────────────────┘│                                     │
└─┴─────────────────────────────────────────────────────────────────────────────────────────────────┴─────────────────────────────────────┘

Orlp's formula scored 42 for APL, maybe that would score less than 58 on J?

I get 45 so far that way f=:(([:!#)%[:*/[:!#/.~)@]**/@(]![)%+/@]![*#@]
TIO

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

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


text:
Find the password
An ordinary N-digit combination lock consists of N rotating discs. Each disc has digits 0-9 inscribed in order, and you need to turn them to the correct password to open it. Obviously, if you don't know the password, you will need to try at most 10N times before unlocking it. That's not interesting.

So let's consider a variant of combination lock, name it distance-revealing lock.
In every unsuccessful attempt to open an distance-revealing lock, it will respond the minimum number of movements to unlock.
One movement is defined as a rotation by one position, for example it needs 1 movement from 890 to 899, and 9 movements from 137 to 952.
The Challenge
Given a distance-revealing lock with its password unknown, try to open the lock with a minimal number of attempts (not movements), while keeping the program from getting too long.
Rules & Scorings

You should write a full program which inputs from stdin and outputs to stdout. The program should do input/output as following:

Start
    Input an integer N (number of digits) from stdin
    Do
        Output a line containing decimal string of length N (your attempt) to stdout
        Input an integer K (response of the lock) from stdin
    While K not equal 0
End

Your program should handle up to N = 200, and should run less than 5 seconds on any input.

Leading zeros in output shouldn't be omitted.

The are 5 testdata for every length, so the total number of testdata is 1000. The testdata are randomly generated.

The final score will be (total number of guesses in all testdata) * ln(code length in bytes + 50). Lowest score wins. (ln is natural log)

I will score the program for you. If you want to know how I will score your program, or you want to score it by yourselves, take a look at previous edits on this post.

This challenge will end at 2017/12/07 14:00 UTC. I will post my solution then.

Running Example
Lines starting with > represent input, and others represent program output.
You can have a password in your mind and interact with your program to test it.
> 3   # 3-digit lock. The hidden password is 746
000   # 1st guess (by program)
> 11  # response to the 1st guess
555   # 2nd guess
> 4   # ...
755
> 2
735
> 2
744
> 2
746   # finally the correct answer! The program attempts 6 times.
> 0   # this is not necessary

Sample Program
EDIT: Maybe the input/output format above was not clear. Here's a sample program in Python.
Python, 369 bytes, total number of attempts = 1005973, score = 6073935
import sys

N = int(input()) # get the lock size

ans = ''
for i in range(N): # for each digit
    lst = []
    for j in range(10): # try all numbers
        print('0' * i + str(j) + '0' * (N - i - 1)) # make a guess
        result = int(input()) # receive the response
        lst.append(result)
    ans += str(lst.index(min(lst)))
print(ans) # output the final answer

Thanks to Jonah for simplifying the challenge.

C, 388 374 368 bytes, total attempts = 162751, score = 982280
char s[999];i;G;H;t;n;h;e;R(x){scanf("%d",x);}W(i,x,a){printf((i-n?0:4)+"%0*d%0*d\n",i,x,n-i,0);R(a);}S(k,i){if(!(t=e=k>4?s[i]=48:k<1?s[i]=53:!G?H=k,G=i:0)){for(;t++<n;)putchar(48|t==i|t==G);puts("");R(&t);t==h?W(G,e=1,&t):0;s[G]=t>h?53+H:53-H,s[i]=t>h^e?53+k:53-k;G=0;}}main(){R(&n);for(W(n,0,&h);i++<n;S(t-h+5>>1,i))W(i,5,&t);s[G]=53+H,puts(s+1),s[G]=53-H,puts(s+1);}

Welcome to PPCG! You got a nice score of 162751*ln(388+50)=989887.

C# (.NET Core), 617 bytes, total attempts = 182255, score = 1185166
using System;namespace p{class C{static void Main(){var l=Console.ReadLine();int L=int.Parse(l);var g=new int[L];var p=n(g);for(int i=0;i<L;i++){g[i]=5;var d=n(g);var f=d-p;var s=f;switch(s){case 5:g[i]=0;d-=5;break;case-5:break;case 3:g[i]=1;d=n(g);f=d-p;if(f>0){g[i]=9;d-=2;}break;case 1:g[i]=2;d=n(g);f=d-p;if(f>0){g[i]=8;d-=4;}break;case-1:g[i]=3;d=n(g);f=d-p;if(f>0){g[i]=7;d-=4;}break;case-3:g[i]=4;d=n(g);f=d-p;if(f>-3){g[i]=6;d-=2;}break;}p=d;}n(g);}static int n(int[] g){foreach(var i in g){Console.Write(i);}Console.WriteLine();var s=Console.ReadLine();var d=int.Parse(s);if(d<1) Environment.Exit(0);return d;}}}

Hopefully C# in this format works for you. It is in the form of a complete program, so there should be a way to compile to an executable. Let me know if there's anything I can do to make it easier. Bytes are part of the scoring even though the Code Golf tag is removed so my official submission removes all the unneeded whitespace and useful names. My explanation below will use fragments of the ungolfed code:
Explanation
This program uses only a single helper method:
static int newGuess(IEnumerable<int> guess)
        {
            foreach (var item in guess)
            {
                Console.Write(item);
            }
            Console.WriteLine();
            var distanceString = Console.ReadLine();
            var distance = int.Parse(distanceString);
            if (distance < 1) System.Environment.Exit(0);
            return distance;
        }

This writes the guess to stdout, then reads the distance from stdin. It also immediately ends the program if a guess is the exact combination. I call it a lot. Next the initial setup:
var lengthString = Console.ReadLine();
int length = int.Parse(l);
var guess = new int[length];
var prevDistance = newGuess(guess);

This gets the length of the combination, then starts guessing with all 0s. Afterwards, it iterates through each digit in a for loop.
guess[i] = 5;
var distance = newGuess(guess);
var difference = distance - prevDistance;
var switchVar = difference;
switch (switchVar)

For each digit, it guesses 5, then decides on the next step based on how the distance changed since the previous guess (where that digit was 0).
case 5:
    guess[i] = 0;
    distance -= 5;
    break;

If the distance increased by 5, then 0 was correct for that distance. Adjust that digit back to 0. Altering the recorded distance manually prevents an extra guess.
case -5:
    break;

If the distance decreased by 5, then 5 is the correct digit and we move to the next digit immediately.
After that things are tricky. Using 5 and 0 for my initial guesses means that the remaining difference possibilities are 3, 1, -1, -3 with 2 possibilities for each, which need 1 additional guess to distinguish. Each of these cases takes a similar form
case 3:
    guess[i] = 1;
    distance = newGuess(guess);
    difference = distance - prevDistance;
    if (difference > 0)
    {
        guess[i] = 9;
        distance -= 2;
    }

Some of the numbers change, but essentially we try one of the two possibilities, and check whether the change was the correct one for that digit. If it wasn't, then the other digit is correct so we set that digit then adjust the difference manually.
This method means we should require, at most, 1 guess for the initial 0s, 2 guesses per digit, and then 1 final guess to ensure the last digit doesn't fall through.
It might be buggy though, it works as far as I've checked manually but that's no guarantee.
Bug found and squashed thanks to Colera Su

I tested it and it didn't work when answer is 37. The output is: 00, 50, 30, 75, 75 (yes, two 75s).

Replacing < with > in every if in switch seems to fix the bug. If that's what you want, your score is 182255*ln(617+50)=1185166.

@ColeraSu Indeed! I must have made a mistake with the find/replace when shortening the code. I've made the fix in the golfed code (the verbose version had the correct comparisons).

Python 2 and 3: 175 bytes, total attempts = 1005972, score = 5448445
This program takes ceil(log(n))*10 attempts per combination or every single digit takes 10 attempts (so, 333 takes 30 attempts).
N=int(input());o=0
def c(a):
 print("0"*(N-len(str(a)))+str(a))
 return int(input())
for j in range(N):m={c(i):i for i in reversed(range(0,10**(j+1),10**j))};o+=m[min(m)]
c(o)

Huge thanks to Colera Su for helping me with the input/output functionality.
Python Version of Challenge (Modified by OP).
I wrote a version of the lock code inside of Python.  You can go ahead and use if you're trying to solve this in Python (like me).  The following works in Python 2 and 3.  It made a lot more sense just to implement lock as a class you can test against and I decided to create a generator function for guessing the inputs.
import sys

class Lock:
    def __init__(self, number):
        self.lock = str(number)
    def l(self): #lengthOfNumber
        return len(self.lock)
    def c(self, guess): #check a guess
        guess = str(guess)
        guess = "0" * (len(self.lock) - len(guess)) + guess
        difference = 0
        for i in range(len(self.lock)):
            d1 = abs(int(self.lock[i]) - int(guess[i]))
            d2 = 10 - d1
            difference += d1 if d1 < d2 else d2
        return difference

def masterLock():
    testdata = ["000","555","755","735","744","746"]
    for answer in testdata:
        yield Lock(answer)

class LockIO:
    def __init__(self):
        self.lock = int(input())
    def l(self):
        return self.lock
    def c(self, guess):
        guess = str(guess)
        guess = "0" * (self.lock - len(guess)) + guess
        print(guess)
        sys.stdout.flush()
        return int(input())

for l in masterLock():
    # Write your code here that tries to guess it
    #   When you're done testing you can unindent your code,
    #   replace "for l in masterLock():" with "l = LockIO()"
    #   and submit the code.
    #
    # Examples:
    #  l.l()      # returns the length of the lock
    #  l.c("952") # returns the distance to the lock
    #  l.c(952)   #  number also works
    pass

First, sorry about that I wrote the LockIO class wrong. I've sent a edit request.
Second, I think you've misread the scoring criterion. The score is calculated by the testdata generated by the generator, not example (I executed your program, and the total number is 1005972). The natural log is also missing.
Third, I've specified that you need to provide a full program, so you should include the LockIO part in your byte count as well. Additionally, you need to output the final result, and that is also counted in the score.

@ColeraSu How is "the class LockIO" related here? Also what is the second block of Python code used for?

@user202729 Lock and masterLock is just for convenience of testing. LockIO is what you actually need to submit, since it uses the required I/O format.

@nfnneil I've added a sample program in the main post. I also sent an edit request for your reference.

@ColeraSu As I was falling asleep I realized what you meant and thanks man.  It was a good challenge.

R, 277 bytes (score=1175356) 258 bytes, total attempts = 202999, score = 1163205
f=file("stdin","r")
w=function(b=1,A=X){cat(A,"\n",sep="");if(b){b=scan(f,n=1)};b}
M=0:9
s1=c(-5,-3,-1,1,3,5,3,1,-1,-3)
s2=s1+rep(c(1,-1),,,5)
L=w(1,"")
X=S=rep(0,L)
v0=w()
for(i in 1:L){X[i]=5
v1=v0-w()
X[i]=4
v2=v0-w()
S[i]=M[s1==v1&s2==v2]
X=0*S}
b=w(0,S)

Try it online!
Stdin-stdout version, as requested by the OP, no boilerplates.
Thanks to Colera Su for fixing an initial bug. This is a marginally shorter version than the one in the comments.

Here below the TIO submission to run a batch of tests within TIO
R, 189 bytes
M=0:9
s1=c(-5,-3,-1,1,3,5,3,1,-1,-3)
s2=c(-4,-2,0,2,4,4,2,0,-2,-4)
f=function(L){S=rep(0,L)
v0=v(S)
X=S
for(i in c(1:L)){X[i]=5
v1=v0-v(X)
X[i]=4
v2=v0-v(X)
S[i]=M[s1==v1&s2==v2]
X[i]=0}
S}

Try it online!
Let's consider a vector of zeros as the initial guess.
Let's call V the distance between the current guess and the solution.
For each position you only need to check the changes in V when you replace 0 with 5 and with 4.
In fact, the differences between changing 0 with 5 are listed in my vector s1. The differences between changing 0 with 4 are listed in my vector s2. As you see these two vectors uniquely map the digits of the solution.
The total number of tests is thus 3*L 2*L + 1, where L is the length of the code: an initial check against all zeros, then two checks for each digit, one against 5 and one against 4.
The improvement from a factor 3 to a factor 2 was inspired by Kamil Drakari's submission.
The rest of the TIO submission is boilerplate for R.
The TIO submission showcases the running time and the total number of operations for 1000 runs with L=1...200, 5 replicates for each value of L.

I get Error in scan(n = 1) : scan() expected 'a real', got 'S=rep(0,L)' when executing.

It seems that scan(file=file("stdin"),n=1) works. This program (same as yours, just corrected I/O) get a score of 202999*ln(277+50)=1175356.

@ColeraSu , I may have missed something, but I thought that 202999*ln(258+50) != 202999*ln(277+50)

Seems that @user202729 made a typo. Fixed.


text:
Implement simplified kerning
Introduction
Kerning means adjusting the spacing between the letters of a text.
As an example, consider the word Top written with the following three glyphs:
##### ..... .....
..#.. ..... .....
..#.. ..##. .###.
..#.. .#..# .#..#
..#.. .#..# .#..#
..#.. ..##. .###.
..... ..... .#...
..... ..... .#...

We could just fill the gaps between the glyphs with dots and be done with it, but the gaps somehow look too wide.
Instead, we slide the glyphs to the left so that they almost touch:
#####........
..#..........
..#..##..###.
..#.#..#.#..#
..#.#..#.#..#
..#..##..###.
.........#...
.........#...

This looks much better!
Note how the bar of T is on top of the left border of o.
In this challenge, your task is to implement a simple kerning program for such rectangular glyphs.
The kerning process
Consider two rectangular 2D character arrays of . and # of the same shape.
In our simple kerning process, we first place the arrays side by side, with one column of .s in between.
Then, we move each # in the right array one step to the left, until some #s of the left and right array are orthogonally or diagonally adjacent.
The outcome of the kerning is the step before we introduce adjacent #s.
Your task is to implement this process.
Let's take an example:
Inputs:
..###
#....
#....
..##.

...#.
...##
..###
....#

Process:
..###....#.
#........##
#.......###
..##......#

..###...#.
#.......##
#......###
..##.....#

..###..#.
#......##
#.....###
..##....#

..###.#.
#.....##
#....###
..##...#

..####.
#....##
#...###
..##..#

In the last array, we have new adjacent pairs of #s, so the second-to-last array is the result of the kerning process.
Input and output
For simplicity, you only need to handle kerning of two glyphs.
Your inputs are two rectangular 2D arrays, in one of the following formats:

2D arrays of integers, with 0 standing for . and 1 for #.
Multiline strings over .#.
Arrays of strings over .#.
2D arrays of the characters .#.

If the inputs are taken as a single string, you can use any reasonable delimiter.
However, the delimiter should go between the two arrays, meaning that you are not allowed to take the two inputs already paired row-by-row.
Your output is the result of the kerning process applied to these two arrays, which is a rectangular 2D array in the same format as the inputs.
You are allowed to add or remove any number of leading or trailing columns of .s, but the output must be rectangular and have the same height as the inputs.
It is guaranteed that the kerning process ends before the left edge of the second input slides over the left edge of the first input.
Rules and scoring
The lowest byte count in each programming language wins.
Standard code-golf rules apply.
Test cases
To help with copy-pasting, these test cases are given as lists of strings.
["#"] ["#"] -> ["#.#"]
["#.","..",".#"] ["##","..","##"] -> ["#..##",".....",".#.##"]
["..#","#..","#.."] ["...","..#","###"] -> ["..#..","#...#","#.###"]
["###.","##..","#...","...."] ["....","...#","..#.",".#.."] -> ["###..","##..#","#..#.","..#.."]
["..##...","#......","#......"] [".....##",".....##",".#...#."] -> ["..##..##","#.....##","#.#...#."]
["...#.",".....",".....",".....","....#"] [".....","....#","#....",".....","....."] -> ["...#..",".....#",".#....","......","....#."]
["..#..",".....",".....",".....","....#"] [".....","....#","#....",".....","....."] -> ["..#..","....#","#....",".....","....#"]
["######","#.....","#.....","#.....","######"] ["......",".....#",".#...#",".....#","......"] -> ["######..","#......#","#..#...#","#......#","######.."]
["######","#.....","#.....","#.....","######"] ["......","......",".#....","......","......"] -> ["######","#.....","#.#...","#.....","######"]
["#...#","#..#.","#.#..","##...","#.#..","#..#.","#...#"] ["...#.","..#..",".#...",".#...",".#...","..#..","...#."] -> ["#...#..#","#..#..#.","#.#..#..","##...#..","#.#..#..","#..#..#.","#...#..#"]

Visualizer. Test case 5 seems to be wrong.

@user202729 Thanks, it's fixed now. I went through several rounds of fixing the test cases in the sandbox, and apparently missed that one.

Also if the two characters "fall through" each other what should the program do?

@user202729 You can assume that will not happen. See the last sentence of section "Input and output".

APL (Dyalog Classic), 40 39 bytes
-1 thanks to Erik the Outgolfer
{⌈⌿↑⍺(⍉(1-⌈/+⌿+∘×⍨2⌈/0,+/⌈\↑(⌽⍺)⍵)↑⍉⍵)}

Try it online!

Python 3, 154 bytes
lambda a,b,p=".":[c.rstrip(p)+d.lstrip(p).rjust(max(len((d+c).strip(p))for(c,d)in zip((a*3)[1:],b[:-1]+b+b[1:]))+1-len(c.rstrip(p)),p)for(c,d)in zip(a,b)]

Try it online!

Retina, 223 bytes
+`(.+)¶(¶(.+¶)*)(\W+(¶|$))
$2$1i$4
T`.`i`\.*i\.*
+`(¶(.)*#.*i.*¶(?<-2>.)*)i
$1@
+`(¶(.)*)i(.*¶(?<-2>.)*(?(2)(?!))#.*i)
$1@$3
T`i@`.`i*[#@]+i
mT`.`i`\.+i+$
msT`i`.`.*^\W+$.*
+`(\b(i+)\W+\2i*)i
$1.
+s`\bi((i+).+\b\2\b)
.$1
i

Try it online! Link includes test cases plus header script to reformat them to its preferred input format of two newline-delimited strings. This seems overly long yet there's probably an edge case that I've overlooked, but it does at least pass all of the test cases now. Explanation:
+`(.+)¶(¶(.+¶)*)(\W+(¶|$))
$2$1i$4

Join the two input arrays together using a letter i as a separator. (This allows use of \W and \b later on.)
T`.`i`\.*i\.*

Change all the .s to is at the join.
+`(¶(.)*#.*i.*¶(?<-2>.)*)i
$1@

Change all is below #s to @s.
+`(¶(.)*)i(.*¶(?<-2>.)*(?(2)(?!))#.*i)
$1@$3

Change all is above #s to @s.
T`i@`.`i*[#@]+i

Change all the @s to .s, plus all the is adjacent to @s or #s.
mT`.`i`\.+i+$

If there is no # after an i, then change the adjacent . back to an i again.
msT`i`.`.*^\W+$.*

If there is a line with no is, change all the is to .s, as there is nothing to do here.
+`(\b(i+)\W+\2i*)i
$1.

Calculate the minimum number of is on any line.
+s`\bi((i+).+\b\2\b)
.$1

Propagate to the other lines.
i

Delete the is, thus performing the required kerning.