title: Is it a valid chess move?

text:
# Question
Title: 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 , 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

# Answer
# 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: **P**awn, k**N**ight, **B**ishop, **R**ook, **Q**ueen, **K**ing. 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.
> 11 votes

# Answer
# 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]
    )

```
> 5 votes

# Answer
# 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:

1. 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)
2. the piece-name attempting to move (as given in the OP -- one of `PRNBQK`)
3. 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).
> 4 votes

# Answer
# 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:

1. 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.
2. 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
> 4 votes

---
Tags: code-golf, decision-problem, chess
---


# Question
Title: Doing a little trolling with the microwave timer
Related

Sometimes when I use my microwave, I do a little trolling and enter times such as `2:90` instead of `3:30` because they end up being the same time anyway. The microwave happily accepts this and starts counting down from `2:90`, displaying times like `2:86` and `2:69` until it gets back to a stage where it can count down like a normal timer. Y'all's task today is to simulate this behaviour by returning a list of all times displayed by the microwave when given a starting time.

## An Example

Say I input `2:90` into the microwave. It starts at `2:90` and then shows `2:89`, `2:88`, `2:87`, `2:86`, ..., `2:60`, `2:59`, `2:58`, `2:57`, ..., `2:00`, `1:59`, `1:58`, `1:57`, ..., `0:05`, `0:04`, `0:03`, `0:02`, `0:01`, `END`. As you can see, where the seconds are less than `60`, it acts as normal. But where the seconds are greater than `60`, it decrements the seconds without impacting the minute count.

## Rules

* Input can be taken in any convienient and reasonable format, including, but not limited to:

+ `[minutes, seconds]`
    + `[seconds, minutes]`
    + `minutes` on one line, `seconds` on the next
    + `seconds` on one line, `minutes` on the next
    + a single integer which is a \[minutes, seconds\] pair divmod 100 (e.g `130` represents `1:30`).
* Output can be given in any convienient and reasonable format, including, but not limited to:

+ `[[minute, second], [minute, second], [minute, second], ...]`
    + `["minute second", "minute second", "minute second", ...]`
    + `minute second\n minute second\n ...`
    + `[[second, minute], [second, minute], [second, minute], ...]`
* The outputted times can be returned in any order - they don't need to be sorted.
* The seconds will never be greater than `99`.
* Including `[0, 0]` or `0:00` is optional.

Make sure to include how you're outputting the times in your answer.

## Sample IO

Input here is given as `[minutes, seconds]`. Output is given as a list of `[minute, seconds]`

```
[0, 90] => [[0, 90], [0, 89], [0, 88], [0, 87], [0, 86], [0, 85], [0, 84], [0, 83], [0, 82], [0, 81], [0, 80], [0, 79], [0, 78], [0, 77], [0, 76], [0, 75], [0, 74], [0, 73], [0, 72], [0, 71], [0, 70], [0, 69], [0, 68], [0, 67], [0, 66], [0, 65], [0, 64], [0, 63], [0, 62], [0, 61], [0, 60], [0, 59], [0, 58], [0, 57], [0, 56], [0, 55], [0, 54], [0, 53], [0, 52], [0, 51], [0, 50], [0, 49], [0, 48], [0, 47], [0, 46], [0, 45], [0, 44], [0, 43], [0, 42], [0, 41], [0, 40], [0, 39], [0, 38], [0, 37], [0, 36], [0, 35], [0, 34], [0, 33], [0, 32], [0, 31], [0, 30], [0, 29], [0, 28], [0, 27], [0, 26], [0, 25], [0, 24], [0, 23], [0, 22], [0, 21], [0, 20], [0, 19], [0, 18], [0, 17], [0, 16], [0, 15], [0, 14], [0, 13], [0, 12], [0, 11], [0, 10], [0, 9], [0, 8], [0, 7], [0, 6], [0, 5], [0, 4], [0, 3], [0, 2], [0, 1], [0, 0]]
[1, 20] => [[1, 20], [1, 19], [1, 18], [1, 17], [1, 16], [1, 15], [1, 14], [1, 13], [1, 12], [1, 11], [1, 10], [1, 9], [1, 8], [1, 7], [1, 6], [1, 5], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], [0, 59], [0, 58], [0, 57], [0, 56], [0, 55], [0, 54], [0, 53], [0, 52], [0, 51], [0, 50], [0, 49], [0, 48], [0, 47], [0, 46], [0, 45], [0, 44], [0, 43], [0, 42], [0, 41], [0, 40], [0, 39], [0, 38], [0, 37], [0, 36], [0, 35], [0, 34], [0, 33], [0, 32], [0, 31], [0, 30], [0, 29], [0, 28], [0, 27], [0, 26], [0, 25], [0, 24], [0, 23], [0, 22], [0, 21], [0, 20], [0, 19], [0, 18], [0, 17], [0, 16], [0, 15], [0, 14], [0, 13], [0, 12], [0, 11], [0, 10], [0, 9], [0, 8], [0, 7], [0, 6], [0, 5], [0, 4], [0, 3], [0, 2], [0, 1], [0, 0]]
[2, 90] => [[2, 90], [2, 89], [2, 88], [2, 87], [2, 86], [2, 85], [2, 84], [2, 83], [2, 82], [2, 81], [2, 80], [2, 79], [2, 78], [2, 77], [2, 76], [2, 75], [2, 74], [2, 73], [2, 72], [2, 71], [2, 70], [2, 69], [2, 68], [2, 67], [2, 66], [2, 65], [2, 64], [2, 63], [2, 62], [2, 61], [2, 60], [2, 59], [2, 58], [2, 57], [2, 56], [2, 55], [2, 54], [2, 53], [2, 52], [2, 51], [2, 50], [2, 49], [2, 48], [2, 47], [2, 46], [2, 45], [2, 44], [2, 43], [2, 42], [2, 41], [2, 40], [2, 39], [2, 38], [2, 37], [2, 36], [2, 35], [2, 34], [2, 33], [2, 32], [2, 31], [2, 30], [2, 29], [2, 28], [2, 27], [2, 26], [2, 25], [2, 24], [2, 23], [2, 22], [2, 21], [2, 20], [2, 19], [2, 18], [2, 17], [2, 16], [2, 15], [2, 14], [2, 13], [2, 12], [2, 11], [2, 10], [2, 9], [2, 8], [2, 7], [2, 6], [2, 5], [2, 4], [2, 3], [2, 2], [2, 1], [2, 0], [1, 59], [1, 58], [1, 57], [1, 56], [1, 55], [1, 54], [1, 53], [1, 52], [1, 51], [1, 50], [1, 49], [1, 48], [1, 47], [1, 46], [1, 45], [1, 44], [1, 43], [1, 42], [1, 41], [1, 40], [1, 39], [1, 38], [1, 37], [1, 36], [1, 35], [1, 34], [1, 33], [1, 32], [1, 31], [1, 30], [1, 29], [1, 28], [1, 27], [1, 26], [1, 25], [1, 24], [1, 23], [1, 22], [1, 21], [1, 20], [1, 19], [1, 18], [1, 17], [1, 16], [1, 15], [1, 14], [1, 13], [1, 12], [1, 11], [1, 10], [1, 9], [1, 8], [1, 7], [1, 6], [1, 5], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], [0, 59], [0, 58], [0, 57], [0, 56], [0, 55], [0, 54], [0, 53], [0, 52], [0, 51], [0, 50], [0, 49], [0, 48], [0, 47], [0, 46], [0, 45], [0, 44], [0, 43], [0, 42], [0, 41], [0, 40], [0, 39], [0, 38], [0, 37], [0, 36], [0, 35], [0, 34], [0, 33], [0, 32], [0, 31], [0, 30], [0, 29], [0, 28], [0, 27], [0, 26], [0, 25], [0, 24], [0, 23], [0, 22], [0, 21], [0, 20], [0, 19], [0, 18], [0, 17], [0, 16], [0, 15], [0, 14], [0, 13], [0, 12], [0, 11], [0, 10], [0, 9], [0, 8], [0, 7], [0, 6], [0, 5], [0, 4], [0, 3], [0, 2], [0, 1], [0, 0]]

```

As this is , the aim of the game is to get your byte count as low as possible

# Answer
# Haskell, 43 bytes

*Doesn't output `0:0`*

```
0?0=[]
n?0=(n,0):(n-1)?59
n?m=(n,m):n?(m-1)

```

Try it online!

This is very simple. Decrements the second hand unless it's zero, in which case it decrements the minute unless it's zero in which case it ends.

# Haskell, 46 bytes

*Outputs `0:0`*

```
n?m=(n,m):[n?(m-1),[(n-1)?59|n>0]>>=id]!!(0^m)

```

Try it online!

This one is a bit more complicated than the last. It employs two special tricks for cheaper branching.

To check the second hand `m`. We do `0^m` which gives \\$1\\$ when `m` is \\$0\\$ and \\$0\\$ otherwise. We can use this to index a list to switch between the two options.

To check the minute hand `n`. We use a list comprehension trick. `[(n-1)?59|n>0]` is empty when `n` is zero and `[(n-1)?59]` otherwise. We use `>>=id` to concat away the wrapping list and then we get `(n-1)?59` when `n>0` and `[]` otherwise.
> 14 votes

# Answer
# , 41 bytes

```
f=\(m,s,`~`=rbind)t(m~s:0)~if(m)f(m-1,59)
```

Attempt This Online!

Makes a 2-column matrix of the minutes and seconds...zero. Then, if the minutes are non-zero, appends the matrix from a recursive call to itself with `m-1` minutes and 59 seconds.
> 12 votes

# Answer
# Jelly, ~~13~~ ~~12~~ 11 bytes

```
ȷ2ḍ41*ạµ¹Ð¿

```

Try it online!

*-1 thanks to Zion mycelia adamancy, and another -1 with inspiration from their suggestion*

Uses flat integer I/O.

Could almost be 10 (`ạ41$’ọ?Ƭȷ2`), but that fails for inputs under 41.

```
       µ¹Ð¿    Collect results to (and through) 0 from:
   41*         raise 41 to the power of
ȷ2ḍ            if the number is divisible by 100,
      ạ        and take its absolute difference with that.

```
> 7 votes

# Answer
# C (gcc), 43 bytes

```
f(n){printf("%d ",n);n&&f(n%100?n-1:n-41);}

```

Try it online!
> 7 votes

# Answer
# Python 3, 52 bytes

```
f=lambda m,s:m+1and[[m,s]]+f(m-0**s,(s or 60)-1)or[]

```

Try it online!
> 6 votes

# Answer
# K (ngn/k), 24 bytes

```
(|/){x-$[*|x;!2;1 -59]}\

```

Try it online!

-1 byte thanks to @dzaima! -3 bytes thanks to @coltim!

## Explanation

Input is *l*.

* `(|/){...}\` while *l* is not `0 0` (keeping intermediate results)...
    + `x-...` decrement the timer by...
        - `$[*|x;...;...]` if seconds \> 0...
            * `!2` equivalent to `0 1`, so `[x[0]-0, x[1]-1]`
            * `1 -59` otherwise reset seconds, so `[x[0]-1, x[1]-(-59)]`
> 5 votes

# Answer
# Vyxal, 12 bytes

```
⁽⌊λ₁Ḋ40*›-;ŀ

```

Try it Online!

Port of Jelly answer. Takes single integer and outputs list of ints.

16 bytes taking second and minute.
> 4 votes

# Answer
# C (GCC), 78 bytes

```
main(h,m){for(scanf("%d%d",&h,&m);h+m;m?--m:--h&(m=59))printf("%d %d\n",h,m);}
```

Attempt This Online!
> 4 votes

# Answer
# Rust, ~~113~~ 100 bytes

```
|t:(u8,u8)|(0..t.0*60+t.1).scan(t,|t,_|Some((*t,*t=match t{(n,0)=>(*n-1,59),(m,s)=>(*m,*s-1)}).0));

```

Had to increase it to follow rules more strictly. Skips the (0,0) at the end.

Playground link
> 3 votes

# Answer
# JavaScript (ES6),  ~~42~~  41 bytes

Expects `(m)(s)`. Returns a list of `[minutes, seconds]` pairs.

```
m=>g=s=>~m?[[m,s],...g(s?s-1:m--&&59)]:[]

```

Try it online!
> 3 votes

# Answer
# Brainfuck, 36 bytes

```
,+>,+<[->[-<.>.]>----[<+>----]<---<]

```

Try it online!

There are no separators and output is just `hours minutes hours minutes ...` in form of bytes.

Separator `-1` can be added at the cost of 7 bytes (totaling 43 bytes):

```
->,+>,+<[->[-<.>.<<.>>]>----[<+>----]<---<]

```

Explanation:

```
,+                    load hours
>,+                   load minutes
<[-                   loop through all hours
  >[-                 loop through all minutes
    <.>.              print hours and minutes
  ]
  >----[<+>----]<---< set minutes to 60; constant is take from esolangs wiki
]

```
> 3 votes

# Answer
# HBL, 15.5 bytes

```
1'.(?,('?.(-,)).('?(-.)(-'-*))?

```

Takes the minutes and seconds as separate arguments to the main program; outputs a list of two-number lists. Try it here!

### Explanation

```
1'.(?,('?.(-,)).('?(-.)(-'-*))?
1                                Cons
 '.                              the argument list
                                 to:
   (?                             If
     ,                            the second argument (is nonzero):
      ('?     )                    Recursive call
         .                         with the same first argument
          (-,)                     and a decremented second argument
                                  Else if
               .                  the first argument (is nonzero):
                ('?          )     Recursive call
                   (-.)            with a decremented first argument
                                   and a second argument of
                       (-   )      the difference between
                         '-        64
                           *       and 5
                                  Else:
                              ?    Empty list

```
> 3 votes

# Answer
# Javascript, 49 bytes

```
let g=a=>([b,c]=a,(b+c)?[g([b-!c,c?c-1:59]),a]:a)

```

A recursive function that takes in an array like `[minutes, seconds]`, and repeatedly appends it to the array that contains the next values.
> 3 votes

# Answer
# Curry (PAKCS), 40 bytes

```
n#m=(n,r m)?(r$n-1,r 59)
r n=anyOf[0..n]

```

Try it online!

This is a non-deterministic function whose return values are the all the ouputs.
> 3 votes

# Answer
# 05AB1E, 12 bytes

```
[=Ð_#тÖ40*>-

```

I/O as integers. Outputs everything on a separated line to save bytes.

Try it online or verify all test cases.

**Explanation:**

```
[          # Loop indefinitely:
 =         #  Print the current number with newline (without popping)
           #  (which will be the implicit input-integer in the first iteration)
  Ð        #  Triplicate the value
   _       #  Pop one, and if it's 0:
    #      #   Stop the infinite loop
   тÖ      #  (Else) Pop another, and check if it's divisible by 100
     40*   #  Multiply that by 40
        >  #  Increase that by 1
         - #  Decrease the value by this

```
> 3 votes

# Answer
# K (ngn/k), 18 bytes

```
{(x,'!y+1),+!x,60}

```

Try it online!

Uses the fact that *outputted times can be returned in any order*. Using the descending order would costs 2 bytes: `{(x,'|!y+1),|+!x,60}`.
> 3 votes

# Answer
# \*\>\<\>, 64 bytes

```
c5*&       1+\
/!?)0:C31-1  <
\r:?!;1-r~&:&/
>r:r:{ao\
R no" "n/

```

Try it online!

I'd like to believe this could be golfed more, mostly in the output section, but this is as good as I could get it.

Using the `-i` flag, the stack is initialize with `[<minutes>, <seconds>]`. Throughout the program, the "canon" seconds can be considered to be at the top of the stack, and minutes right below that.

```
Main loop:
c5*&            Push 60 onto the stack, and then pop it into a register
           1+   Add 1 to the seconds, this way our starting time is printed correctly
             \  Mirror the IP down

             <  Change IP direction to the left
         -1     Subtract one from our seconds
      C31       Go to the print function
     :          Duplicate our seconds
    0           Push 0 onto the stack
   )            Check if the seconds is greater than 0
 !?             If it is, IP continues left, wrapping back to our < instruction
/               Else, mirror the IP down

\               Mirror the IP to the right
 r:             Put the minutes on top of the stack and duplicate it
   ?!;          If the minutes and the seconds are 0, end execution
      1-        Else, subtract one from the minutes
        r       Put the seconds back on top of the stack
         ~      Remove the seconds
         &:&    Take 60 out of the register, duplicate it, and pop that duplicate back into the register
            /   Mirror the IP up into the < on line 2

Print function:
>               Change the IP direction to the right
 r:             Reverse the stack, and duplicate the top value
   r:           Repeat
     {          Shift the stack to the left. Stack should look like [m, s, s, m]
      ao        Print a newline
        \       mirror the IP down
        /       Mirror the IP to the left
       n        Pop the top of the stack, print it as a number
   o" "         Print a space
  n             Pop the top of the stack, print it as a number
R               Return the IP to where it was, maintaining current direction

```
> 3 votes

# Answer
# Husk, 12 bytes

```
↑Σ¡?-41←¦100

```

Try it online!

Port of unrelated string's answer: upvote that. Inputs & outputs as simple integers (so, no separator between minutes & seconds).

```
↑Σ¡?-41←¦100
  ¡                 # apply function repeatedly, collect values in infinite list:
   ?                #  if:
        ¦100        #   it's divisible by 100
    -41             #  then: subtract 41
       ←            #  else: decrement
↑                   # finally, get longest prefix where function gives truthy result:
 Σ                  #  sum (of secs, mins)

```

---

Previous approach:

# Husk, 15 bytes

```
↑Σ¡?ż-ḋ2ȯe59←→←

```

Try it online!

Outputs as \[\[secs,mins\]...\], omitting \[0,0\] at the end.

```
  ¡                 # apply function repeatedly, collect values in infinite list:
   ?                #  if:
              ←     #   the first element is nonzero
    ż-ḋ2            #  then: zip-subtract 1,0 (binary digits of 2)
        ȯe59        #  else: make a 2-element list of 59 and
            ←→      #   the last element, decremented
↑                   # finally, get longest prefix where function gives truthy result:
 Σ                  #  sum (of secs, mins)

```
> 2 votes

# Answer
# , 25 24 bytes

```
(,.i.,])(,,/)60,"0/&i.~[

```

Try it online!
> 2 votes

# Answer
# Retina 0.8.2, ~~79~~ 74 bytes

```
\d+
$*
\G1
1$'¶
1>`:.*
:59$*
%(r`1\G
¶$`1
O^`
(1*):(1{10})*(1*)
$.1:$#2$.3

```

Try it online! Takes input in `m:ss` format. Output includes both start and end times. Explanation:

```
\d+
$*

```

Convert to unary.

```
\G1
1$'¶

```

Count down to `0` minutes.

```
1>`:.*
:59$*

```

Subsequent minutes count down from `59`.

```
%(`

```

Apply the rest of the script to each minute individually.

```
r`1\G
¶$`1
O^`

```

Count down to `0` seconds.

```
(1*):(1{10})*(1*)
$.1:$#2$.3

```

Convert to decimal.
> 2 votes

# Answer
# Rust, 67 bytes

```
|mut h,mut m,f:fn(u8,u8)|while h+m>0{f(h,m);if m<1{h-=1;m=60};m-=1}

```

This one takes a function pointer, and outputs by calling that function.

Playground link (without gist), for which I ruthlessly plagiarised mousetale's test harness. Without that, I probably wouldn't've written this answer.

There's a shorter (60 byte) version, if you replace the `while h+m>0` with `loop`. That only works in debug mode, though – in which it exits the loop by panicking – so I don't know that it counts.
> 2 votes

# Answer
# Zsh, 46 bytes

```
m=({$1..0})
echo $m[1]:{$2..0} ${^m:1}:{59..0}

```

Try it online!

The `^` flag sets the `RC_EXPAND_PARAM` flag for that expansion.

The list is needed because `{a..b}` never expands to zero arguments, while `${^foo}` does.
> 2 votes

# Answer
# Factor \+ `math.unicode pair-rocket`, 60 bytes

```
[ [ .s dup last 0 = 1 => -59 "\0"? v- dup Σ 0 > ] loop . ]

```

Try it online!

Outputs times to standard output in the format `{ minutes seconds }`, one per line, in the order they would be seen on the microwave display.
> 1 votes

# Answer
# Pyth, 18 bytes

```
WsQQ=?eAQ,GtH,tG59

```

Try it online!

Doesn't include \[0,0\]

```
WsQQ=?eAQ,GtH,tG59
                    (Q implicitly initialized as the input)
WsQ                 While sum(Q) > 0:
   Q                 Output Q
       AQ            Set [G,H] = Q (minutes and seconds, respectively)
    =                Update Q to the following:
     ?e Q             If (seconds) > 0:
         ,GtH          [(minutes), (seconds) - 1]
                      Else:
             ,tG59     [(minutes) - 1, 59]

```

---

If single-integer output is allowed:

### Pyth, 15 bytes

```
WQQ=-Q^41!%Q100

```

Try it online!
> 1 votes

# Answer
# Perl 5 `-a`, 43 bytes

```
do{say"@F";@F=(--$_,59)if!$F[1]--}until$_<0

```

Try it online!

Minutes and seconds are space separated in both input and output.
> 1 votes

# Answer
# Charcoal, 17 bytes

```
ＩＥ⊕θＥ⎇‹ιＩθ⁶⁰⊕η⟦ιλ

```

Try it online! Link is to verbose version of code. Takes minutes and seconds as separate input and outputs a list of lists of lists of minute and second pairs in ascending order. Explanation:

```
   θ                First input
  ⊕                 Incremented
 Ｅ                  Map minutes over implicit range
       ι            Current minute
      ‹             Is less than
         θ          First input
        Ｉ           Cast to integer
     ⎇              If true then
          ⁶⁰        Literal integer `60` else
             η      Second input
            ⊕       Incremented
    Ｅ               Map seconds over implicit range
              ⟦ιλ   Minute and second as a list
Ｉ                   Cast to string
                    Implicitly print

```
> 1 votes

# Answer
# Julia, 39 bytes

```
m>s=show((m,s))~s<1 ? -1<m-1>60 : m>s-1

```

Try it online!

Takes input as two arguments (`1>90`), prints the values as tuples and ends with an error
> 1 votes

---
Tags: code-golf, number
---


title: Does it match the digit pattern?

text:
# Question
Title: Does it match the digit pattern?
Recently I had a Maths test and noticed that a certain number on the test matched an interesting pattern. The number (`28384`) matched a generic digit sequence that looks like this

```
(n)(x)(n+1)(x)(n+2)(x)(n+3) etc...

```

where `n` and `x` are single digit integers. The sequence can begin with either `x` or `n` and end with either `x` or `n+y`.

Your task is, given a multi digit positive integer, output a truthy or falsey value, depending on whether the input matches the pattern. The input will be between 4 and 18 digits long. You may take input as a string representation of the integer. The input will not begin with a 0 but can contain or end with 0s.

`n+y` will always be a single digit number (hence why the length limit is 18).

# Test Cases

These should output a truthy value

```
182838485868788898
4344
85868
12223242526

```

And these should be falsey

```
12345
6724013635
36842478324836
1222232425
5859510511

```

As with all code golfs, shortest code wins! Good luck and may the odds, be ever in your favour!

# Answer
# Python 2, ~~84~~ ~~81~~ ~~80~~ 79 bytes

*-1 byte thanks to ovs*

```
lambda x:g(x,1)|g(x,0)
g=lambda x,a:len(set(x[a::2]))==(x[a<1::2]in"123456789")

```

Try it online!

---

# Python 3, ~~82~~ ~~79~~ ~~78~~ 77 bytes

```
lambda x:g(x,1)|g(x,0)
g=lambda x,a:len({*x[a::2]})==(x[a<1::2]in"123456789")

```

Try it online!

Slightly shorter in Python 3, but I didn't think it deserved its own answer.

---

# Explanation

We set up a function `g` that takes string and an index (either 1 or 0). `g` then returns whether or not `len(set(x[a::2]))`, that is the number of unique digits in every other position, is equal to `(x[a==0::2]in"123456789")`, whether or not the other digits are in ascending order. If the digits are in ascending order this returns whether or not they are all the same, if not it will ask if the set is empty, which it cannot be, thus always returning false.
> 9 votes

# Answer
# Jelly, ~~13~~ 11 bytes

```
Ds2ZI’M¦Ẏ¬Ạ

```

Try it online!

Explanation:

```
Ds2ZI’M¦Ẏ¬Ạ Accepts an integer
D           Get individual digits
  2         2
 s          Split into chunks of specific length
   Z        Zip
    I       Take deltas
     ’      Decrement
      M     Take maximal indices
       ¦    Apply at specific indices
        Ẏ   Reduce dimensionality
         ¬  Vectorized NOT
          Ạ Check if all are truthy

```
> 5 votes

# Answer
# 05AB1E, 15 bytes

```
TG9LNýN.øŒ})˜Iå

```

Try it online!

### Explanation

```
TG9LNýN.øŒ})˜Iå
TG        }     # For 1 to 9...
  9L             # Push [1 .. 9]
    Ný           # Join with current value
      N.ø        # surround with current value
         Œ       # Push substrings
           )    # Wrap stack to array
            ˜   # Deep flatten the array
             I  # Push input
              å # Is the input in the array?
                # Implicit print

```

It should work (test cases did) but if you find any flaws please let me know.

14 Bytes if no output counts as falsy:

```
TG9LNýN.øŒIåi1

```
> 3 votes

# Answer
## D, 117 bytes

```
int f(string n){int o=n[0]!=n[2],x=n[o];foreach(i,c;n){if(i%2!=o&&i>1&&c!=n[i-2]+1||i%2==o&&c!=x)return 0;}return 1;}

```

Definitely suboptimal, but it works fine

Try It Online!
> 3 votes

# Answer
# Haskell, ~~108~~ ~~113~~ ~~97~~ 95 bytes

```
d(x:_:r)=x:d r
d r=r
c(x:n:r)=and$all(==x)(d r):zipWith(==)(d$n:r)[n..]
f s@(_:n:_)=c s||c(n:s)

```

Sample call: `f "182838485868788898"` yields `True`

Ungolfed version with explanations:

```
-- Take every other element from the string, starting with the first
d (x:_:r) = x : d r
d r       = r
c (x:n:r) = and $ all (== x) (d r)              -- Every other char is equal to the first
                : zipWith (==) (d $ n:r) [n..]  -- The remaining chars are a prefix of n(n+1)(n+2)...
f s@(_:n:_) = c s      -- The case where s already starts with x
           || c (n:s)  -- If not, prepend a dummy x and try again

```
> 3 votes

# Answer
## JavaScript (ES6), ~~66~~ ~~63~~ 60 bytes

Takes input as a string.

```
s=>[...s].every((d,i)=>d-s[j^(k=i+j&1)]==k*i>>1,j=s[2]-s[0])

```

### Test cases

```
let f =

s=>[...s].every((d,i)=>d-s[j^(k=i+j&1)]==k*i>>1,j=s[2]-s[0])

console.log('[Truthy]');
console.log(f("182838485868788898"))
console.log(f("4344"))
console.log(f("85868"))
console.log(f("12223242526"))

console.log('[Falsy]');
console.log(f("12345"))
console.log(f("6724013635"))
console.log(f("36842478324836"))
console.log(f("1222232425"))
```
> 2 votes

# Answer
# Python 3, ~~99 96~~ 89 bytes

* Saved 3 bytes: use of `all()` function
* @WheatWizard saved 7 bytes:shorthanding `&` `|` and replace extra variable by `k<1`

```
lambda x,g=lambda x,k:(x[k<1::2]in'123456789')&all(j==x[k]for j in x[k::2]):g(x,0)|g(x,1)

```

Try it online!

Explanation:

First split the string into two lists: one with odd-indexed and other with even-indexed elements. The two lists A and B are supposed be such that either:

1. A contains same number and B contains consecutive numbers in ascending order.

OR just the opposite

2. B contains same number and A contains consecutive numbers in ascending order.

The consecutive condition is checked by: `a in '123456789'`

The same-number condition is checked by: `all(i=a[x] for i in a)`
> 2 votes

# Answer
# C (gcc), 123 bytes

```
#define X*s&&*s++-++n&&(r=0)
t,n,x,r;f(char*s){t=*s==s[2];for(r=1,n=s[t],x=s[!t],s+=2;*s;)t||X,*s&&*s++-x&&(r=0),t&&X;n=r;}

```

Try it online!
> 2 votes

# Answer
# PHP, 68 bytes

```
for(;$v<10;)$s.=strstr(+$v.join(+$v,range(1,9)).+$v++,$argn);echo$s;

```

Try it online!

Output part of search string starting from and including the first occurrence of input to the end of search string as truthy value and nothing for falsy

for 2 Bytes more you can replace `echo$s;` with `!!echo$s;` to get `1` as truthy value

Find the occurrence of the input in one of the following strings in the array

```
Array
(
    [0] => 0102030405060708090
    [1] => 1112131415161718191
    [2] => 2122232425262728292
    [3] => 3132333435363738393
    [4] => 4142434445464748494
    [5] => 5152535455565758595
    [6] => 6162636465666768696
    [7] => 7172737475767778797
    [8] => 8182838485868788898
    [9] => 9192939495969798999
)

```
> 2 votes

# Answer
## JavaScript (ES6), 54 bytes

```
f=
s=>[...s].every((e,i)=>i<2|e-s[i-2]==(s[2]!=s[0]^i%2))
```

```
<input oninput=o.textContent=this.value[3]?f(this.value):``><pre id=o>
```

Takes input as a string.
> 2 votes

# Answer
# MATL, 15 bytes

```
2L&),duw]hSFTX=

```

Try it online!

With some help of @LuisMendo in chat. Note that, if empty output + error is also considered 'falsy', the `X` can be left out, bringing the score to **14 bytes**.

```
2L&)     % Split the input into odd and even-indexed elements
    ,   ] % Do twice (new feature since MATL v20.0), i.e., on both halves of the input
     d     % Pairwise differences of the array. Results in [0,0,...] for the 'constant' part,
            %  and [1,1,...] for the 'increasing' part.
      u      % Get unique elements. Results in [0] for the constant part, [1] for the increasing part.
       w      % Swap the stack to do the same for the other half of the input.
         hS    % Horizontal concatenation followed by sort. Results in [0,1] for the desired string.
           FTX= % Check if the result is indeed [0,1]. Implicit display.

```
> 2 votes

# Answer
# Julia, ~~57~~ 56 bytes

```
~s=(!x=occursin(s,join(x*k for k='0':'9')x);!s[1]|!s[2])
```
* replace `||` by `|` by @MarcMush

Attempt This Online!

* input: the number as decimal string
> 2 votes

# Answer
# Python 3, ~~167 161 157 131~~ 106 bytes

*-55 bytes thanks to @WheatWizard's suggestions*

```
def g(t):k,c,f,j=t[::2],t[1::2],'123456789',''.join;return(len({*k})and j(c)in f)or(len({*c})and j(k)in f)

```

Try it online!
> 1 votes

# Answer
# Mathematica, 121 bytes

```
(m[x_]:=Take[s=IntegerDigits@#,{x,Length@s,2}];w[b_,n_]:=Union@Differences@m@b=={1}&&Length@Union@m@n==1;w[1,2]||w[2,1])&

```
> 1 votes

# Answer
# Pyth, 20 bytes

```
ASm.+sMd.Tcz2&-GZ-H1

```

Output `[]` when the number matches the digit pattern, anything else otherwise.

Try it online!

**Explanations** (example with input `85868`)

```
ASm.+sMd.Tcz2&-GZ-H1

          cz2           # Chop the input in pairs: ['85', '86', '8']
        .T              # Transpose, ignore absences: ['888', '56']
     sM                 # Convert to integers: [[8, 8, 8], [5, 6]]
  m.+  d                # Compute deltas: [[0, 0], [1]]
 S                      # Sort: [[0, 0], [1]]
A                       # Assign first list to G and second list to H
              -GZ       # Filter 0 on G (on absence): [0, 0] -> []
                 -H1    # Filter 1 on H (on absence): [1] -> []
             &          # Check both lists are empty (logical and): [] & [] -> []

```
> 1 votes

# Answer
# Pyth, 17 bytes

```
qU2Ssm{.+d.TcjQT2

```

Try it here

Same algorithm as my Jelly answer.

Explanation:

```
qU2Ssm{.+d.TcjQT2 Accepts an integer
             jQT  Take digits of input
            c   2 Split in pairs
          .T      Transpose
     m            Map the following on each of the two resulting lists:
       .+d          Take deltas
      {             Deduplicate
    s             The list is now in [[a, b, ...], [A, B, ...]] format, convert it to [a, b, ..., A, B, ...]
   S              Sort
qU2               Check if equal to [0, 1]

```
> 1 votes

# Answer
# Java (OpenJDK 8), ~~128~~ ~~119~~ ~~118~~ ~~108~~ ~~107~~ 104 bytes

```
s->{int i=3,a=s[2]-s[0],b=s[3]-s[1];for(;++i<s.length;)a+=b-(b=s[i]-s[i-2]==a?a:2);return(a|b)==1&a!=b;}

```

Try it online!

# Explanation:

```
s->{                             // lambda
  int i=3,                       //  iterating index
      a=s[2]-s[0],               //  diff of even-indexed characters
      b=s[3]-s[1];               //  diff of odd-indexed characters
  for(;++i<s.length;)            //  iterate
    a+=b-(b=                     //   swap a and b
        s[i]-s[i-2]==a?a:2       //    or set b to 2 if the diffs don't match
      ));                        //
  return (a|b)==1                //  return true if both a and b are in (0,1)
        &a!=b;                   //         but different
}

```
> 1 votes

# Answer
# Retina, 47 bytes

```
.
$*11;
(1+)(?<=\1;1+;\1)

^1+;1+

^;?(;1;)+;?$

```

Try it online!

Outputs 1 if it matches the pattern, 0 if it does not

### Explanation

```
.
$*11;

```

Convert each digit n to n+1 in unary, separated by semicolons

```
(1+)(?<=\1;1+;\1)

```

(Trailing newline) converts each digit to the difference between itself and the one 2 spots before it

```
^1+;1+

```

(Trailing newline) removes the first 2 digits

```
^;?(;1;)+;?$

```

Counts the number of matches of this pattern, which checks for alternating 0s and 1s
> 1 votes

# Answer
# Husk, 19 bytes

```
S¤|o←Ẋ~&Λȯ¬→-E↔TC2d

```

Try it online!
> 1 votes

# Answer
# Vyxal, 11 bytes

```
y"v¯vUfsk≈⁼

```

Try it Online!
> 1 votes

---
Tags: code-golf, number, sequence
---


title: Equal, sum or difference!

text:
# Question
Title: Equal, sum or difference!
Write shortest possible code that will return true if the two given integer values are equal or their sum or absolute difference is 5.

Example test cases:

```
4 1 => True
10 10 => True
1 3 => False
6 2 => False
1 6 => True
-256 -251 => True
6 1 => True
-5 5 => False

```

The shortest I could come up with in python2 is 56 characters long:

```
x=input();y=input();print all([x-y,x+y-5,abs(x-y)-5])<1

```

-9, thanks @ElPedro. It takes input in format x,y:

```
x,y=input();print all([x-y,x+y-5,abs(x-y)-5])<1

```

# Answer
> 27 votes
# Python 2, 30 bytes

```
lambda a,b:a in(b,5-b,b-5,b+5)

```

Try it online!

One byte saved by Arnauld

Three bytes saved by alephalpha

# Answer
> 20 votes
# JavaScript (ES6), 28 bytes

Takes input as `(a)(b)`. Returns \\$0\\$ or \\$1\\$.

```
a=>b=>a+b==5|!(a-=b)|a*a==25

```

Try it online!

# Answer
> 11 votes
# Dyalog APL, 9 bytes

```
=∨5∊+,∘|-

```

Try it online!

Spelled out:

```
  =   ∨  5      ∊                +   , ∘    |            -
equal or 5 found in an array of sum and absolute of difference.

```

# Answer
> 8 votes
# x86 machine code, 39 bytes

```
00000000: 6a01 5e6a 055f 5251 31c0 39d1 0f44 c601  j.^j._RQ1.9..D..
00000010: d139 cf0f 44c6 595a 29d1 83f9 050f 44c6  .9..D.YZ).....D.
00000020: 83f9 fb0f 44c6 c3                        ....D..

```

# Assembly

```
section .text
	global func
func:					;inputs int32_t ecx and edx
	push 0x1
	pop esi
	push 0x5
	pop edi
	push edx
	push ecx
	xor eax, eax

	;ecx==edx?
	cmp ecx, edx
	cmove eax, esi

	;ecx+edx==5?
	add ecx, edx
	cmp edi, ecx
	cmove eax, esi

	;ecx-edx==5?
	pop ecx
	pop edx
	sub ecx, edx
	cmp ecx, 5

	;ecx-edx==-5?
	cmove eax, esi
	cmp ecx, -5
	cmove eax, esi

	ret

```

Try it online!

Edit: fixed bash stderr errors on TIO

Edit 2: improved formatting in TIO header and footer code

# Answer
> 7 votes
# Jelly, 7 bytes

```
+,ạ5eo=

```

Try it online!

### How it works

```
+,ạ5eo=  Main link. Arguments: x, y (integers)

+        Yield x+y.
  ạ      Yield |x-y|.
 ,       Pair; yield (x+y, |x-y|).
   5e    Test if 5 exists in the pair.
      =  Test x and y for equality.
     o   Logical OR.

```

# Answer
> 6 votes
# Python 2, ~~29~~ 31 bytes

```
lambda a,b:a+b==5or`a-b`in"0-5"

```

Try it online!

Since I didn't manage to read the task carefully the first time, in order to fix it, I had to come up with a completely different approach, which is unfortunately not as concise.

# Answer
> 6 votes
# , 40 bytes (or 34)

```
function(x,y)any((-1:1*5)%in%c(x+y,x-y))

```

Try it online!

For non-R users:

* `-1:1*5` expands to `[-5, 0, 5]`
* the `%in%` operator takes elements from the left and checks (element-wise) if they exist in the vector on the right

A direct port of @ArBo's solution has ~~35~~ 34 bytes, so go upvote that answer if you like it:

```
function(x,y)x%in%c(y--1:1*5,5-y)

```

# Answer
> 5 votes
# , ~~12~~ 11 bytes

*1 byte saved thanks to Adám*

```
1#.=+5=|@-,+

```

Try it online!

## Explanation

This is equivalent to:

```
1 #. = + 5 = |@- , +

```

This can be divided into the following fork chain:

```
(= + (5 e. (|@- , +)))

```

Or, visualized using `5!:4<'f'`:

```
  ┌─ =
  ├─ +
──┤   ┌─ 5
  │   ├─ e.
  └───┤          ┌─ |
      │    ┌─ @ ─┴─ -
      └────┼─ ,
           └─ +

```

Annotated:

```
  ┌─ =                                     equality
  ├─ +                                     added to (boolean or)
──┤   ┌─ 5                                   noun 5
  │   ├─ e.                                  is an element of
  └───┤          ┌─ |  absolute value         |
      │    ┌─ @ ─┴─ -  (of) subtraction       |
      └────┼─ ,        paired with            |
           └─ +        addition               | any of these?

```

# Answer
> 4 votes
# Python 2, 38 bytes

-2 bytes thanks to @DjMcMayhem

```
lambda a,b:a+b==5or abs(a-b)==5or a==b

```

Try it online!

# Answer
> 4 votes
# PowerShell, ~~48~~ ~~44~~ 40 bytes

```
param($a,$b)$b-in($a-5),(5-$a),(5+$a),$a

```

Try it online! or Verify all Test Cases

Takes input `$a` and `$b`. Checks if `$b` is `-in` the group (`$a-5`, `5-$a` `5+$a`, or `$a`), which checks all possible combinations of `$a`,`$b`, and `5`.

*-4 bytes thanks to mazzy.*
*-4 bytes thanks to KGlasier.*

# Answer
> 4 votes
# Wolfram Language (Mathematica), 22 bytes

Takes input as `[a][b]`.

```
MatchQ[#|5-#|#-5|#+5]&

```

Try it online!

# Answer
> 4 votes
# Java (JDK), 30 bytes

```
a->b->a+b==5|a==b|(b-=a)*b==25

```

Try it online!

# Answer
> 4 votes
# Perl 6, 24 bytes

*-1 byte thanks to Grimy*

```
{$^a-$^b==5|0|-5|5-2*$b}

```

Try it online!

This uses the Any Junction but technically, `^` could work as well.

### Explanation:

```
{                      }  # Anonymous code block
 $^a-$^b==                # Is the difference equal to
           | |  |        # Any of
          0
            5
              -5
                 5-2*$b

```

# Answer
> 4 votes
# x86-16 machine code, ~~21~~ 20 bytes

```
00000000: 8bd0 2bc3 740d 7902 f7d8 3c05 7405 03d3  ..+.t.y...<.t...
00000010: 80fa 05c3                                ....

```

Listing:

```
8B D0       MOV  DX, AX     ; Save AX to DX
2B C3       SUB  AX, BX     ; AX = AX - BX
74 0D       JZ   DONE       ; if 0, they are equal (ZF=1)
79 02       JNS  IS_POS     ; if positive, check if result is 5
F7 D8       NEG  AX         ; is negative, negate the result to get abs value
        IS_POS:
3C 05       CMP  AL, 5      ; is result 5?
74 05       JZ   DONE       ; if so, exit with ZF=1
03 D3       ADD  DX, BX     ; DX = DX + BX
80 FA 05    CMP  DL, 5      ; ZF = ( DX == 5 )
        DONE:
C3          RET             ; return to caller

```

Input numbers in `AX` and `BX` and returns Zero Flag (`ZF`) if result is truthy.

Try it online! (testing code borrowed and adapted from @Logem's answer \- thanks!)

*Explanation:*

If the difference between the numbers is 0, they are equal. Otherwise if result is negative, first negate it (abs value) and check for 5. If still not true, add and check for 5.

*Bonus:*

If desired, you can also determine which condition was true with the following:

* `ZF` = `1` and `DX` = `5` ; sum is 5
* `ZF` = `1` and `AX` = `5` ; diff is 5
* `ZF` = `1` and `AX` = `0` ; equal
* `ZF` = `0` ; falsey

# Answer
> 4 votes
# Pascal (FPC), ~~26~~ 70 bytes

**Edit:** \+ input variables.

```
Procedure z(a,b:integer);begin Writeln((abs(a-b)in[0,5])or(a+b=5))end;

```

Try it online!

---

```
(abs(a-b)in[0,5])or(a+b=5)

```

Try it online!

I hope that my answer is according to all rules of code-golf. It was fun anyway.

# Answer
> 3 votes
# C# (.NET Core), ~~43~~, ~~48~~, ~~47~~, 33 bytes

EDIT: Tried to use % and apparently forgot how to %. Thanks to Arnauld for pointing that out!

EDIT2: AdmBorkBork with a -1 byte golf rearranging the parentheses to sit next to the return so no additional space is needed!

EDIT3: Thanks to dana for -14 byte golf for the one-line return shortcut and currying the function (Ty Embodiment of Ignorance for linking to TIO).

# C# (.NET Core), 33 bytes

```
a=>b=>a==b|a+b==5|(a-b)*(a-b)==25

```

Try it online!

# Answer
> 3 votes
# Scala, 43 bytes

```
def f(a:Int,b:Int)=a+b==5|(a-b).abs==5|a==b

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 10 bytes

```
OIÆ‚Ä50SåZ

```

Try it online!

---

```
O           # Sum the input.
 IÆ         # Reduced subtraction of the input.
   ‚        # Wrap [sum,reduced_subtraction]
    Ä       # abs[sum,red_sub]
     50S    # [5,0]
        å   # [5,0] in abs[sum,red_sub]?
         Z  # Max of result, 0 is false, 1 is true.

```

Tried to do it using stack-only operations, but it was longer.

# Answer
> 3 votes
# C (gcc), 33 bytes

```
f(a,b){a=!(a+b-5&&(a-=b)/6|a%5);}

```

Try it online!

Tried an approach I didn't see anyone else try using. The return expression is equivalent to `a+b==5||((-6<a-b||a-b<6)&&(a-b)%5==0)`.

---

# Answer
> 3 votes
# Brachylog, 8 bytes

```
=|+5|-ȧ5

```

Takes input as a list of two numbers (use `_` for negatives). Try it online!

### Explanation

Pretty much a direct translation of the spec:

```
=          The two numbers are equal
 |         or
  +        The sum of the two numbers
   5       is 5
    |      or
     -     The difference of the two numbers
      ȧ    absolute value
       5   is 5

```

# Answer
> 2 votes
# C (gcc), ~~41~~ 34 bytes

```
f(a,b){a=5==abs(a-b)|a+b==5|a==b;}

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~13~~ 12 bytes

```
ÐO5Qs`α5QrËO

```

Try it online!

Takes input as a list of integers, saving one byte. Thanks @Wisław!

# Alternate 12 byte answer

```
Q¹²α5Q¹²+5QO

```

Try it online!

This one takes input on separate lines.

# Answer
> 2 votes
## Ruby, 34 Bytes

```
->(a,b){[a+5,a-5,5-a,a].include?b}

```

Online Eval \- Thanks @ASCII-Only

# Answer
> 2 votes
# Factor, ~~44~~ 40 bytes

Saved 4 bytes thanks to @chunes!

```
[ { [ = ] [ - abs 5 = ] [ + 5 = ] } || ]

```

Try it online!

The repetition of `=` is annoying, but I couldn't find another way.

`||` tries out each of the three quotations in `{...}` and checks if the result is true for any of them. The first, `[ = ]`, checks if they're equal, the second finds the absolute value of their difference and compares that to 5, and the third compares their sum to 5.

# Answer
> 1 votes
# Japt, ~~14~~ 13 bytes

```
¥VªaU ¥5ª5¥Nx

```

Try it online!

# Answer
> 1 votes
# Tcl, 53 bytes

```
proc P a\ b {expr abs($a-$b)==5|$a==$b|abs($a+$b)==5}

```

Try it online!

# Answer
> 1 votes
# Japt, ~~13~~ 12 bytes

```
x ¥5|50ìøUra

```

Try it or run all test cases

```
x ¥5|50ìøUra
                 :Implicit input of array U
x                :Reduce by addition
  ¥5             :Equal to 5?
    |            :Bitwise OR
     50ì         :Split 50 to an array of digits
        ø        :Contains?
         Ur      :  Reduce U
           a     :    By absolute difference

```

# Answer
> 1 votes
## Batch, 81 bytes

```
@set/as=%1+%2,d=%1-%2
@if %d% neq 0 if %d:-=% neq 5 if %s% neq 5 exit/b
@echo 1

```

Takes input as command-line arguments and outputs 1 on success, nothing on failure. Batch can't easily do disjunctions so I use De Morgan's laws to turn it into a conjunction.

# Answer
> 1 votes
# Charcoal, 18 bytes

```
Ｎθ¿№⟦θ⁺⁵θ⁻⁵θ⁻θ⁵⟧Ｎ1

```

Try it online! Link is to verbose version of code. Port of @ArBo's Python 2 solution.

# Answer
> 1 votes
# Retina 0.8.2, 82 bytes

```
\d+
$*
^(-?1*) \1$|^(-?1*)1{5} -?\2$|^-?(-?1*) (\3)1{5}$|^-?(1 ?){5}$|^(1 ?-?){5}$

```

Try it online! Link includes test cases. Explanation: The first two lines convert the inputs into unary. The final line then checks for any of the permitted matches:

```
^(-?1*) \1$                              x==y
^(-?1*)1{5} -?\2$   x>=0 y>=0 x=5+y i.e. x-y=5
                    x>=0 y<=0 x=5-y i.e. x+y=5
                    x<=0 y<=0 x=y-5 i.e. y-x=5
^-?(-?1*) (\3)1{5}$ x<=0 y<=0 y=x-5 i.e. x-y=5
                    x<=0 y>=0 y=5-x i.e. x+y=5
                    x>=0 y>=0 y=5+x i.e. y-x=5
^-?(1 ?){5}$        x>=0 y>=0 y=5-x i.e. x+y=5
                    x<=0 y>=0 y=5+x i.e. y-x=5
^(1 ?-?){5}$        x>=0 y>=0 x=5-y i.e. x+y=5
                    x>=0 y<=0 x=5+y i.e. x-y=5

```

Pivoted by the last column we get:

```
x==y            ^(-?1*) \1$
x+y=5 x>=0 y>=0 ^-?(1 ?){5}$
      x>=0 y>=0 ^(1 ?-?){5}$
      x>=0 y<=0 ^(-?1*)1{5} -?\2$
      x<=0 y>=0 ^-?(-?1*) (\3)1{5}$
      x<=0 y<=0 (impossible)
x-y=5 x>=0 y>=0 ^(-?1*)1{5} -?\2$
      x>=0 y<=0 ^(1 ?-?){5}$
      x<=0 y>=0 (impossible)
      x<=0 y<=0 ^-?(-?1*) (\3)1{5}$
y-x=5 x>=0 y>=0 ^-?(-?1*) (\3)1{5}$
      x>=0 y<=0 (impossible)
      x<=0 y>=0 ^-?(1 ?){5}$
      x<=0 y<=0 ^(-?1*)1{5} -?\2$

```

# Answer
> 1 votes
## Common Lisp, 48 bytes

```
(lambda(a b)(find 5(list(abs(- b a))a(+ a b)b)))

```

# Answer
> 1 votes
# Desmos, 90 bytes

A pretty straightfoward solution, could definitely by golfed further:

```
f(a,b)=\left\{a+b=5:0,1\right\}\left\{\left|a-b\right|=5:0,1\right\}\left\{a=b:0,1\right\}

```

Try It On Desmos!

0 is true, and 1 is false.

# Answer
> 1 votes
# Pyth, 12 bytes

```
}5[sQaFQ+4l{

```

Try it online!

```
}5[sQaFQ+4l{
}5[sQaFQ+4l{Q) // Implicit input and closed brace
  [          ) // Create an array of the following:
   sQ          //   Sum of input
     aFQ       //   Absolute difference of input
        +4l{Q  //   Length of unique values in input, + 4
}5             // Is '5' in the array?

```

# Answer
> 1 votes
# Vyxal, ~~11~~ 10 bytes

```
=£₌+ĸW5c¥∨

```

Try it Online!

### Credits

* Saved 1 byte thanks to @Lyxal by employing the use of an absolute difference built-in

# Answer
> 1 votes
# Pyth, 15 bytes

```
|!!/,a.*QsQ5q.*

```

Try it online!

Not super impressed, especially having to use double negation `!!` to cast a number into `true`... I'm sure there's a better way.

```
|!!/,a.*QsQ5q.*
   /,      5     Count '5's in:
     a.*Q        Absolute value of (A, B)
         sQ      Sum of (A, B)
 !!              Cast to truthy
|                OR:
            q.*  A==B

```

# Answer
> 1 votes
# Factor, 37 bytes

```
[ 2dup + 5 = -rot - abs "\0"in? or ]

```

Try it online!

## Explanation

`"\0"` Has literal `0` and `5` embedded in the string (you can see it on TIO). So `"\0"in?` is equivalent to `{ 0 5 } member?` In other words, checking whether the input is 0 or 5.

```
          ! -256 -251
2dup      ! -256 -251 -256 -251
+         ! -256 -251 -507
5         ! -256 -251 -507 5
=         ! -256 -251 f
-rot      ! f -256 -251
-         ! f -5
abs       ! f 5
"\0"in?   ! f t
or        ! t

```

# Answer
> 1 votes
# \*\>\<\>, 33 bytes

```
:{:}=?;:{:}+5=?;-:0(?!u01-*O5=?;.

```

Try it online!

Could be lower if handling negative numbers wasn't a requirement. Uses the exit code as its truthy/falsey.

Initializes the stack with the `-i` flag, but this method can't handle negatives. The above code still works, but you must prepend your starting values to the start of the script. For example, the following works with the stack of `[-15, 12]`

```
53*0-c:{:}=?;:{:}+5=?;-:0(?!u01-*O5=?;.

```

## Explanation

```
:{:}                                Duplicate the two values on the stack
    =?;                             If they're equal, halt execution
       :{:}                         Duplicate the two values on the stack, again
           +                        Add them together
            5=                      Check if that value is equal to 5
              ?;                    If so, halt execution
                -:                  Else, subtract our two values, and duplicate the result
                  0(                Check if the difference is less than 0
                    ?!u             If it is greater than 0, Dive and ignore instructions until we reach a Rise
                       01-*         If it isn't, multiply it by -1
                            O       Rise from our previous Dive. Ignored if there was no Dive.
                             5=     Check if our difference is equal to 5
                               ?;   If so, halt execution
                                 .  Else, throw an error

```

# Answer
> 0 votes
# Runic Enchantments, 27 bytes

```
i::i::}3s=?!@-'|A5:}=?!@+=@

```

Try it online!

Outputs `0` (exactly one zero) for false and any other output (literally whatever is left on the stack) for true.

New interpreter build, updated answer, saved 3 bytes (previous revision miscounted and said 4).

### Explanation:

```
i::i::                         Read two inputs, duplicating each twice.
      }                        Rotate stack right
       3s                      Rotate the top 3 items to the right
         =? @                  Compare equal, if so, dump stack
           !                   If not, skip next instruction
             -'|A              Subtract, absolute value, (j)
                 5:}           Push two 5s, rotate one to the bottom
                    =? @       Compare 5 with (j), if equal, dump stack
                      ! +=     If not, add the two inputs, compare with remaining 5
                          @    Dump stack (will be 1 for true and 0 for false)

```

Essentially it reads both inputs 3 times and arranges the stack so that each operation works on a copy of each input (or a literal `5`). As the only way to dump a `0` is if all three comparisons are false, simply dumping the rest of the stack avoids having to do anything other than vomiting the entire stack to output and terminating, all posibilities of which are valid truthy values.

# Answer
> 0 votes
# Perl 5, 51 bytes

Pretty simple really, uses the `an` flags for input. Outputs 0 for false, 1 for true. Not gonna lie, I don't know if bitwise OR is appropriate here, but is does work for all the test cases, so that's nice.

```
($a,$b)=@F;print($a==$b|$a+$b==5|$a-$b==5|$b-$a==5)

```

Try it online!

# Answer
> 0 votes
# Julia 1.0, 38 bytes

```
f(a,b)=((a+b-5)*(a-b)*(abs(a-b)-5))==0

```

Try it online!

Of course, it's probably not the shortest one

# Answer
> 0 votes
# APL(NARS) 19 chars, 38 bytes

```
{∨/(⍺=⍵),5∊∣⍺+⍵,-⍵}

  f←{∨/(⍺=⍵),5∊∣⍺+⍵,-⍵}
  4 f 1
1
  1 f 3
0
  6 f 2
0
  1 f 6
1
  ¯256 f ¯251
1
  6 f 1
1
  ¯5 f 5
0

```

# Answer
> 0 votes
# Ruby (\>=1.9), ~~23~~ 38 bytes

```
->(a,b){a==b or a+b==5 or(a-b).abs==5}

```

Try it online!

It's an anonymous function, so the TIO has some extra code to take input and return the output. Put the two numbers on separate lines.

Returns `true` if they are equal or add to 5, or if their absolute difference is 5, and `false` if not.

# Answer
> 0 votes
# Haskell, 30 Bytes

```
a?b=elem 5[a-b+5,abs(a-b),a+b]

```

# Answer
> 0 votes
# Vyxal, 8 bytes

```
₍+ε5c□≈∨

```

Try it Online!

---
Tags: code-golf, decision-problem
---


title: Swep tha vowels!

text:
# Question
Title: Swep tha vowels!
Note: the title was misspelled intentionally.

Given a string s, swap the first vowel runs of every 2 words. For this challenge, y is considered a vowel.

For example, given an input of "great day sir":

```
1. Input: "great day sir"
2. Identify pairs of words: "[great day] [sir]" (No word for sir to pair with)
3. Identify the first vowel runs in each word: "[gr[ea]t d[ay]] [s[i]r]"
4. Swap the vowel runs in each pair: "[gr[ay]t d[ea]] [s[i]r]"
5. Return/print: "grayt dea sir"

```

When there are vowel runs of different lengths, you still swap the whole runs. When a word has more than one vowel runs, you still only swap the first one. When the first or second word of a pair of words does not have a vowel, then you do not swap the vowels for those words.

You may assume that the input only consists of one case of alphabetic letters and the literal space or another constant delimiter.

Standard methods of I/O, standard loopholes apply. Leading/trailing whatevers are okay.

**Test cases:**

```
Input -> Output

"great day sir" -> "grayt dea sir"
"ppcg is the best" -> "ppcg is the best" (When there is no vowel to swap, don't swap vowels."
"this is a test case" -> "this is e tast case"
"loooooooooooooong word" -> "long woooooooooooooord"
"great night" -> "grit neaght"
"anything goes" -> "oenything gas"
"qwrtpsdfghjklzxcvbnm aaaaaaaa hi there" -> "qwrtpsdfghjklzxcvbnm aaaaaaaa he thire"
"this is a long test case in case you could not tell" -> "this is o lang tast cese an cise ou cyould net toll"

```

# Answer
> 9 votes
# , ~~42~~, 41 bytes

```
ò2Eá
òÍ¨[aeiouy]«©¨ƒ ƒ©¨[aeiouy]«©/³²±
Íî

```

Try it online!

Hexdump:

```
00000000: f232 45e1 0af2 cda8 5b61 6569 6f75 795d  .2E.....[aeiouy]
00000010: aba9 a883 2083 a9a8 5b61 6569 6f75 795d  .... ...[aeiouy]
00000020: aba9 2fb3 b2b1 0acd ee                   ../......

```

Explanation:

```
ò       ò                                   " Recursively:
 2E                                         "   Move to the end of two words forward
   á<cr>                                    "   And append a newline

```

This will put all groups of two words on their own line, for example:

```
this is
a long
test case
in case
you could
not tell

```

Now we run some fancy regex-magic:

```
Í                                           " Globally substitute
 ¨[aeiouy]«©                                "   A vowel (capture group 1)
            ¨<131>                          "   Followed by as few characters as possible, then a space
                   <131>©                   "   Followed by as few characters as possible (capture group 2)
                         ¨[aeiouy]«©        "   Followed by a vowel again
                                    /       " With:
                                     ³²±    "   Capture groups '3', '2', '1'
Í                                           " Remove all:
 î                                          "   Newlines

```

# Answer
> 6 votes
# Japt, ~~39~~ 37 bytes

They said it would be ugly, but I didn't listen... and it was:

```
¸ò ®efQ="%y+" ?Z£XrQZg°T fQP PÃ:ZÃc ¸

```

Test it online!

### Explanation

```
 ¸  ò ® efQ="%y+" ?Z£    XrQ    Zg° T fQ    P PÃ :ZÃ c ¸
UqS ò mZ{Zef"%y+" ?ZmXYZ{Xr"%y+"Zg++T f"%y+"P P} :Z} c qS
             Implicit: U = input string, such as     "abc def ghi jkl mno"
UqS          Split on spaces, splitting into words.  ["abc","def","ghi","jkl","mno"]
ò            Group into runs of two items.           [["abc","def"],["ghi","jkl"],["mno"]]
mZ{          For each pair Z:
 Zef"%y+"?     If not every item contains a run of vowels (%y = [AEIOUYaeiouy]),
 :Z            return Z.                             [              ["ghi","jkl"]        ]
 ZmXYZ{        Otherwise, for each item X in Z:
  Xr"%y+"        Replace each run of vowels with
  Zg++T           the item at the next index in Z,   [["def","abc"]               ["mno"]]
  f"%y+"P         but only the first run of vowels.  [["e",  "a"  ]               ["o"  ]]
  P              Replace only for the first match.   [["ebc","daf"]               ["mno"]]
 }
}                                                    [["ebc","daf"],["ghi","jkl"],"mno"]]
c            Flatten back into a single array.       ["ebc","def","ghi","jkl","mno"]
qS           Re-join on spaces.                      "ebc daf ghi jkl mno"
             Implicit: output result of last expression

```

# Answer
> 5 votes
# JavaScript (ES6), ~~62~~ ~~106~~ ~~98~~ 101 bytes

```
s=>s.match(/(\w+)( (\w+))?/g).map(m=>m.replace(/([aeiouy]+)(\w* \w*?)([aeiouy]+)/g,'$3$2$1')).join` `

```

```
f=
s=>s.match(/(\w+)( (\w+))?/g).map(m=>m.replace(/([aeiouy]+)(\w* \w*?)([aeiouy]+)/g,'$3$2$1')).join` `
;

[
  "great day sir",
  "ppcg is the best",
  "this is a test case",
  "loooooooooooooong word",
  "great night",
  "anything goes",
  "qwrtpsdfghjklzxcvbnm aaaaaaaa hi there",
].map(f).map(s=>console.log(s))
```

# Answer
> 4 votes
# Retina, 65 bytes

```
((\w*?)([aeiouy]+)(\w* \w*?)([aeiouy]+)|(\w+ ))(\w*)
$2$5$4$3$6$7

```

Try it online! Includes test cases. I wanted to use a conditional group reference but I couldn't get it to work in 66 bytes let alone 65 or less.

# Answer
> 4 votes
# Retina, 50 bytes

```
\S+ \S+
$&¶
%O$^`(?<=\b[^aeiouy]*)[aeiouy]+
$`
¶

```

Try it online!

−2 bytes thanks to Martin.

* First step is splitting each word pair to its own line ( is newline). This allows us to use `.*` within a pair of words.
* Next, for each line we find the first vowel block in each word, and sort them by position in descending order.

# Answer
> 3 votes
# Python 2, 148 bytes

```
from re import*
v="([aeiouy]+)"
print sub(r"(\w+)(?: (\w+))?",lambda m:sub(v+"(.* .*?)"+v,lambda g:''.join(g.groups()[::-1]),m.group()),raw_input())

```

Try it online!

Code Golfing is getting addictive!

> Sections off pairs of words, then grabs the 2 groups of vowels and the string in between, reverses the order and uses that as the substitute.

# Answer
> 3 votes
## Perl, 58 bytes

**57 bytes code + 1 for `-p`.**

```
$v="([aeiouy]+)";s!\w+ \w+!$&=~s/$v(.* .*?)$v/$3$2$1/r!ge

```

-2 bytes thanks to @Dada!

Try it online!

# Answer
> 3 votes
# Haskell, 177 173 171 169 bytes

```
unwords.s.words
s(x:y:z)=maybe[x,y]id(do(a,b)<-k x;(c,d)<-k y;j[b c,d a])++s z
s x=x
v=(`elem`"aeiouy")
j=Just
k s=do(a,(x:y,r))<-j$span v<$>break v s;j(x:y,\n->a++n++r)

```

Try it online!

This is a direct shortening of the following naïve solution, so there should something much better around here:

```
swapvowels :: String -> String
swapvowels = unwords . swapPairs . words

swapPairs :: [String] -> [String]
swapPairs (word1:word2:rest) =
   case (,) <$> extractVowels word1 <*> extractVowels word2 of
     Just ((vowels1, rebuild1), (vowels2, rebuild2))
       -> [rebuild1 vowels2, rebuild2 vowels1] ++ swapPairs rest
     Nothing -> [word1,word2] ++ swapPairs rest
swapPairs rest = rest

extractVowels :: String -> Maybe (String, String -> String)
extractVowels s = do
    let isVowel l = l `elem` "aeiouy"
    (a,b) <- Just $ break isVowel s
    (w@(_:_),r) <- Just $ span isVowel b
    return (w, \n -> a ++ n ++ r)

```

# Answer
> 2 votes
# Java (OpenJDK 8), ~~363~~ 304+25 bytes

*-34 bytes thanks to @KevinCruijssen*

Golfed:

```
l->{String s[]=l.split(" "),a,b;Pattern p=Pattern.compile("[aeiouy]+");for(int i=0;i<s.length-1;i+=2){Matcher m=p.matcher(s[i]),n=p.matcher(s[i+1]);a=m.find()?m.group():null;b=n.find()?n.group():null;if(a!=null&b!=null){s[i]=s[i].replaceFirst(a,b);s[i+1]=s[i+1].replaceFirst(b,a);}}return l.join(" ",s);}

```

Try it online!

Ungolfed:

```
String swapVowels(String line) {
    String[] parts = line.split(" ");
    Pattern pattern = Pattern.compile("([aeiouy]+)");
    for (int i = 0; i < parts.length - 1; i += 2) {
        Matcher matcherL = pattern.matcher(parts[i]), matcherR = pattern.matcher(parts[i + 1]);
        String vowelRunL = matcherL.find() ? matcherL.group() : null, vowelRunR = matcherR.find() ? matcherR.group() : null;
        if (vowelRunL != null & vowelRunR != null) {
            parts[i] = parts[i].replaceFirst(vowelRunL, vowelRunR);
            parts[i + 1] = parts[i + 1].replaceFirst(vowelRunR, vowelRunL);
        }
    }
    return String.join(" ", parts);
}

```

# Answer
> 2 votes
# Ruby, 87+1 = 88 bytes

Uses the `-p` flag.

```
gsub(/(\w+) (\w+)/){_,a,b=*$~;a[r=/[aeiouy]+/]&&b[r]?a.sub(r,b[r])+' '+b.sub(r,a[r]):_}

```

Try it online!

# Answer
> 1 votes
# Python 3, 198 196 192 bytes

* Saved 6 bytes: thanks to Zachary T: `if(m and n)` to if m and n & removed unwanted r for regex string, index i starting from 1 instead of 0

```
from re import*
s=search
a=input().split()
v="[aeiouy]+"
j=1
while j<len(a):
 i=j-1;m=s(v,a[j]);n=s(v,a[i])
 if m and n:a[i]=sub(v,m[0],a[i],1);a[j]=sub(v,n[0],a[j],1)
 j+=2
print(' '.join(a))

```

Try it online!

# Answer
> 0 votes
# Vyxal `S`, 33 bytes

```
⌈2ẇƛƛ≬k∪$cḊ:‡hAǑ";:vƒiṘ¨vJƛ÷Ȧṅ;;f

```

Try it Online!

Really really bad, I couldn't find a single good piece of this code

---
Tags: code-golf, string, parsing
---


title: Reversing and Shifting

text:
# Question
Title: Reversing and Shifting
Sandbox

*Adapted from exercise 8 of 100 little Keg exercises*

String manipulation is a very important part of any programming language. Consequently, that is what this challenge is about.

## The Challenge

I want you to write a program that:

* Takes a series of characters as input and,
* Then takes another input (integer/letter) (we'll call this `instruction`) and,
* Takes a single integer (we'll call this `times`) as the last input and then,
* If `instruction` is equal to the letter `R`:
    + Reverse the string `times` times.
* Otherwise, if `instruction` is equal to the letter `l`:
    + Shift the string left `times` times
* Otherwise, for all other values of `instruction`:
    + Shift the string right `times` times

## Test Cases

```
String, Instruction, Times -> Output
"Howdy!", R, 1 -> "!ydwoH"
"elloH", r, 1 -> "Hello"
"tedShif", l, 3 -> "Shifted"
"sn't it?Amazing, i", l, 8 -> "Amazing, isn't it?"

```

## Rules

* Input can be taken as *any* convenient format... if a list of three items works best for you, take the input as a list. If newline-separated input is how you choose to work, go ahead and use newline-separated input.
* The string, instruction and times integer can be taken in any order
* Output is also to be given in any convenient format.
* The input string will *not* contain newlines, nor unprintable ascii characters.
* You can substitute `R` and `l` for any other two characters, as long as you specify what the two characters are
* All instructions are case sensitive. In other words, only input of `R` should reverse the string, not `r`.
* The magnitude of a shift will always be less than the length of the string
* The `times` integer is a positive integer (i.e. \\$ n \> 0 \\$)

## Scoring

This is , so the answer with the fewest bytes wins.

# Answer
# Python 3.8 (pre-release), 65 bytes

```
lambda s,i,t:[s[(n:=[-t,t][i=='l']):]+s[:n],s[::(-1)**t]][i=='R']

```

Try it online!

Abuses the de-facto ternary statement `[a,b][condition]`.

* If `i=='R'`:
    + Return the string, read with step `(-1)**t`. This is `-1` (reversed) for odd `t` and `1` (not reversed) for even `t`.
* Else:
    + Let `n` be `[-t,t][i=='l']`. This is `t` when left-shifting and `-t` otherwise (right-shifting).
    + Return the string, spliced accordingly: `s[n:] + s[:n]`. Thanks to Python's negative indexing, this works like a charm for both cases.
> 6 votes

# Answer
# APL (Dyalog Unicode), 20 bytesSBCS

Full program. Prompts for the string, then `times`, then `instruction`:

* `+` for reversal
* `1` for left shift
* any other character for right shift

```
(⍎⍕⊃¯1,⍨⍞∩'+1')⌽⍣⎕⊢⍞

```

Try it online!

prompt for string

on that, do the following:

prompt for `times`

`(``)⌽⍣` apply the  function that many times, with the following to its left:

`∩'+1'` intersection of the following and `"+1"`:

prompt for `instruction`

`¯1,⍨` append negative one

pick the first one

stringify

evaluate (gives `1` or `-1` or the complex conjugate function `+`)

The function  does a:

* left shift if it has `1` on its left
* right shift if it has `-1` on its left
* reversal if it has any function on its left

`+` negates the imaginary part of its argument but strings have no imaginary parts, so it does nothing
> 6 votes

# Answer
# Python 2, 67 bytes

```
lambda s,t,i:[s[t:]+s[:t],s[::1-t%2*2],s[-t:]+s[:-t]]['lR'.find(i)]

```

Try it online!
> 3 votes

# Answer
# Ruby, 63 bytes

```
->s,c,n{c==?R?[s,s.reverse][n%2]:s.chars.rotate(c==?l?n:-n)*''}

```

Try it online!

An anonymous lambda that takes 3 arguments. If the instruction is `R`, it returns the original or the reversed version based on whether `n` is even or odd. Otherwise, it converts the string into a character array and `rotate`s that left or right based on the instruction specified (Ruby rotates left if the argument provided is positive) the joins the char array back together into a string using `*''`.
> 3 votes

# Answer
# 05AB1E, 16 bytes

```
²³F1¹QiRë0¹QiÀëÁ

```

Try it online!

`1` instead of `R`, `0` instead of `l`.

I'm new to this language, would appreciate if anyone could give me tips.

```
²³F1¹QiRë0¹QiÀëÁ
²³               # Push the second and third inputs.
  F              # Do the following [third input] times:
   1¹Qi          # If the first input is equal to 1,
       R         # Reverse (at this point, the second input will be at the top of the stack).
        ë0¹Qi    # Else-if the first input is equal to 0,
             À   # Shift left.
              ëÁ # Else shift right.

```
> 3 votes

# Answer
# C (clang), 72 bytes

```
j;f(char*s,z,i,t){for(j=0;j<z;++j)putchar(s[i?(z+t*i+j)%z:t%2?z+~j:j]);}

```

Try it online!

Input as: char\* , length, instruction(r=-1 , R=0 , l =1), times

Loop into input string using a shifted index with modulo `i?(z+t*i+j)%z` or a `length - index -1` for reverse
> 2 votes

# Answer
# Burlesque, 32 bytes

```
pe{{so}{<-}{SO}{rt}{1}{RT}}cnjE!

```

Try it online!

Takes arguments as: `"StringToMod" N "Op"` Where op is a reverse ordered string for reverse, a string in order for rotate right and anything else for rotate left, other short options or `op` could be space character, alpha character, other. If those are unacceptable input add 4 bytes for `{'R==}` & `{'r==}` as conditions.

```
pe         # Push inputs to stack
{
 {so} {<-} # If sorted push reverse
 {SO} {rt} # If reverse-sorted push rotate right
 {1}  {RT} # Else push rotate left
}cn        # Condition on op
jE!        # Evaluate N times

```
> 2 votes

# Answer
# Jelly, 18 bytes

```
Ḣ⁾lRi‘ịUṛ¡ṭṙN,$}¥ɗ

```

Try it online!

A dyadic link taking a Jelly string prepended with the instruction as its left argument (e.g. `RHello world`) and the integer as its right argument. Returns a Jely string.
> 1 votes

# Answer
# Charcoal, ~~27~~ 25 bytes

```
≔×⌕RrηＩζδＦ×¬δＩζ≦⮌θ⭆θ§θ⁻κδ

```

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

```
≔×⌕RrηＩζζ

```

Convert the third input to integer, then multiply it by the index of the second input in `Rr`. This leaves it zero if the second input is `R` and unchanged if it is `r` but it negates the third input if the second input is anything else.

```
Ｆ×¬δＩζ≦⮌θ

```

If the third input is now zero then reverse the first input the original number of times.

```
⭆θ§θ⁻κζ

```

Shift the first input rightwards by the third input.
> 1 votes

# Answer
# Pyth, 38 bytes

```
J.zKs@J2A<J2?qHd_FGK?qHN+>GK<GK+>KG<KG

```

Try it online!

This is a quite naive strategy but it works ¯\\\_(ツ)\_/¯

Input is taken on three lines: the first is the input, second is the operation, third is the count.

Substitute `R` for  (space). Substitute `l` for `"` (double quote).
> 1 votes

# Answer
# JavaScript (Node.js), 74 bytes

```
i=>n=>g=a=>n--?g(a.map((_,p)=>a[(i-1?i-2?L+p-1:p+1:L+~p)%L],L=a.length)):a

```

Try it online!

Input `i` (instruction, 1 = Reverse, 2 = Left, 3 = Right), `n` (times), `a` (array of characters).

Output array of characters.
> 1 votes

# Answer
# Vyxal `D`, 11 bytes

```
:[‛ǔǓiĖ|_(Ṙ

```

Try it Online!

Uses `0` for reverse, `1` for shift left, and `2` for shift right.
> 0 votes

---
Tags: code-golf, string
---