Google questions

Babylon Stacking Game

GoogleOnsiteMedium

Two players play a game with colored tiles. BabylonGame(tiles) takes a string with one letter per tile, such as "YYYWWWGGGBBB": twelve tiles in four colors. Every tile starts as its own stack of height 1, and the stacks are numbered from 0 in the order of the string.

The players alternate, and player 0 moves first. A move puts the whole stack source on top of a different stack target. It is legal when the two stacks have the same height or the same top color. The merged stack has the sum of the two heights and the top color of the stack that was moved. It takes the place of target in the list, and source is removed, so every stack after source gets an index one lower. A player with no legal move on their turn loses.

Part 1: Play the game

Implement:

  • legal_moves() returns every legal move for the current stacks as [source, target], ordered by source and then target.
  • play(source, target) makes the move for the current player and returns true. If the move is not legal, including an index outside the list or source == target, it returns false and changes nothing, and the turn stays with the same player.
  • state() returns the stacks in index order, each as [height, top_color], with the color as a one-letter string.
  • current_player() returns 0 or 1.
  • winner() returns -1 while the current player has a legal move. Otherwise the game is over and it returns the other player.
  1. Example 1
    init
    ["YWYG"]
    operations
    [["legal_moves",[]],["play",[0,2]],["state",[]],["current_player",[]],["legal_moves",[]],["play",[0,1]],["play",[1,0]],["play",[2,0]],["state",[]],["winner",[]],["current_player",[]],["legal_moves",[]]]
    Output
    [[[0,1],[0,2],[0,3],[1,0],[1,2],[1,3],[2,0],[2,1],[2,3],[3,0],[3,1],[3,2]],true,[[1,"W"],[2,"Y"],[1,"G"]],1,[[0,2],[2,0]],false,false,true,[[2,"G"],[2,"Y"]],-1,0,[[0,1],[1,0]]]

    Why: At the start every stack has height 1, so any pair is legal. Playing 0 onto 2 puts Y on Y at position 2 with height 2 and removes stack 0, so the state is [1,W], [2,Y], [1,G] and it is player 1's turn. Only W and G match now, by height. Playing 0 onto 1 or 1 onto 0 mixes height 1 and 2 with different colors, so both return false. Playing 2 onto 0 merges G onto W into [2,G], leaving [2,G], [2,Y]. The game goes on because those two have the same height, so winner() is -1 and it is player 0's turn.

Constraints

  • 1 <= len(tiles) <= 12
  • 'A' <= tiles[i] <= 'Z'
  • 1 <= number of operations <= 10^4
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question