아마존 본사 입사 문제였습니다.
tic-tac-toe는 두 명의 플레이어가 턴을 돌아가면서 1부터 9까지 포지션을 선택하는 게임 입니다. 선택된 포지션은 X나 0로 표시가 되며, 선택된 포지션은 다시 선택할 수가 없습니다. 게임 그리드는 3*3으로 다음과 같습니다.
* *
1 * 2 * 3
* *
* *
4 * 5 * 6
* *
* *
7 * 8 * 9
* *
가로 세로 대각선으로 먼저 세 줄을 연속으로 만드는 플레이어가 우승하게 되며 무승부인 경우도 생깁니다. (매 턴마다 포지션을 입력해야 하지만, 출력은 게임이 끝이 났을 때만 하셔도 됩니다)
입력의 예:
Player 1 - please type a position (available position(s) are 1,2,3,4,5,6,7,8,9):
출력의 예:
* *
X * X * 0
* *
* *
X * 0 * 6
* *
* *
X * 8 * 9
* *
Win playear is: player 1
class Tictactoe:
casetowin = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
def __init__(self):
self.board = list(range(1, 10))
self.available = list(range(1, 10))
self.winner = 0
self.phase = 1
def __str__(self):
string = ''
for i in range(3):
row = self.board[i * 3:i * 3 + 3]
string += '\t\t*\t\t*\t\n\t{0[0]}\t*\t{0[1]}\t*\t{0[2]}\n\t\t*\t\t*\t\n'.format(row)
return string
def move(self, x):
self.board[x - 1] = 'O' if self.phase == 1 else 'X'
self.available.remove(x)
self.winner = self.checkcase()
self.phase = 2 if self.phase == 1 else 1
def checkcase(self):
caselist = []
for case in self.casetowin:
caselist = [self.board[x] for x in case]
if caselist.count('O') == 3:
return 1
elif caselist.count('X') == 3:
return 2
else:
continue
return 0
if __name__ == '__main__':
t = Tictactoe()
while t.winner == 0 and len(t.available) != 0:
move = 0
print('\n' + str(t))
string = 'Player {0} - Please type a position (available position(s) are {1}): ' \
.format(t.phase, ','.join([str(x) for x in t.available]))
while move not in t.available:
try:
move = int(input(string))
if move not in t.available: raise TypeError
except:
print('Please try again. ', end='')
t.move(move)
else:
print(t)
if t.winner > 0:
print('The winner is: Player ' + str(t.winner))
else:
print('The game ended up in a tie')
C++입니다.
position 입력 메시지 출력시 빈칸 숫자들을 ","로 구분하여 나열하는 부분을 간과하면 안될 듯.
프로그램 설명:
"turn"이 9가 될 때까지 진행. 짝수 "turn"은 "O", 홀수 "turn"은 "X". "board[]"값은 Empty, O, X 중 하나.
Winning 조건 점검은, Clever한 방법을 고민하다가 포기하고 평범하게 갔습니다.
board[] index에 따른 보드판이 다음과 같다면:
0|1|2
3|4|5
6|7|8
Note : 현재 위치가 4가 아닌 경우, 현재 위치가 속한 한쪽 사선만 점검하면 되지만 조건식 추가로 코드가 복잡해지는거 같아서 그냥 두 사선 뱡향을 모두 점검합니다.
#include <iostream>
using namespace std;
typedef enum { Player_Empty, Player_O, Player_X } PlayerType;
static PlayerType board[9];
int getValidPosition(int turn)
{
int position;
int numEmpty = 10-turn;
do {
cout << "Player " << (turn%2 ? 1 : 2) << " - please type a position ";
cout << "(available position(s) are ";
for (int i=0, count=0; i<9; ++i)
{
if (board[i] == Player_Empty)
{
cout << i+1;
cout << (numEmpty != ++count ? "," : "):");
}
}
cin >> position;
if (position < 1 || 9 < position || board[position-1] != Player_Empty)
cout << "Invalid position. Try again.\n";
else
return position-1; // convert to array index
} while (true);
}
bool hasWon(PlayerType player, int ndx)
{
// check row
int base = (ndx/3)*3;
if (board[base + (ndx-base+0)%3] == player &&
board[base + (ndx-base+1)%3] == player &&
board[base + (ndx-base+2)%3] == player) return true;
// check column
if (board[(ndx+0*3)%9] == player &&
board[(ndx+1*3)%9] == player &&
board[(ndx+2*3)%9] == player) return true;
// check diagonals
if (ndx % 2 != 0)
return false; // indices 1,3,5,7 cannot make a diagonal win condition
if (board[0] == player &&
board[4] == player &&
board[8] == player) return true;
if (board[2] == player &&
board[4] == player &&
board[6] == player) return true;
return false;
}
bool printBoard()
{
for (int row=0; row<3; ++row)
{
cout << "|";
for (int col=0; col<3; ++col)
{
int ndx = row*3+col;
switch (board[ndx])
{
case Player_O: cout << "O"; break;
case Player_X: cout << "X"; break;
default: cout << ndx+1; break;
}
cout << "|";
}
cout << endl;
}
}
int main(void)
{
int turn = 0; // even = "O", odd = "X"
printBoard();
while (++turn < 10)
{
int position = getValidPosition(turn);
board[position] = (turn%2) ? Player_X : Player_O;
printBoard();
if (hasWon(board[position], position))
{
cout << ((board[position] == Player_X) ? "X" : "O") << " has won.\n";
return 0;
}
}
cout << "This game is a draw\n";
return 0;
}
2014年12月29日 10:27
자바로 풀어봤습니다.
import java.util.Scanner;
public class RealTest {
// 판단
public static int whoIsWinner(int count, String check, int winner) {
if(count==3&check.equals("X")) {
winner = 1;
}else if(count==3&check.equals("O")) {
winner = 2;
}
return winner;
}
// 이긴 사람이 있는가?
public static int answerResult(String[][] ticTacToe, int player) {
int winner = 0;
String[] checkList = {"X", "O"};
// 행 판단
for(String check : checkList) {
for(int i=0; i<3; i++) {
int count = 0;
for(int j=0; j<3; j++) {
if(ticTacToe[i][j].equals(check)){
count++;
}
}
winner = whoIsWinner(count, check, winner);
}
}
// 열 판단
for(String check : checkList) {
for(int j=0; j<3; j++) {
int count = 0;
for(int i=0; i<3; i++) {
if(ticTacToe[i][j].equals(check)){
count++;
}
}
winner = whoIsWinner(count, check, winner);
}
}
// 대각선 판단
for(String check : checkList) {
int countLeft = 0, countRight = 0;
for(int i=0; i<3; i++) {
if(ticTacToe[i][i].equals(check)) {
countLeft++;
}
if(ticTacToe[i][2-i].equals(check)) {
countRight++;
}
}
winner = whoIsWinner(countLeft, check, winner);
winner = whoIsWinner(countRight, check, winner);
}
return winner;
}
// 해당 원소가 들어있는가? & 있으면 표시
public static boolean checkContain(String[][] ticTacToe, String selectedElement, int player) {
boolean result = false;
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
if(ticTacToe[i][j].equals(selectedElement)) {
result = true;
if(player==1) {
ticTacToe[i][j] = "X";
}else {
ticTacToe[i][j] = "O";
}
}
}
}
return result;
}
// 남은 원소 출력
public static void printRemaining (String[][] ticTacToe, int player) {
String remaining = "";
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
if((ticTacToe[i][j].equals("X")==false)&(ticTacToe[i][j].equals("O")==false)) {
remaining += " "+ticTacToe[i][j]+",";
}
}
}
remaining = remaining.substring(0, remaining.length()-1);
System.out.printf("Player %d's turn\n", player);
System.out.printf("please type a position (available position(s) are %s):", remaining);
}
// 결과 출력
public static void painting(String[][] ticTacToe) {
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
if(j!=2) {
System.out.print(" *");
}else {
System.out.print(" ");
}
}
System.out.println();
for(int j=0; j<3; j++) {
if(j!=2) {
System.out.printf(" %s *",ticTacToe[i][j]);
}else {
System.out.printf(" %s ",ticTacToe[i][j]);
}
}
System.out.println();
for(int j=0; j<3; j++) {
if(j!=2) {
System.out.print(" *");
}else {
System.out.print(" ");
}
}
System.out.println();
}
System.out.println();
}
// 메인
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// 게임 시작 전 세팅
String[][] ticTacToe = {{"1", "2", "3"}, {"4", "5", "6"}, {"7" ,"8" ,"9"}};
System.out.println("Game Start!");
painting(ticTacToe);
// 시작
int player = 1;
for(int i=1; i<=9; i++) {
while(true) {
printRemaining(ticTacToe, player);
String selectedElement = scan.next();
boolean isContain = checkContain(ticTacToe, selectedElement, player);
if(isContain==false) {
System.out.println("The element does not exist. Please re-enter.\n");
continue;
}else {
break;
}
}
System.out.println();
painting(ticTacToe);
int winner = answerResult(ticTacToe, player);
if(winner!=0) {
System.out.printf("Game over! Winner is player %d\n", winner);
break;
}else if(i==9&&winner==0) {
System.out.println("Game over! draw! \n");
}
// 플레이어 차례 선정
if(player==1) {
player=2;
}else {
player=1;
}
}
}
}
2022年06月15日 19:51
#include <iostream>
using namespace std;
int main()
{
int pb[9] = {0};
int input = 0;
int turn = 0;
int end = 1;
int e;
while (end!=0)
{
e = 1;
int c=1;
if (turn == 1) turn = 2;
else turn=1;
while (e)
{
cout << "player" << turn << "- ";
cin >> input;
cin.get();
if (pb[input - 1]) continue;
e = 0;
if (turn == 1) pb[input - 1] = 1;
else pb[input - 1] = -1;
}
for (int i = 0; i < 3; i++) if ((pb[i] + pb[i + 1] + pb[i + 2]) == 3 || (pb[i] + pb[i + 1] + pb[i + 2]) == -3) end=0;
for (int i = 0; i < 3; i++) if ((pb[i] + pb[i + (1* 3)] + pb[i+(2 *3)]) == 3 || (pb[i] + pb[i+(1* 3)] + pb[i+(2 *3)] ==3 )) end = 0;
if ((pb[0] + pb[4] + pb[8]) == -3 || (pb[0] + pb[4] + pb[8])==3) end = 0;
if ((pb[2] + pb[4] + pb[6]) == -3 || (pb[2] + pb[4] + pb[6])==3) end = 0;
c++;
if (c == 9) break;
}
for (int i = 0; i < 9; i++)
{
if (i % 3 == 0) cout << endl;
if (pb[i] == 1) cout <<"O ";
else if (pb[i] == -1) cout << "X ";
else cout << i+1<<" ";
}
cout << endl <<"win players is " << turn<<endl;
cin.get();
cin.get();
return 0;
}
검토부탁드립니다. ps.중간에 입력에서 잘못된 값을 받는 경우는 생각하지 않았습니다.
2014年12月05日 23:45
Scala로 구혔습니다. 입력은 Random으로 처리했습니다.
def game(user: String, board: Array[String])(input: (String) => Int): (String, Array[String]) = {
val in = input(user) - 1
if(in < 0 || in > 8) {
game(user, board)(input)
} else if(List("X", "O").contains(board(in))) {
game(user, board)(input)
} else {
board(in) = user
checkRule(user, board) match {
case null =>
if(user == "X")
game("O", board)(input)
else
game("X", board)(input)
case result =>
(result, board)
}
}
}
def checkRule(user: String, board: Array[String]): String = {
val position = board.zipWithIndex.filter(_._1 == user).map(_._2)
def rule1 =
board.grouped(3).exists { grouped =>
grouped.forall(_ == user)
}
def rule2 = {
val temp = position.map(_ % 3)
(0 until 3).exists { n =>
temp.count(_ == n) == 3
}
}
def rule3 = {
def fn(start: Int, step: Int): Boolean = {
if(start > 3 * 3) {
true
} else if(position.contains(start)) {
fn(start + step, step)
} else {
false
}
}
fn(0, 4) || fn(2, 2)
}
if(rule1 || rule2 || rule3) {
user
} else if(board.forall(List("X", "O").contains)){
"draw"
} else
null
}
val (result, board) =
game("X", (1 to 9).map(_.toString).toArray) { user =>
scala.util.Random.nextInt(9) + 1
}
println(
board.grouped(3).map{ grouped =>
grouped.mkString(
"\t*\t\t*\t\n",
"\t*\t",
"\n\t*\t\t*\t"
)
}.mkString("\n")
)
if(result == "draw")
println("The game is a draw.")
else
println(s"Win player is: player $result")
python 3.4
#화면 출력
def show(map):
mapPosion = [7,9,11,
25,27,29,
43,45,47]
for i in range(1,55):
count = 0
ch1 = '\n' if i%6==0 else ' * '
ch2 = ' '+map[mapPosion.index(i)] if i in mapPosion else ' '
ch3 = ch1 if i%2==0 else ch2
print(ch3,end='')
#값 입력
def inValue(player,map):
piece = 'O' if player == 1 else 'X'
strNo = input('\nplayer%s(%s)\n원하는 위치를 입력해 주세요.: ' % (player,piece))
result = 0
if strNo in map:
if map[int(strNo)-1] in ('O','x'):
print('\n!!!!! 그 자리에는 넣을 수 없습니다. !!!!!\n')
else:
index = int(strNo)-1
map[index] = piece
result = int(strNo)
else:
print('\n!!!!!유요한 값이 아닙니다.!!!!!\n')
return int(result)
#조건체크
def check(player,map):
w,h = 3,3
name = 'player1' if player == 1 else 'player2'
check = 0
#가로
for i in range(w-1,(w*h),w):
check += (map[i] == map[i-1] and map[i] == map[i-2])
#세로
for i in range(w):
check += (map[i] == map[i+w] and map[i] == map[i+(w*2)])
#대각선 \
check += map[0] == map[w+1] and map[0] == map[(w+1)*2]
#대각선 /
check += map[w-1] == map[(w-1)*2] and map[w-1] == map[(w-1)*3]
#무승부
if check:
print('\n%s 승리!!!\n' % name)
else:
count = 0
for i in map:
count += (not i.isdigit())
if count == len(map):
print('\n무승부!!!\n')
check = 1
return check
def main():
#필드
map = ['1','2','3',
'4','5','6',
'7','8','9']
player = 1
while 1:
show(map)
if inValue(player,map):
if check(player,map):
break;
player = player * (-1)
main()
coding by python beginner
board = [['1','2','3'],['4','5','6'],['7','8','9']]
symbol = ['X', 'O']
player = 1
def chkWin():
if board[0][0] == board[1][1] and board[1][1] == board[2][2]:
return board[0][0]
elif board[0][2] == board[1][1] and board[1][1] == board[2][0]:
return board[0][2]
else:
for i in range(len(board)):
if len(list(set([board[0][i],board[1][i], board[2][i]]))) == 1:
return board[0][i]
elif len(list(set([board[i][0], board[i][1], board[i][2]]))) == 1:
return board[i][0]
return False
def printBoard():
print('-' * 7)
for t in board:
print('|' + '|'.join(t) + '|')
print('-' * 7)
def tic(player, idx):
board[int((idx-1) / 3)][(idx-1) % 3] = symbol[player-1]
printBoard()
if chkWin() != False:
print('Win playear is: player %s' % player)
return False
return True
def play(player):
remainPos = ''
for arr in board:
for pos in arr:
if pos not in symbol:
remainPos += pos
if remainPos == '':
print('Game is draw.')
return False
else:
print('Player %d - please type a position \
(available position(s) are %s):' % (player, ','.join(list(remainPos))))
pos = int(input())
if remainPos.find(str(pos)) == -1:
print('Not available position.')
return play(player)
else:
return tic(player, pos)
printBoard()
while True:
player ^= 1
if play(player + 1) == False: break
Sub Main()
Dim map()() As Byte = {
New Byte() {1, 2, 3},
New Byte() {4, 5, 6},
New Byte() {7, 8, 9}
}
Dim seledA As New List(Of Byte)
Dim seledB As New List(Of Byte)
Dim print As Action =
Sub()
Console.Clear()
For y As Integer = 0 To 2
For x As Integer = 0 To 2
If seledA.Contains(map(x)(y)) Then
Console.ForegroundColor = ConsoleColor.Red
Console.Write("X ")
ElseIf seledB.Contains(map(x)(y)) Then
Console.ForegroundColor = ConsoleColor.Cyan
Console.Write("X ")
Else
Console.ForegroundColor = ConsoleColor.Gray
Console.Write(map(x)(y) & " ")
End If
Next
Console.WriteLine()
Next
End Sub
print()
Dim check As Func(Of List(Of Byte), Boolean) =
Function(lst As List(Of Byte)) As Boolean
Dim b As Boolean = False
b = b Or lst.Where(Function(n As Byte) n = 1 Or n = 2 Or n = 3).Count = 3
b = b Or lst.Where(Function(n As Byte) n = 4 Or n = 5 Or n = 6).Count = 3
b = b Or lst.Where(Function(n As Byte) n = 7 Or n = 8 Or n = 9).Count = 3
b = b Or lst.Where(Function(n As Byte) n = 1 Or n = 5 Or n = 9).Count = 3
b = b Or lst.Where(Function(n As Byte) n = 3 Or n = 5 Or n = 7).Count = 3
b = b Or lst.Where(Function(n As Byte) n = 1 Or n = 4 Or n = 7).Count = 3
b = b Or lst.Where(Function(n As Byte) n = 2 Or n = 5 Or n = 8).Count = 3
b = b Or lst.Where(Function(n As Byte) n = 3 Or n = 6 Or n = 9).Count = 3
Return b
End Function
For i As Integer = 1 To 9
Dim n As Byte = CByte(Console.ReadLine)
Dim seled As List(Of Byte) = IIf(i Mod 2 = 0, seledA, seledB)
If Not seledA.Union(seledB).Contains(n) Then
seled.Add(n)
If check(seled) Then
print()
If i Mod 2 = 0 Then
Console.WriteLine("Win: A")
Else
Console.WriteLine("Win: B")
End If
Exit For
End If
Else
i -= 1
End If
print()
Next
Console.ReadLine()
End Sub
실시간으로 띄워봣습니다
Java 로 풀어봤습니다.
n * n 가능하도록 만들어봤습니다. 랜덤입력 방식으로 처리됩니다.
n : board 크기 range : board 인덱스 범위 pickedSize : 랜덤입력 값 추출 변수
public class TicTacToeGame_Refactoring {
public static void main(String[] args) {
final int n = 3;
final int range = 3;
final int pickedSize = 2;
char board[][] = new char[n][n];
List<Integer> picked = new ArrayList<Integer>();
List<TwoDimensions> randomInput = new ArrayList<TwoDimensions>();
// 1. init (random input)
createInput(picked, pickedSize, range, randomInput);
Collections.shuffle(randomInput);
// 2. input data (board)
char mark = 'O';
for (TwoDimensions in : randomInput)
{
board[in.x][in.y] = mark;
if (isDecideWinner(board, in.x, in.y, mark))
{
print(board);
System.out.println("Winner is : " + mark);
return;
}
if (mark == 'O') mark = 'X';
else mark = 'O';
}
// 3. Draw
print(board);
System.out.println("draw");
}
public static void print(char board[][]) {
int boardSize = board.length;
for (int i = 0 ; i < boardSize; i++) {
for (int j = 0 ; j < boardSize; j++)
System.out.print(board[i][j] + "\t");
System.out.println();
}
}
public static boolean isDecideWinner(char board[][], int x, int y, char mark) {
int boardSize = board.length;
// width
for (int i = 0 ; i < boardSize; i++)
{
if (board[x][i] != mark)
break;
else if (i == boardSize -1)
return true;
}
// height
for (int i = 0 ; i < boardSize; i++)
{
if (board[i][y] != mark)
break;
else if (i == boardSize -1)
return true;
}
// diagonal
if ( x == y || Math.abs(x-y) == boardSize)
{
for (int i = 0 ; i < boardSize ; i++)
{
if (board[i][i] != mark)
break;
else if ( i == boardSize -1)
return true;
}
for (int i = 0 ; i < boardSize ; i++)
{
if (board[i][boardSize-1] != mark)
break;
else if ( i == boardSize - 1)
return true;
}
}
return false;
}
public static void createInput(List<Integer> picked, int pickedSize, int range, List<TwoDimensions> storage)
{
if(picked.size() == pickedSize)
{
TwoDimensions dimensions = new TwoDimensions();
dimensions.x = picked.get(0); dimensions.y = picked.get(1);
storage.add(dimensions);
return ;
}
for(int next = 0 ; next < range ; next++)
{
picked.add(next);
createInput(picked, pickedSize, range, storage);
picked.remove(picked.size() -1);
}
}
}
class TwoDimensions
{
int x; int y;
}
c입니다
#include <stdio.h>
#include <Windows.h>
#define COL GetStdHandle(STD_OUTPUT_HANDLE)
#define ORIGINAL SetConsoleTextAttribute(COL,0x0007);
#define YELLOW SetConsoleTextAttribute(COL,0x000e);
int board[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; //판
void print(void) //출력
{
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
switch (board[((3 * i) + 1 + j)])
{
case 'O':
printf("%c",'O');
break;
case 'X':
printf("%c",'X');
break;
default:
printf("%d", board[((3 * i) + 1 + j)]);
break;
}
if (j == 2)
printf("\n");
else
printf(" * ");
}
}
printf("\n");
}
int getposition(int turn) //입력받기
{
int position = 1;
do{
printf("Player %d - please type a position(available position(s) are ", turn % 2 ? 1 : 2);
for (int i = 0 ; i < 9 ; ++i)
if(board[i+1] == i+1)
printf("%d, ", board[i+1]);
printf("):");
scanf_s("%d", &position);
if (position < 1 || position>9 || board[position] != position) //1미만 9초과 이미 입력한 경우
printf("error:invalid position.");
else
return position;
} while (1);
}
int winnig_con(int player) //이기는 조건
{
int i = 0;
while (i < 3)
{
if (board[i + 1] == player && board[i + 2] == player && board[i + 3] == player) //row
{
YELLOW printf("Win playear is : player %d\n", player == 'O' ? 1 : 2);
return 1;
}
i += 3;
}
i = 0;
while (i < 3)
{
if (board[i + 1] == player && board[i + 4] == player && board[i + 7] == player) //column
{
YELLOW printf("Win playear is : player %d\n", player == 'O' ? 1:2);
return 1;
}
i++;
}
if (board[1] == player && board[5] == player && board[9] == player)
{
YELLOW printf("Win playear is : player %d\n", player == 'O' ? 1 : 2);
return 1;
}
else if (board[3] == player && board[5] == player && board[7] == player)
{
YELLOW printf("Win playear is : player %d\n", player == 'O' ? 1 : 2);
return 1;
}
return 0;
}
int main(void)
{
int turn = 1;
int position = 0;
while (turn<10)
{
position = getposition(turn);
board[position] = (turn % 2 ? 'O' : 'X');
print();
while (winnig_con(turn % 2 ? 'O' : 'X'))
{
print();
ORIGINAL printf("");
return 0;
}
turn++;
}
YELLOW printf("DRAW\n");
print();
ORIGINAL printf("");
return 0;
}
풀이 작성