Editor

Four in a Row

#331 · Games and puzzles · Intermediate · 80 XP · about 18 min

Two players drop discs into an upright board with 7 columns, numbered 0 to 6 from the left, and 6 rows. A disc dropped into a column falls to the lowest empty square of that column. Player 'X' moves first, then 'O', and they keep taking turns.

A player wins as soon as four of their discs line up in a straight line: across, up and down, or diagonally in either direction. The game ends right there, and any moves still left in the list are ignored.

Write four_in_a_row(moves), where moves is the list of columns in the order the discs were dropped. Return a tuple (winner, move): the winning player and the number of the move that won (the first move is number 1). If nobody has four in a row after all the moves, return ('nobody', len(moves)).

Examples

four_in_a_row([3, 3, 4, 4, 5, 5, 6])      # returns ('X', 7)
four_in_a_row([0, 1, 0, 1, 0, 1, 6, 1])   # returns ('O', 8)
four_in_a_row([0, 1, 2, 3])               # returns ('nobody', 4)

In the first game X fills the bottom row from column 3 to column 6 with the seventh move. In the second, O stacks four discs in column 1 with the eighth.

Constraints

  • moves has 0 to 100 items, each from 0 to 6.
  • Every move before the game ends goes into a column that still has room. Moves after a win might not, which does not matter because they are ignored.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.