Test Failed
Push — master ( dcae49...58e792 )
by Jinyun
02:20
created

FindWinnerOnATicTacToeGame::tictactoe2()   B

Complexity

Conditions 10
Paths 55

Size

Total Lines 33
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 22
c 1
b 0
f 0
dl 0
loc 33
rs 7.6666
cc 10
nc 55
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class FindWinnerOnATicTacToeGame
8
{
9
    public static function tictactoe(array $moves): string
10
    {
11
        if (empty($moves)) {
12
            return '';
13
        }
14
        $row = $col = array_fill(0, 2, array_fill(0, 3, 0));
15
        $d1 = $d2 = array_fill(0, 2, 0);
16
        foreach ($moves as $k => $v) {
17
            [$r, $c, $i] = [$v[0], $v[1], $k % 2];
18
            if (++$row[$i][$r] === 3 ||
19
                ++$col[$i][$c] === 3 ||
20
                ($r === $c && ++$d1[$i] === 3) ||
21
                ($r + $c === 2 && ++$d2[$i] === 3)) {
22
                return $i === 0 ? 'A' : 'B';
23
            }
24
        }
25
26
        return count($moves) === 9 ? 'Draw' : 'Pending';
27
    }
28
29
    public static function tictactoe2(array $moves): string
30
    {
31
        if (empty($moves)) {
32
            return '';
33
        }
34
        $n = 8;
35
        $a = $b = array_fill(0, $n, 0);
36
        foreach ($moves as $k => $v) {
37
            [$r, $c] = [$v[0], $v[1]];
38
            if ($k % 2 === 0) {
39
                $player = & $a;
40
            } else {
41
                $player = & $b;
42
            }
43
            $player[$r]++;
44
            $player[$c + 3]++;
45
            if ($r === $c) {
46
                $player[6]++;
47
            }
48
            if ($r + $c === 2) {
49
                $player[7]++;
50
            }
51
        }
52
        for ($i = 0; $i < $n; $i++) {
53
            if ($a[$i] === 3) {
54
                return 'A';
55
            }
56
            if ($b[$i] === 3) {
57
                return 'B';
58
            }
59
        }
60
61
        return count($moves) === 9 ? 'Draw' : 'Pending';
62
    }
63
}
64