确定井字游戏获胜者(基于回合)


26

让我们玩一些代码高尔夫球!

挑战在于找到井字游戏的赢家。

这是通过给董事会指定一个明确的获胜者来完成的,但有很多不同之处:

单元格编号如下:

1|2|3
-+-+-
4|5|6
-+-+-
7|8|9

您将获得一个由9个动作组成的数组,如下所示:

{3, 5, 6, 7, 9, 8, 1, 2, 3}

解析如下:

  • 玩家1标记单元格3
  • 玩家2标记单元格5
  • 玩家1标记单元格6
  • 玩家2标记单元格7
  • 玩家1标记单元格9
  • 玩家1赢了

注意:一个玩家获胜后,游戏不会停止,有可能失败的玩家在获胜的玩家之后设法连续获得3个,但只有第一个获胜者才算。

您现在的工作是获取9个数字作为输入,并输出获胜玩家和获胜回合。如果没有人获胜,请输出您选择的常量。您可以通过任何标准均值/格式接收输入并提供输出。

玩得开心!

根据要求提供更多示例:

{2,3,4,5,6,7,1,8,9} => Player 2 wins in round 6
{1,2,4,5,6,7,3,8,9} => Player 2 wins in round 8
{1,2,3,5,4,7,6,8,9} => Player 2 wins in round 8

11
欢迎来到PPCG!这是一篇不错的第一篇文章,但是通常我们不喜欢非常严格的输入/输出格式。您是否考虑删除“玩家X在Y轮中获胜”,让我们以任何合理的格式输出,例如列表[X, Y]?如果出现平局,我们可以输出其他一致值吗?我建议这样做,因为打印这些确切的字符串实际上并不是打高尔夫球的一部分。对于未来的挑战想法,我建议使用沙盒。:-)
Xcoder先生,18年

对不起这是我的错。我认为现在是正确的。
Grunzwanzling

仔细阅读挑战,我说可能会有平局,当发生时您可以输出自己选择的内容。当玩家2在第6轮获胜时,我返回{2,6},在没有人获胜时返回{0,0}。
Grunzwanzling

我们可以使用零索引吗?(单元,玩家,回合)
Arnauld

1
“您会得到一系列精确的9个动作,例如:{3, 5, 6, 7, 9, 8, 1, 2, 3}”-应该3真的出现两次吗?
乔纳森·艾伦

Answers:


8

视网膜,114字节

(.)(.)
$1O$2X
^
123;;456;;789¶X
{`(.)(.*¶)(.)\1
$3$2
}`.*(.)(.)*\1(?<-2>.)*(?(2)(?!))\1.*¶(..)*
$1$#3
.*¶
T
T`d`Rd

在线尝试!根据我对井字游戏的回答-X或O?X<N>如果第一个玩家在N回合后O<N>获胜,T则输出;如果第二个玩家获胜,则两个都不赢。说明:

(.)(.)
$1O$2X
^
123;;456;;789¶X

创建一个内部棋盘,并用其移动的玩家标记每个移动。

{`(.)(.*¶)(.)\1
$3$2

应用移动。

}`.*(.)(.)*\1(?<-2>.)*(?(2)(?!))\1.*¶(..)*
$1$#3

搜索获胜者,如果找到获胜者,则用获胜者和剩余移动次数替换棋盘。

.*¶
T

如果动作已经用尽,没有人赢,那么这场比赛就是平局。

T`d`Rd

从剩余移动数计算回合数。


4
这是更多之一。。。
法夸德勋爵18年

6

MATL,39字节

3:g&+XIx"IX@oXK@(XIt!yXdyPXd&hK=Aa?KX@.

输出是

  • 1以及R,如果用户1在回合R中获胜,则分开显示;
  • 0并且R,如果用户2在回合R中获胜,则分别显示;
  • 如果没有人获胜,则为空。

在线尝试!验证所有测试用例

说明

3:       % Push [1 2 3]
g        % Convert to logical. Gives [true true true]
&+       % Matrix of all pairs of additions. Gives a 3×3 matrix, which represents
         % the board in its initial state, namely all cells contain 2. This value
         % means "cell not used yet". 1 will represent "cell marked by user 1",
         % and 0 will represent "cell marked by user 2"
XI       % Copy into clipboard I
x        % Delete
"        % Implicit input: array with moves. For each move
  I      %   Push current board state
  X@     %   Push iteration index (starting at 1), that is, current round number
  o      %   Modulo 2: gives 1 or 0. This represents the current user
  XK     %   Copy into clipboard K
  @      %   Push current move ((that is, cell index)
  (      %   Write user identifier (1 or 0) into that cell. Cells are indexed
         %   linearly in column-major order. So the board is transposed compared
         %   to that in the challenge, but that is unimportant
  XI     %   Copy updated board into clipboard I
  t!     %   Duplicate and transpose
  y      %   Duplicate from below: push copy of board
  Xd     %   Extract main diagonal as a 3×1 vector
  y      %   Duplicate from below: push copy of transposed board
  PXd    %   Flip vertically and extract main diagonal. This is the anti-diagonal
         %   of the board
  &h     %   Concatenate stack horizontally. This concatenates the board (3×3),
         %   transposed board (3×3), main diagonal (3×1 vector) and anti-diagonal
         %   (3×1) into an 3×8 matrix
  K=     %   Push current user identifier. Test for equality with each entry of the
         %   3×8 matrix
  A      %   For each column, this gives true if all its entries are true. Note 
         %   that the first three columns in the 3×8 matrix are the board columns;
         %   the next three are the board rows; and the last two columns are the
         %   main diagonal and anti-diagonal. The result is a 1×8 vector
  a      %   True if any entry is true, meaning the current user has won
  ?      %   If true
    K    %     Push current user identifier
    X@   %     Push current round number
    .    %     Break for loop
         %   Implicit end
         % Implicit end
         % Implicit display

5

Javascript(ES6),130个字节

m=>m.reduce((l,n,i)=>l||(b[n-1]=p=i%2+1,"012,345,678,036,147,258,048,246".replace(/\d/g,m=>b[m]).match(""+p+p+p)&&[p,i+1]),0,b=[])

f=m=>m.reduce((l,n,i)=>l||(b[n-1]=p=i%2+1,"012,345,678,036,147,258,048,246".replace(/\d/g,m=>b[m]).match(""+p+p+p)&&[p,i+1]),0,b=[])
console.log(JSON.stringify(f([3,5,6,7,9,8,1,2,3])))
console.log(JSON.stringify(f([2,3,4,5,6,7,1,8,9])))
console.log(JSON.stringify(f([1,2,4,5,6,7,3,8,9])))
console.log(JSON.stringify(f([1,2,3,5,4,7,6,8,9])))

说明

m=>m.reduce((l,n,i)=>               // Reduce the input array with n as the current move
  l||(                              //  If there is already a winner, return it
  b[n-1]=p=i%2+1,                   //  Set the cell at b[n-1] to the current player p
  "012,345,678,036,147,258,048,246" //  For every digit in the list of possible rows:
    .replace(/\d/g,m=>b[m])         //   Replace it with the player at the cell
    .match(""+p+p+p)                //  If any of the rows is filled with p:
      &&[p,i+1]                     //   Return [p, current move]
),0,b=[])

您介意提供解释还是非公开的版本?我有兴趣了解您的解决方案。
杰克

4

Java(OpenJDK 8),445字节

int[] t(int[]m){int[][]f=new int[3][3];boolean z=false;for(int i=0;i<9;i++){f[m[i]%3][m[i]/3]=z?2:1;if(f[m[i]%3][0]==(z?2:1)&&f[m[i]%3][1]==(z?2:1)&&f[m[i]%3][2]==(z?2:1)||f[0][m[i]/3]==(z?2:1)&&f[1][m[i]/3]==(z?2:1)&&f[2][m[i]/3]==(z?2:1)||m[i]%3+m[i]/3==2&&f[0][2]==(z?2:1)&&f[1][1]==(z?2:1)&&f[2][0]==(z?2:1)||m[i]%3==m[i]/3&&f[0][0]==(z?2:1)&&f[1][1]==(z?2:1)&&f[2][2]==(z?2:1)){return(new int[]{(z?2:1),++i});}z=!z;}return(new int[]{0,0});}

在线尝试!

返回值{1,8}表示玩家1在第8轮中获胜。返回值{0,0}表示平局。


5
除非您消除所有不必要的间距,否则由于缺乏打高尔夫球的努力,此答案将被视为无效。此外,我们不建议您这么快地回答自己的挑战,您可能需要添加一个TIO链接,以便我们可以测试您的代码。
Xcoder先生18年


对不起,我复制了错误的内容。实际上它的时间更短
Grunzwanzling

您可以在Java问题中看到打高尔夫球技巧,以删除一些字节。例如,false可以用替换1<0,并且]可以删除第一个之后的空格。
user202729

442个字节。同样,在TIO上存在“页眉”和“页脚”部分的原因是,您无需评论//Code that was submitted//End of code
user202729

2

Kotlin,236个字节

i.foldIndexed(l()to l()){o,(a,b),p->fun f(i:(Int)->Int)=b.groupBy(i).any{(_,v)->v.size>2}
if(f{(it-1)/3}|| f{it%3}|| listOf(l(1,5,9),l(3,5,7)).any{b.containsAll(it)}){return p%2+1 to o}
b to a+p}.let{null}
fun l(vararg l:Int)=l.toList()

美化

    i.foldIndexed(l() to l()) { o, (a, b), p ->
        fun f(i: (Int) -> Int) = b.groupBy(i).any { (_, v) -> v.size > 2 }
        if (f { (it - 1) / 3 } || f { it % 3 } || listOf(l(1, 5, 9), l(3, 5, 7)).any { b.containsAll(it) }) {
            return p % 2 + 1 to o
        }
        b to a + p
    }.let { null }
fun l(vararg l:Int)= l.toList()

测试

fun f(i: List<Int>): Pair<Int, Int>? =
i.foldIndexed(l()to l()){o,(a,b),p->fun f(i:(Int)->Int)=b.groupBy(i).any{(_,v)->v.size>2}
if(f{(it-1)/3}|| f{it%3}|| listOf(l(1,5,9),l(3,5,7)).any{b.containsAll(it)}){return p%2+1 to o}
b to a+p}.let{null}
fun l(vararg l:Int)=l.toList()

data class Test(val moves: List<Int>, val winner: Int, val move: Int)

val tests = listOf(
        Test(listOf(3, 5, 6, 7, 9, 8, 1, 2, 3), 1, 5),
        Test(listOf(2, 3, 4, 5, 6, 7, 1, 8, 9), 2, 6),
        Test(listOf(1, 2, 4, 5, 6, 7, 3, 8, 9), 2, 8),
        Test(listOf(1, 2, 3, 5, 4, 7, 6, 8, 9), 2, 8)
)

fun main(args: Array<String>) {
    tests.forEach { (input, winner, move) ->
        val result = f(input)
        if (result != winner to move) {
            throw AssertionError("$input ${winner to move} $result")
        }
    }
}

蒂奥

在线试用


1

Python 2,170个字节

q=map(input().index,range(1,10))
z=zip(*[iter(q)]*3)
o='',
for l in[q[2:7:2],q[::4]]+z+zip(*z):
 r=[n%2for n in l];y=all(r)*2+1-any(r)
 if y:o+=[max(l)+1,y],
print min(o)

在线尝试!尝试所有测试用例

#swap cell number / turn
q=map(input().index,range(1,10))
#split in 3 parts (rows)
z=zip(*[iter(q)]*3)
#starting value for the list with the results
#since string are "greater" than lists, this will
#be the output value when there is a draw
o='',
#iterate over diagonals, rows and columns
for l in[q[2:7:2],q[::4]]+z+zip(*z):
 #use %2 to separate between player 1 and 2
 r=[n%2 for n in l]
 #store in y the value of the player if the trio is a valid win, 0 otherwise
 #it's a win if all moves are from the same player
 y=all(r)*2+1-any(r)
 #if y has a valid player, add the highest turn of the trio, and the player to o
 if y:o+=[max(l)+1,y],
#output the smaller turn of the valid winning trios
print min(o)


1

Python 3.6+,137个字节

n=m=c=z=0
for a in input():m+=1<<~-int(a);c+=1;z=z or f'{c&1}:{c}'*any(m&t==t for t in[7,56,448,73,146,292,273,84]);n,m=m,n
print(z or-1)

输出格式为winner number:round-1并列。玩家2是0玩家1是1。输入形式为带1个索引的平方数的未消除字符串。


1

果冻,35 个字节

9s3,ZU$$;ŒD$€Ẏf€⁸L€3e
s2ZÇƤ€ZFTḢ;Ḃ$

单调链接,获取动作列表并返回列表,[move, player]其中玩家被标识为1(第一个动作)和0(第二个动作)。

在线尝试!

怎么样?

9s3,ZU$$;ŒD$€Ẏf€⁸L€3e - Link 1: any winning play?: list of player's moves:
9s3                   - (range of) nine split into threes = [[1,2,3],[4,5,6],[7,8,9]]
       $              - last two links as a monad:
      $               -   last two links as a monad:
    Z                 -     transpose = [[1,4,7],[2,5,8],[3,6,9]]
     U                -     upend     = [[7,4,1],[8,5,2],[9,6,3]]
   ,                  -  pair = [[[1,2,3],[4,5,6],[7,8,9]],[[7,4,1],[8,5,2],[9,6,3]]]
           $€         - last two links as a monad for €ach:
         ŒD           -   diagonals = [[1,5,9],[2,6],[3],[7],[4,8]] or [[7,5,3],[4,2],[1],[9],[8,6]]
        ;             -  concatenate = [[1,2,3],[4,5,6],[7,8,9],[1,5,9],[2,6],[3],[7],[4,8]] or [[7,4,1],[8,5,2],[9,6,3],[7,5,3],[4,2],[1],[9],[8,6]]
             Ẏ        - tighten = [[1,2,3],[4,5,6],[7,8,9],[1,5,9],[2,6],[3],[7],[4,8],[7,4,1],[8,5,2],[9,6,3],[7,5,3],[4,2],[1],[9],[8,6]]
                      -    i.e.:    row1    row2    row3    diag\   x     x   x   x     col1    col2    col3    diag/   x     x   x   x
                      -    where x's are not long enough to matter for the rest...
                ⁸     - chain's left argument, list of player's moves
              f€      - filter to keep those moves for €ach of those lists to the left
                 L€   - length of €ach result
                   3e - 3 exists in that? (i.e. were any length 3 when filtered down to only moves made?)

s2ZÇƤ€ZFTḢ;Ḃ$ - Main link: list of the moves  e.g. [2,3,4,5,6,7,1,8,9]
s2            - split into twos                    [[2,3],[4,5],[6,7],[1,8],[9]]
  Z           - transpose                          [[2,4,6,1,9],[3,5,7,8]]
    Ƥ€        - for Ƥrefixes of €ach:
   Ç          -   call last link (1) as a monad     [0,0,0,0,0] [0,0,1,1]
      Z       - transpose                          [[0,0],[0,0],[0,1],[0,1],[0]]
       F      - flatten                            [0,0,0,0,0,1,0,1,0]
        T     - truthy indices                     [          6   8  ]
         Ḣ    - head (if empty yields 0)           6
            $ - last two links as a monad:
           Ḃ  -   modulo by 2 (evens are player 2) 0
          ;   -   concatenate                      [6,0]

0

Python 2,168字节

import itertools as z
f=lambda g:next(([i%2+1,i+1]for i in range(9) if any(c for c in z.combinations([[0,6,1,8,7,5,3,2,9,4][j]for j in g[i%2:i+1:2]],3)if sum(c)==15)),0)

输出(玩家,回合)或平局为0。

将游戏映射到3 x 3的魔方,并寻找3个O或X的总和为15的集合。


0

干净244个 ... 220个字节

import StdEnv
f[a,b]i#k= \l=or[and[isMember(c+n)(take i l)\\c<-:"123147159357"%(j,j+2)]\\j<-[0,3..9]&h<-:"\0\0",n<-[h-h,h,h+h]]
|k a=(1,i*2-1)|i>4=(0,0)|k b=(2,i*2)=f[a,b](i+1)
@l=f(map(map((!!)l))[[0,2..8],[1,3..7]])1

在线尝试!

迭代到的字符串h包含不可打印的字符串,等效于"\003\001\000\000"


0

Python 2中140个 136 134字节

lambda a,i=0:i<9and(any(set(a[i%2:i+1:2])>=set(map(int,t))for t in'123 456 789 147 258 369 159 357'.split())and(i%2+1,i+1)or f(a,i+1))

在线尝试!

编辑:4字节+ 2字节thx到Eric the Outgolfer。

输出元组(playerNumber,roundNumber);如果没有获胜者,则输出False。



@Erik-是的,我应该已经做到了;但我正在抗击流感,眼睛受伤了:)。谢谢!
Chas Brown

好吧,很快好起来。:)
暴民埃里克(Erik the Outgolfer)'18年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.