按字符数发布您的最短代码,以检查玩家是否赢了,如果是,那么。
假设你在变量b
(板)中有一个整数数组,它包含Tic Tac Toe板,以及玩家的移动:
因此,假设数组b = [ 1, 2, 1, 0, 1, 2, 1, 0, 2 ]
代表董事会
X|O|X
-+-+-
|X|O
-+-+-
X| |O
对于这种情况,您的代码应输出1
以表示玩家1赢了。如果没有人赢了,您可以输出0
或false
。
我自己的(Ruby)解决方案即将推出。
编辑:抱歉,忘记将其标记为社区维基。您可以假设输入格式正确,不必进行错误检查。
更新:请以函数的形式发布您的解决方案。大多数人已经这样做了,但有些人没有,这不完全公平。电路板作为参数提供给您的功能。结果应该由函数返回。该函数可以具有您选择的名称。
答案 0 :(得分:37)
疯狂的Python解决方案 - 79个字符
max([b[x] for x in range(9) for y in range(x) for z in range(y)
if x+y+z==12 and b[x]==b[y]==b[z]] + [0])
但是,这假设b中的董事会职位的顺序不同:
5 | 0 | 7
---+---+---
6 | 4 | 2
---+---+---
1 | 8 | 3
也就是说,b[5]
表示左上角,依此类推。
尽量减少上述情况:
r=range
max([b[x]for x in r(9)for y in r(x)for z in r(y)if x+y+z==12and b[x]==b[y]==b[z]]+[0])
93个字符和换行符。
更新:使用按位AND技巧,最多79个字符和换行符:
r=range
max([b[x]&b[y]&b[z]for x in r(9)for y in r(x)for z in r(y)if x+y+z==12])
答案 1 :(得分:22)
这是dmckee解决方案的变体,除了Compact Coding中的每对数字现在是ASCII字符的基数为9的数字。
77 -char版本不适用于MSVC:
// "J)9\t8\r=,\0" == 82,45,63,10,62,14,67,48,00 in base 9.
char*k="J)9 8\r=,",c;f(int*b){return(c=*k++)?b[c/9]&b[c%9]&b[*k--%9]|f(b):0;}
这个 83 -char版本应该适用于每个C编译器:
f(int*b){char*k="J)9 8\r=,",s=0,c;while(c=*k++)s|=b[c%9]&b[c/9]&b[*k%9];return s;}
(请注意,9和8之间的空格应该是一个标签.StackOverflow将所有标签转换为空格。)
测试用例:
#include <stdio.h>
void check(int* b) {
int h0 = b[0]&b[1]&b[2];
int h1 = b[3]&b[4]&b[5];
int h2 = b[6]&b[7]&b[8];
int h3 = b[0]&b[3]&b[6];
int h4 = b[1]&b[4]&b[7];
int h5 = b[2]&b[5]&b[8];
int h6 = b[0]&b[4]&b[8];
int h7 = b[2]&b[4]&b[6];
int res = h0|h1|h2|h3|h4|h5|h6|h7;
int value = f(b);
if (value != res)
printf("Assuming f({%d,%d,%d, %d,%d,%d, %d,%d,%d}) == %d; got %d instead.\n",
b[0],b[1],b[2], b[3],b[4],b[5], b[6],b[7],b[8], res, value);
}
#define MAKEFOR(i) for(b[(i)]=0;b[(i)]<=2;++b[(i)])
int main() {
int b[9];
MAKEFOR(0)
MAKEFOR(1)
MAKEFOR(2)
MAKEFOR(3)
MAKEFOR(4)
MAKEFOR(5)
MAKEFOR(6)
MAKEFOR(7)
MAKEFOR(8)
check(b);
return 0;
}
答案 2 :(得分:12)
不是最短的Python解决方案,但我喜欢它如何将“DICE”引入到井字游戏中:
W=lambda b:max([b[c/5-9]&b[c/5+c%5-9]&b[c/5-c%5-9]for c in map(ord,"DICE>3BQ")])
简单表达的69个字符:
max([b[c/5-9]&b[c/5+c%5-9]&b[c/5-c%5-9]for c in map(ord,"DICE>3BQ")])
答案 3 :(得分:10)
当然使用正则表达式返回0,1或2的函数(换行符仅用于避免滚动条):
sub V{$"='';$x='(1|2)';"@_"=~
/^(...)*$x\2\2|^..$x.\3.\3|$x..\4..\4|$x...\5...\5/?$^N:0}
例如,它可以被称为V(@b)
。
答案 4 :(得分:10)
w=:3 : '{.>:I.+./"1*./"1]1 2=/y{~2 4 6,0 4 8,i,|:i=.i.3 3'
答案 5 :(得分:9)
我不喜欢重复自己(水平/垂直和对角线),但我认为这是一个良好的开端。
C#w / LINQ:
public static int GetVictor(int[] b)
{
var r = Enumerable.Range(0, 3);
return r.Select(i => r.Aggregate(3, (s, j) => s & b[i * 3 + j])).Concat(
r.Select(i => r.Aggregate(3, (s, j) => s & b[j * 3 + i]))).Aggregate(
r.Aggregate(3, (s, i) => s & b[i * 3 + i]) | r.Aggregate(3, (s, i) => s & b[i * 3 + (2 - i)]),
(s, i) => s | i);
}
策略:按行AND
行/列/对角线的每个元素与其他元素(以3作为种子)获取该子集的胜利者,并OR
将它们全部放在一起端。
答案 6 :(得分:8)
哎呀:不知怎的,我误解了很多。这实际上是115个字符,而不是79个字符。
def t(b)[1,2].find{|p|[448,56,7,292,146,73,273,84].any?{|k|(k^b.inject(0){|m,i|m*2+((i==p)?1:0)})&k==0}}||false end
# Usage:
b = [ 1, 2, 1,
0, 1, 2,
1, 0, 2 ]
t(b) # => 1
b = [ 1, 1, 0,
2, 2, 2,
0, 2, 1 ]
t(b) # => 2
b = [ 0, 0, 1,
2, 2, 0,
0, 1, 1 ]
t(b) # => false
扩展代码,用于教育目的:
def tic(board)
# all the winning board positions for a player as bitmasks
wins = [ 0b111_000_000, # 448
0b000_111_000, # 56
0b000_000_111, # 7
0b100_100_100, # 292
0b010_010_010, # 146
0b001_001_001, # 73
0b100_010_001, # 273
0b001_010_100 ] # 84
[1, 2].find do |player| # find the player who's won
# for the winning player, one of the win positions will be true for :
wins.any? do |win|
# make a bitmask from the current player's moves
moves = board.inject(0) { |acc, square|
# shift it to the left and add one if this square matches the player number
(acc * 2) + ((square == player) ? 1 : 0)
}
# some logic evaluates to 0 if the moves match the win mask
(win ^ moves) & win == 0
end
end || false # return false if the find returns nil (no winner)
end
我确信这可以缩短,尤其是大阵列以及可能用于获得玩家动作的位掩码的代码 - 这三元素让我感到烦恼 - 但我认为现在这很好。
答案 7 :(得分:4)
Octave / Matlab,97个字符,包括空格和换行符。如果没有获胜者则输出0,如果玩家1获胜则输出1,如果玩家2获胜则输出2,如果两个玩家获胜则输出2.0801:
function r=d(b)
a=reshape(b,3,3)
s=prod([diag(a) diag(fliplr(a)) a a'])
r=sum(s(s==1|s==8))^(1/3)
如果我们更改规范并从头开始将b作为3x3矩阵传递,我们可以删除整形线,将其缩小到80个字符。
答案 8 :(得分:4)
sub W{$n=$u=0;map{$n++;$u|=$_[$_-$n]&$_[$_]&$_[$_+$n]for/./g}147,4,345,4;$u}
横向赢取有三种方法:
0,1,2 ==> 1-1, 1, 1+1
3,4,5 ==> 4-1, 4, 4+1
6,7,8 ==> 7-1, 7, 7+1
从左下角到右上角对角线获胜的一种方法:
2,4,6 ==> 4-2, 4, 4+2
垂直获胜的三种方式:
0,3,6 ==> 3-3, 3, 3+3
1,4,7 ==> 4-3, 4, 4+3
2,5,8 ==> 5-3, 5, 5+3
从左上角到右下角对角线获胜的一种方法:
0,4,8 ==> 4-4, 4, 4+4
阅读中间栏以获得神奇的数字。
答案 9 :(得分:3)
因为在正确播放时没有人在tictactoe获胜我认为这是最短的代码
echo 0;
7个字符
更新:更好的bash条目是:
86个字符或81个,不包括函数定义(win())。
win()for q in 1 28 55 3 12 21 4 20;{ [[ 3*w -eq B[f=q/8]+B[g=q%8]+B[g+g-f] ]]&&break;}
但是,这是来自bash中的tic-tac-toe程序的代码,因此它不符合规范。
# player is passed in caller's w variable. I use O=0 and X=2 and empty=8 or 9
# if a winner is found, last result is true (and loop halts) else false
# since biggest test position is 7 I'll use base 8. could use 9 as well but 10 adds 2 characters to code length
# test cases are integers made from first 2 positions of each row
# eg. first row (0 1 2) is 0*8+1 = 1
# eg. diagonal (2 4 6) is 2*8+4 = 20
# to convert test cases to board positions use X/8, X%8, and X%8+(X%8-X/8)
# for each test case, test that sum of each tuplet is 3*player value
答案 10 :(得分:2)
def X(b)
u=0
[2,6,7,8,9,13,21,-9].each do|c|u|=b[n=c/5+3]&b[n+c%5]&b[n-c%5]end
u
end
如果输入有两个玩家都赢了,例如
X | O | X ---+---+--- X | O | O ---+---+--- X | O | X
然后输出为3.
答案 11 :(得分:2)
77排除进口并定义b。
import Data.Bits
import Data.Array
b = listArray (0,8) [2,1,0,1,1,1,2,2,0]
w b = maximum[b!x.&.b!y.&.b!z|x<-[0..8],y<-[x+1..8],z<-[12-x-y],z<8,z>=0,z/=y]
或82假设正常排序:
{-# LANGUAGE NoMonomorphismRestriction #-}
import Data.Bits
import Data.Array
b = listArray (0,8) [1,2,1,0,1,2,1,0,2]
w b = maximum[b!x.&.b!y.&.b!z|x<-[0..8],d<-[1..4],y<-[x+d],z<-[y+d],d/=2||x==2,z<9]
答案 12 :(得分:2)
不是胜利者,但也许还有改进的余地。从来没有这样做过。原始概念,初稿。
#define l w|=*b&b[s]&b[2*s];b+=3/s;s
f(int*b){int s=4,w=0;l=3;l;l;l=2;--b;l=1;b-=3;l;l;return l;}
感谢KennyTM的一些想法和测试工具。
“开发版”:
#define l w|=*b&b[s]&b[2*s];b+=3/s;s // check one possible win
f( int *b ) {
int s=4,w=0; // s = stride, w = winner
l=3; // check stride 4 and set to 3
l;l;l=2; // check stride 3, set to 2
--b;l=1; // check stride 2, set to 1
b-=3;l;l; return l; // check stride 1
}
答案 13 :(得分:2)
完整功能的75个字符
T=lambda a:max(a[b/6]&a[b/6+b%6]&a[b/6+b%6*2]for b in[1,3,4,9,14,15,19,37])
如果你像其他人一样遗漏了函数定义,则为66个字符
r=max(a[b/6]&a[b/6+b%6]&a[b/6+b%6*2]for b in[1,3,4,9,14,15,19,37])
8个不同的方向由起始值+增量子表示,压缩成单个数字,可以使用除法和模块提取。例如2,5,8 = 2 * 6 + 3 = 15.
检查一行包含三个相等的值是使用&amp;运营商。 (如果它们不相等则导致零)。 max用于找到可能的赢家。
答案 14 :(得分:1)
JavaScript - 下面的函数“w”是114个字符
<html>
<body>
<script type="text/javascript">
var t = [0,0,2,0,2,0,2,0,0];
function w(b){
i = '012345678036147258048642';
for (l=0;l<=21;l+=3){
v = b[i[l]];
if (v == b[i[l+1]]) if (v == b[i[l+2]]) return v;
}
}
alert(w(t));
</script>
</body>
</html>
答案 15 :(得分:1)
Visual Basic 275 254(包含宽松的输入)字符
Function W(ByVal b())
Dim r
For p = 1 To 2
If b(0) = b(1) = b(2) = p Then r = p
If b(3) = b(4) = b(5) = p Then r = p
If b(6) = b(7) = b(8) = p Then r = p
If b(0) = b(3) = b(6) = p Then r = p
If b(1) = b(4) = b(7) = p Then r = p
If b(2) = b(5) = b(8) = p Then r = p
If b(0) = b(4) = b(8) = p Then r = p
If b(6) = b(4) = b(2) = p Then r = p
Next
Return r
End Function
答案 16 :(得分:1)
b,p,q,r=["."]*9,"1","2",range
while"."in b:
w=[b[i*3:i*3+3]for i in r(3)]+[b[i::3]for i in r(3)]+[b[::4],b[2:8:2]]
for i in w[:3]:print i
if["o"]*3 in w or["x"]*3 in w:exit(q)
while 1:
m=map(lambda x:x%3-x+x%3+7,r(9)).index(input())
if"."==b[m]:b[m]=".xo"[int(p)];p,q=q,p;break
...哦,当你说“Code Golf:Tic Tac Toe”时,这不是你的意思吗? ;)(输入小数位数来放置x或o,即7位于西北方向)
board = ["."]*9 # the board
currentname = "1" # the current player
othername = "2" # the other player
numpad_dict = {7:0, 8:1, 9:2, # the lambda function really does this!
4:3, 5:4, 6:5,
1:6, 2:7, 3:8}
while "." in board:
# Create an array of possible wins: horizontal, vertical, diagonal
wins = [board[i*3:i*3+3] for i in range(3)] + \ # horizontal
[board[i::3] for i in range(3)] + \ # vertical
[board[::4], board[2:8:2]] # diagonal
for i in wins[:3]: # wins contains the horizontals first,
print i # so we use it to print the current board
if ["o"]*3 in wins or ["x"]*3 in wins: # somebody won!
exit(othername) # print the name of the winner
# (we changed player), and exit
while True: # wait for the player to make a valid move
position = numpad_dict[input()]
if board[position] == ".": # still empty -> change board
if currentname == "1":
board[position] = "x"
else:
board[position] = "o"
currentname, othername = othername, currentname # swap values
答案 17 :(得分:1)
130个字符仅为功能大小。如果未找到匹配项,则该函数不返回任何内容,在Lua中类似于返回false。
function f(t)z={7,1,4,1,1,3,2,3,3}for b=1,#z-1 do
i=z[b]x=t[i]n=z[b+1]if 0<x and x==t[i+n]and x==t[i+n+n]then
return x end end end
assert(f{1,2,1,0,1,2,1,0,2}==1)
assert(f{1,2,1,0,0,2,1,0,2}==nil)
assert(f{1,1,2,0,1,2,1,0,2}==2)
assert(f{2,1,2,1,2,1,2,1,2}==2)
assert(f{2,1,2,1,0,2,2,2,1}==nil)
assert(f{1,2,0,1,2,0,1,2,0}~=nil)
assert(f{0,2,0,0,2,0,0,2,0}==2)
assert(f{0,2,2,0,0,0,0,2,0}==nil)
assert(f{0,0,0,0,0,0,0,0,0}==nil)
assert(f{1,1,1,0,0,0,0,0,0}==1)
assert(f{0,0,0,1,1,1,0,0,0}==1)
assert(f{0,0,0,0,0,0,1,1,1}==1)
assert(f{1,0,0,1,0,0,1,0,0}==1)
assert(f{0,1,0,0,1,0,0,1,0}==1)
assert(f{0,0,1,0,0,1,0,0,1}==1)
assert(f{1,0,0,0,1,0,0,0,1}==1)
assert(f{0,0,1,0,1,0,1,0,0}==1)
答案 18 :(得分:1)
Python,102个字符
由于您没有真正指定如何获取输入和输出,因此这可能是必须包含在函数中的“原始”版本。 b
是输入列表; r
是输出(0,1或2)。
r=0
for a,c in zip("03601202","11133342"):s=set(b[int(a):9:int(c)][:3]);q=s.pop();r=r if s or r else q
答案 19 :(得分:1)
1+1 i.~,+./"2>>(0 4 8,2 4 6,(],|:)3 3$i.9)&(e.~)&.>&.>(]<@:#"1~[:#:[:i.2^#)&.>(I.@(1&=);I.@(2&=))
我打算发布有关其工作原理的解释,但那是昨天,现在我无法阅读此代码。
我们的想法是创建一个包含所有可能获胜三元组的列表(048,246,012,345,678,036,147,258),然后制作每个玩家拥有的方块的powerset,然后将两个列表相交。如果有匹配,那就是赢家。
答案 20 :(得分:1)
C中的解决方案(162个字符):
这利用了玩家一个值(1)和玩家二个值(2)设置了独立位的事实。因此,您可以将三个测试框的值按位和位 - 如果值非零,则所有三个值必须相同。此外,结果值==赢得的玩家。
到目前为止不是最短的解决方案,但我能做的最好:
void fn(){
int L[]={1,0,1,3,1,6,3,0,3,1,3,2,4,0,2,2,0};
int s,t,p,j,i=0;
while (s=L[i++]){
p=L[i++],t=3;
for(j=0;j<3;p+=s,j++)t&=b[p];
if(t)putc(t+'0',stdout);}
}
更易阅读的版本:
void fn2(void)
{
// Lines[] defines the 8 lines that must be tested
// The first value is the "Skip Count" for forming the line
// The second value is the starting position for the line
int Lines[] = { 1,0, 1,3, 1,6, 3,0, 3,1, 3,2, 4,0, 2,2, 0 };
int Skip, Test, Pos, j, i = 0;
while (Skip = Lines[i++])
{
Pos = Lines[i++]; // get starting position
Test = 3; // pre-set to 0x03 (player 1 & 2 values bitwise OR'd together)
// search each of the three boxes in this line
for (j = 0; j < 3; Pos+= Skip, j++)
{
// Bitwise AND the square with the previous value
// We make use of the fact that player 1 is 0x01 and 2 is 0x02
// Therefore, if any bits are set in the result, it must be all 1's or all 2's
Test &= b[Pos];
}
// All three squares same (and non-zero)?
if (Test)
putc(Test+'0',stdout);
}
}
答案 21 :(得分:1)
我想出了两个表达式,每个表达式为64个:
max(a[c/8]&a[c/8+c%8]&a[c/8-c%8]for c in map(ord,'\t\33$#"!+9'))
和
max(a[c/5]&a[c/5+c%5]&a[c/5+c%5*2]for c in[1,3,4,8,12,13,16,31])
当你添加“W = lambda b:”使它成为一个函数时,它就会产生75个字符串。 迄今为止最短的Python?
答案 22 :(得分:0)
LinQ 236
如果没有函数声明,C#可能会减少;)
Function P(ByVal b())
Dim s() = "012.048.036.147.258.345.678".Split(".")
If (From x In s Where b(Val(x(0))) & b(Val(x(1))) & b(Val(x(2))) = "111").Any Then Return 1
If (From x In s Where b(Val(x(0))) & b(Val(x(1))) & b(Val(x(2))) = "222").Any Then Return 2
Return 0
End Function
答案 23 :(得分:0)
经过我的第一次打高尔夫球训练后,我能够将这个功能削减到155个字符(诅咒阵列括号!)。通过一些数学技巧,我能够推广水平,垂直和对角线的三格检查。另外,我独立发现了Eric Pi所说的关于用bitwise和ss测试三元组等价的内容。我的方法:
int i=-1,j,w=0;int[]a={0,0,2,0,9,3,3,1,3,1,1,1,1,3,2,4};while(++i<4)for(j=a[i];j<a[i+4];j+=a[i+8])if((g[j]&g[j+a[i+12]]&g[j+2*a[i+12]])>0)w=g[j];return w;
另外,我创建了一个类来生成所有有效的测试板(不像听起来那么简单)。对于那些有兴趣尝试使用Java最佳155的人,这是我的测试类:
public class TicTacToe
{
public static void main(String[] args)
{
int[][] boards = generateBoards();
for(int i = 0; i < boards.length; ++i)
{
int winner = getWinner(boards[i]);
System.out.println(winner + " " + boards[i][0] + " " + boards[i][1] + " " + boards[i][2]);
System.out.println( " " + boards[i][3] + " " + boards[i][4] + " " + boards[i][5]);
System.out.println( " " + boards[i][6] + " " + boards[i][7] + " " + boards[i][8]);
System.out.println();
}
}
public static int getWinner(int[] g)
{
int i=-1,j,w=0;int[]a={0,0,2,0,9,3,3,1,3,1,1,1,1,3,2,4};while(++i<4)for(j=a[i];j<a[i+4];j+=a[i+8])if((g[j]&g[j+a[i+12]]&g[j+2*a[i+12]])>0)w=g[j];return w;
}
public static boolean isValid(int[] board)
{
// O = 0 : X = 1
int counts[] = new int[2];
// Count the number of Xs and Os
for(int i = 0; i < 9; ++i)
if(board[i] > 0)
++counts[board[i] - 1];
// Make sure the counts make sense. If not return "no"
if(!(counts[1] == counts[0] || counts[1] == counts[0] + 1))
return false;
// Now we're going to total the number of horizontal/vertical wins
int wins[] = new int[2];
// Check rows
if(board[0] != 0 && board[0] == board[1] && board[1] == board[2]) ++wins[board[0] - 1];
if(board[3] != 0 && board[3] == board[4] && board[4] == board[5]) ++wins[board[3] - 1];
if(board[6] != 0 && board[6] == board[7] && board[7] == board[8]) ++wins[board[6] - 1];
// Check columns
if(board[0] != 0 && board[0] == board[3] && board[3] == board[6]) ++wins[board[0] - 1];
if(board[1] != 0 && board[1] == board[4] && board[4] == board[7]) ++wins[board[1] - 1];
if(board[2] != 0 && board[2] == board[5] && board[5] == board[8]) ++wins[board[2] - 1];
// Make sure the win counts make sense
if(wins[0] > 1 && wins[1] > 1)
return false;
// Hmmmm... I guess it's a valid board
return true;
}
public static int[][] generateBoards()
{
int boardSize = 9;
int permutationCount = (int)Math.pow(4, 9);
int[][] boards = new int[permutationCount][boardSize];
int actualIndex = 0;
for(int i = 0; i < permutationCount; ++i)
{
boolean isUnique = true;
for(int j = 0; j < boardSize; ++j)
{
int x = (i >>> j) & 3;
if(x == 3)
isUnique = false;
boards[actualIndex][j] = x;
}
if(isUnique && isValid(boards[actualIndex]))
++actualIndex;
}
return Arrays.copyOf(boards, actualIndex);
}
}
不错我认为对于没有任何异域函数调用的简单java。享受!
答案 24 :(得分:0)
高尔夫模式:
(defun x(b)(find-if-not 'null(mapcar(lambda(r)(let((v(mapcar(lambda(c)(elt b c))r)))(if(apply '= v)(car v))))'((0 1 2)(3 4 5)(6 7 8)(0 3 6)(1 4 7)(2 5 8)(0 4 8)(2 4 6)))))
可读模式:
(defun ttt-winner (board)
(find-if-not 'null
(mapcar (lambda (row)
(let ((vals (mapcar (lambda (cell) (elt board cell)) row)))
(if (apply '= vals) (car vals))))
'((0 1 2) (3 4 5) (6 7 8) (0 3 6) (1 4 7) (2 5 8) (0 4 8) (2 4 6)))))
答案 25 :(得分:0)
我的第一个代码高尔夫,重达140个字符(导入声明,我否认你!):
import operator as o
def c(t):return({1:1,8:2}.get(reduce(o.mul,t[:3]),0))
def g(t):return max([c(t[x::y]) for x,y in zip((0,0,0,1,2,2,3,6),(1,3,4,3,3,2,1,1))])
稍微不那么模糊g:
def g(t):return max([c(t[x::y]) for x,y in [[0,1],[0,3],[0,4],[1,3],[2,3],[2,2],[3,1],[6,1]]])
答案 26 :(得分:0)
C#,148我想。
int[] m={0,1,3,1,6,1,0,3,1,3,2,3,0,4,2,2};int i,s,w,r=0,o;for(i=0;i<16;i+=2){s=m[i];w=m[i+1];o=v[s];if((o==v[w+s])&&(o==v[s+(w*2)])){r=o;}}return r;
答案 27 :(得分:0)
f(int*b){char*s="012345678036147258048264\0";int r=0;while(!r&&*s){int q=r=3;while(q--)r&=b[*s++-'0'];}return r;}
我觉得它有效吗?我的第一个代码高尔夫,温柔。
每3位数字对3个需要匹配的单元格进行编码。内心同时检查三合会。外部同时检查所有8。
答案 28 :(得分:0)
C#解决方案。
乘以每行中的值,col&amp;对角线。如果result == 1,则X获胜。如果结果== 8,则O赢。
int v(int[] b)
{
var i = new[] { new[]{0,1,2}, new[]{3,4,5}, new[]{6,7,8}, new[]{0,3,6}, new[]{1,4,7}, new[]{2,5,8}, new[]{0,4,8}, new[]{2,4,6} };
foreach(var a in i)
{
var n = b[a[0]] * b[a[1]] * b[a[2]];
if(n==1) return 1;
if(n==8) return 2;
}
return 0;
}
答案 29 :(得分:0)
var s=new[]{0,0,0,1,2,2,3,6};
var t=new[]{1,3,4,3,2,3,1,1};
return(s.Select((p,i)=>new[]{g[p],g[p+t[i]],g[p+2*t[i]]}).FirstOrDefault(l=>l.Distinct().Count()==1)??new[]{0}).First();
(g
是网格)
可能会改进......我还在努力;)
答案 30 :(得分:0)
可能会变得更好,但我现在感觉不是特别聪明。这只是为了确保代表Haskell ......
假设b
已存在,则会将结果放入w
。
import List
a l=2*minimum l-maximum l
z=take 3$unfoldr(Just .splitAt 3)b
w=maximum$0:map a(z++transpose z++[map(b!!)[0,4,8],map(b!!)[2,4,6]])
假设从stdin输出并输出到stdout,
import List
a l=2*minimum l-maximum l
w b=maximum$0:map a(z++transpose z++[map(b!!)[0,4,8],map(b!!)[2,4,6]])where
z=take 3$unfoldr(Just .splitAt 3)b
main=interact$show.w.read
答案 31 :(得分:0)
缩小的:
#define A(x) a[b[x%16]]
int c,b[]={4,8,0,1,2,4,6,0,3,4,5,2,8,6,7,2};int
T(int*a){for(c=0;c<16;c+=2)if(A(c)&A(c+1)&A(c+2))return A(c);return 0;}
两者都返回计数(一个必要,另一个需要用空格替换)。
数组编码从偶数位置开始并采用mod 16的三种方式获胜的八种方法。
来自Eric Pi的按位和诡计。
更易读的形式:
#define A(x) a[b[x%16]]
// Compact coding of the ways to win.
//
// Each possible was starts a position N*2 and runs through N*2+2 all
// taken mod 16
int c,b[]={4,8,0,1,2,4,6,0,3,4,5,2,8,6,7,2};
int T(int*a){
// Loop over the ways to win
for(c=0;c<16;c+=2)
// Test for a win
if(A(c)&A(c+1)&A(c+2))return A(c);
return 0;
}
测试脚手架:
#include <stdlib.h>
#include <stdio.h>
int T(int*);
int main(int argc, char**argv){
int input[9]={0};
int i, j;
for (i=1; i<argc; ++i){
input[i-1] = atoi(argv[i]);
};
for (i=0;i<3;++i){
printf("%1i %1i %1i\n",input[3*i+0],input[3*i+1],input[3*i+2]);
};
if (i = T(input)){
printf("%c wins!\n",(i==1)?'X':'O');
} else {
printf("No winner.\n");
}
return 0;
}
答案 32 :(得分:0)
借用其他提交的一些技巧。 (不知道C#让你这样的init数组)
static int V(int[] b)
{
int[] a={0,1,3,1,6,1,0,3,1,3,2,3,0,4,2,2};
int r=0,i=-2;
while((i+=2)<16&&(r|=b[a[i]]&b[a[i]+a[i+1]]&b[a[i]+a[i+1]*2])==0){}
return r;
}
答案 33 :(得分:0)
def s(b)(0..8).to_a+[0,3,6,1,4,7,2,5,8,0,4,8,2,4,6].each_slice(3){|m|if b.values_at(*m).uniq.length<2&&b[m[0]]!=0;return b[m[0]];end}return false;end
这是一个相当简单的解决方案,我相信我能够再减少它。这是一个可读的版本:
def someone_won(b)
helper = (0..8).to_a + [ 0, 3, 6, 1, 4, 7, 2, 5, 8, 0, 4, 8, 2, 4, 6]
helper.each_slice(3) { |m|
if b.values_at(*m).uniq.length < 2 && b[m[0]] != 0
return b[m[0]]
end
}
return false
end
答案 34 :(得分:0)
我确信有更短的方法可以做到这一点,但是... Perl,141个字符(函数内部134个)
sub t{$r=0;@b=@_;@w=map{[split//]}split/,/,"012,345,678,036,147,258,048,246";for(@w){@z=map{$b[$_]}@$_;$r=$z[0]if!grep{!$_||$_!=$z[0]}@z;}$r;}