Skip to content

Instantly share code, notes, and snippets.

@huang47
Created February 28, 2020 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huang47/f566a633d71178f95c1ff30fb77d7b87 to your computer and use it in GitHub Desktop.
Save huang47/f566a633d71178f95c1ff30fb77d7b87 to your computer and use it in GitHub Desktop.
/**
* @format
*/
import 'react-native';
import React from 'react';
import App from '../App';
// initial value: 0,
// matrix: [
// 00 01 02
// ['x', 'x', 'y'],
// 10 11 12
// ['y', 'y', 'x'],
// 20 21 22
// ['x', 'y', 'x'],
// ]
// 'x', 'x', 'x' row 1, 2, 3
//
// 'x', col 1, 2, 3
// 'x',
// 'x'
//
// 'x', 1
// 'x',
// 'x'
// 'x', 1
// 'x',
// 'x'
function isRowWin(row) {
return row[0] === row[1] && row[0] === row[2];
}
function isColWin(matrix) {
return (
(matrix[0][0] === matrix[0][1] && matrix[0][0] === matrix[0][2]) ||
(matrix[0][1] === matrix[1][1] && matrix[0][1] === matrix[1][2]) ||
(matrix[0][2] === matrix[2][1] && matrix[0][2] === matrix[2][2])
)
}
function isDiagWin(matrix) {
return (
(matrix[0][0] === matrix[1][1] && matrix[0][0] === matrix[2][2]) ||
(matrix[2][0] === matrix[1][1] && matrix[0][0] === matrix[0][2])
)
}
function isDraw(matrix) {
const isNotYetFinished = matrix.some(row => row.some(x => x === 0));
if (isNotYetFinished) { return false; }
// row win
const [r1, r2, r3] = matrix;
if (isRowWin(r1) || isRowWin(r2) || isRowWin(r3)) {
return false;
}
// col win
if (isColWin(matrix)) {
return false;
}
// diagnol win
if (isDiagWin(matrix)) {
return false;
}
return true;
}
describe('is draw or not', () => {
it('return false if it is in initial state', () => {
expect(isDraw([
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
])).toBe(false);
});
it('return false if it is not finished yet', () => {
expect(isDraw([
['x', 'x', 'y'],
['y', 'y', 'x'],
['x', 'y', 0],
])).toBe(false);
});
it('when it is finished, return true if draw', () => {
expect(isDraw([
['x', 'x', 'y'],
['y', 'y', 'x'],
['x', 'y', 'x'],
])).toBe(true);
});
it('when it is finished, return false if it is not draw', () => {
expect(isDraw([
['x', 'x', 'x'],
['y', 'y', 'x'],
['x', 'y', 'y'],
])).toBe(false);
});
it('when it is finished, return false if it is not draw', () => {
expect(isDraw([
['x', 'x', 'y'],
['x', 'y', 'x'],
['x', 'y', 'y'],
])).toBe(false);
});
it('when it is finished, return false if it is not draw', () => {
expect(isDraw([
['x', 'y', 'y'],
['y', 'x', 'y'],
['x', 'y', 'x'],
])).toBe(false);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment