Last active
July 2, 2019 22:14
-
-
Save testerez/9e378643667de78a7962120eb1fa3226 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import * as assert from 'assert'; | |
| type Direction = (x: number, y: number) => [number, number]; | |
| const directions: Direction[] = [ | |
| (x, y) => [x + 1, y + 1], | |
| (x, y) => [x - 1, y + 1], | |
| (x, y) => [x, y + 1], | |
| (x, y) => [x + 1, y], | |
| ]; | |
| const getWinner = (grid: string[][], target: number) => { | |
| for (const y0 in grid) { | |
| for (const x0 in grid[y0]) { | |
| for (const direction of directions) { | |
| let x = Number(x0); | |
| let y = Number(y0); | |
| const player = grid[y][x]; | |
| let total = 0; | |
| while (player && grid[y] && player === grid[y][x]) { | |
| total++; | |
| if (total === target) { | |
| return player; | |
| } | |
| [x, y] = direction(x, y); | |
| } | |
| } | |
| } | |
| } | |
| }; | |
| // tests | |
| const X = 'X'; | |
| const O = 'O'; | |
| const _ = ''; | |
| assert.equal(getWinner([ | |
| [_, _, _], | |
| [X, X, X], | |
| [_, _, _] | |
| ], 3), X); | |
| assert.equal(getWinner([ | |
| [_, _, _], | |
| [X, X, _], | |
| [_, _, _] | |
| ], 3), undefined); | |
| assert.equal(getWinner([ | |
| [_, _, O, _], | |
| [_, _, O, _], | |
| [_, _, O, _], | |
| [_, _, O, _], | |
| ], 4), O); | |
| assert.equal(getWinner([ | |
| [_, _, O, _], | |
| [_, _, X, _], | |
| [_, X, O, _], | |
| [X, _, O, _], | |
| ], 3), X); | |
| assert.equal(getWinner([ | |
| [_, _, O, _], | |
| [_, _, _, _], | |
| [_, X, O, _], | |
| [X, _, O, _], | |
| ], 3), undefined); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment