To be complete : my question came up while writing code to play gomoku (game where you need to aling 5 stones on a go board), using MonteCarlo Tree search algorithm. The most time-consuming part in my implementation is the function which checks if the considered move is a win : I need to consider the possibility to have 5 aligned stones on a line, column, or diagonal including the current played stone.
Eventually, I didn't use the diagonal function but took directly parts of the array. Using a compiled function gave me a susbtantial speed-up compared to my previous, non-compiled, function, but maybe I am still far from optimal...
Here is the code I am currently using:
CheckWin2Comp =
Compile[{{statearray, _Integer, 2}, {posx, _Integer}, {posy, _Integer}, {player, _Integer}},
Module[{linec = {1, 1}, colc = {1, 1}, diag1c = {1, 1, 11},
diag2c = {1, 1}, arraysize = Length[statearray], candidatesline = {0},
candidatescol = {0}, candidatesdiag1 = {0},candidatesdiag2 = {0}},
linec = statearray[[posx, Max[posy - 4, 1] ;; Min[posy + 4, arraysize]]];
If[Count[linec, player] > 4,
candidatesline = Total /@ Partition[linec, 5, 1],
candidatesline = {0}];
If[MemberQ[candidatesline, 5 player], Return[player]];
colc = Transpose[statearray][[posy, Max[posx - 4, 1] ;; Min[posx + 4, arraysize]]];
If[Count[colc, player] > 4,
candidatescol = Total /@ Partition[colc, 5, 1],
candidatescol = {0}];
If[MemberQ[candidatescol, 5 player], Return[player]];
diag1c =
Table[statearray[[posx - i, posy - i]], {i,
Max[-4, Max[posx - arraysize, posy - arraysize]],
Min[4, Min[posx, posy] - 1]}];
candidatesdiag1 = Total /@ Partition[diag1c, 5, 1];
If[MemberQ[candidatesdiag1 , 5 player], Return[player]];
diag2c =
Table[statearray[[posx - i, posy + i]], {i,
Max[-4, Max[posx - arraysize, 1 - posy]],
Min[4, Min[posx, arraysize - posy + 1] - 1]}];
candidatesdiag2 = Total /@ Partition[diag2c, 5, 1];
If[MemberQ[candidatesdiag2 , 5 player], Return[player]];
Return[0]], CompilationTarget -> "C",
RuntimeAttributes -> {Listable}, Parallelization -> True]