Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Design a data structure such that getWinner method runs in O(1) time.

Assume you call put(x, y, Player) for each move. Best space efficient solution wins.

share|improve this question
2  
It's hard to figure out what you are asking here. What is your getWinner method code? – beary605 Sep 30 '12 at 7:20
1  
Add a winner field, from enum none/naughts/crosses/draw, and keep it up-to-date after each move. Now getWinner runs un O(1), by power of the magic of underspecified problems. – J B Sep 30 '12 at 7:52
1  
O(1) with respect to what? Anyway, the tic tac toe board has a finite number of possible configurations, so anything you can do with it, up to and including a complete traversal of all possible game trees, can be done in constant time. The board is even small enough that -- unlike with, say, chess or go -- the constants should remain fairly reasonable. – Ilmari Karonen Sep 30 '12 at 10:05
There are 26830 possible configurations for a game to be considered finished (one player wins or there is a draw). Even with a poor encoding, it seems entirely feasible to just enumerate each of these games – ardnew Sep 30 '12 at 17:32

closed as not a real question by Ilmari Karonen, grc, J B, Ventero, Matt Oct 1 '12 at 11:17

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, see the FAQ.

1 Answer

PHP

<?php
    class TicTacToe {

        private $board;

        public function __construct($board = '_________') {
            $this->board = $board;
        }

        public function put($x, $y, $player) {
            // TODO: validate input
            // assumes $x, $y in [0..2] and $player in (O|X)
            $this->board[$x + 3*$y] = $player;
        }

        public function getWinner() {
            preg_match(
                '/^(...)*(O|X)\2\K\2'. // horizontal
                '|(O|X)..\3..\K\3'.    // vertical
                '|(O|X)...\4...\K\4'.  // diagonal \
                '|^..(O|X).\5.\K\5/',  // diagonal /
                $this->board,
                $matches
            );

            if(!empty($matches)) {
                return $matches[0];
            } else {
                return 'None';
            }
        }
    }
?>

getWinner() is a constant time lookup, because the length of $this->board is always exactly 9. A simiar approach should work for any language that supports mutable strings and regular expressions.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.