๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿง  ์•Œ๊ณ ๋ฆฌ์ฆ˜

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํ˜ผ์ž์„œ ํ•˜๋Š” ํ‹ฑํƒํ†  JS

by megan07 2024. 1. 3.

๋ฌธ์ œ๋งํฌ

 

ํ’€์ด ๋ฐฉ๋ฒ•

๋‚˜์˜ฌ ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ๋ฅผ ๊ตฌํ•ด 0์„ ๋ฆฌํ„ดํ•ด์คฌ์Šต๋‹ˆ๋‹ค

1. X๊ฐ€ O๋ณด๋‹ค ๋งŽ์„ ๋•Œ
2. O๊ฐ€ X๋ณด๋‹ค 2๊ฐœ์ด์ƒ ๋งŽ์„ ๋•Œ
3. ์„ ๊ณต์ด ์ด๋ฏธ ์ด๊ฒผ๋Š”๋ฐ ํ›„๊ณต์ด ์ด์–ด์„œ ์ง„ํ–‰ํ•œ ๊ฒฝ์šฐ
4. ํ›„๊ณต์ด ์ด๋ฏธ ์ด๊ฒผ๋Š”๋ฐ ์„ ๊ณต์ด ์ด์–ด์„œ ์ง„ํ–‰ํ•œ ๊ฒฝ์šฐ

์ด๊ธฐ๋Š” ๊ฒฝ์šฐ๋ฅผ ๋น™๊ณ ๋ผ๊ณ  ์ง€์นญํ–ˆ์Šต๋‹ˆ๋‹ค
๊ฐ€๋กœ, ์„ธ๋กœ ๋น™๊ณ  ์—ฌ๋ถ€๋ฅผ ํŒ๋ณ„ํ•˜๋Š” ํ•จ์ˆ˜
๋Œ€๊ฐ์„  ๋น™๊ณ  ์—ฌ๋ถ€๋ฅผ ํŒ๋ณ„ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์„œ ํ™œ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค

 

function solution(board) {
  // ๋‚˜์˜ฌ ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ ๊ตฌํ•˜๊ธฐ
  //1. X๊ฐ€ O๋ณด๋‹ค ๋งŽ์„ ๋•Œ
  //2. O๊ฐ€ X๋ณด๋‹ค 2๊ฐœ์ด์ƒ ๋งŽ์„ ๋•Œ
  //3. ์„ ๊ณต์ด ์ด๋ฏธ ์ด๊ฒผ๋Š”๋ฐ ํ›„๊ณต์ด ์ด์–ด์„œ ์ง„ํ–‰ํ•œ ๊ฒฝ์šฐ
  //4. ํ›„๊ณต์ด ์ด๋ฏธ ์ด๊ฒผ๋Š”๋ฐ ์„ ๊ณต์ด ์ด์–ด์„œ ์ง„ํ–‰ํ•œ ๊ฒฝ์šฐ

  let o_cnt = 0;
  let x_cnt = 0;

  for (row of board) {
    for (item of row) {
      if (item === 'O') o_cnt++;
      if (item === 'X') x_cnt++;
    }
  }

  if (o_cnt < x_cnt || o_cnt - x_cnt > 1) return 0;

  //๊ฐ€๋กœ ์„ธ๋กœ ๋น™๊ณ  ์ฐพ๊ธฐ
  function row_col_bingo(check_type) {
    for (let i = 0; i < 3; i++) {
      let col_bingo = true;
      let row_bingo = true;

      const col_start = board[0][i];
      const row_start = board[i][0];

      //์ฒดํฌํ•  ํƒ€์ž…๊ณผ ๊ฐ ํ–‰๊ณผ ์—ด์˜ ์‹œ์ž‘์ ์ด ๋‹ค๋ฅด๋ฉด false
      if (col_start !== check_type) col_bingo = false;
      if (row_start !== check_type) row_bingo = false;

      //๊ฐ ํ–‰๊ณผ ์—ด์˜ ๊ฐ’์ด ์ฒดํฌํ•  ํƒ€์ž…๊ณผ ๋‹ค๋ฅด๋ฉด false
      for (let j = 0; j < 3; j++) {
        const col_item = board[j][i];
        const row_item = board[i][j];
        if (col_item !== col_start) col_bingo = false;
        if (row_item !== row_start) row_bingo = false;
      }

      //ํ•œ ์ค„์ด๋ผ๋„ ๋น™๊ณ ๋ฉด true ๋ฐ˜ํ™˜
      if (col_bingo || row_bingo) return true;
    }
    return false;
  }

  //๋Œ€๊ฐ์„  ๋น™๊ณ  ์ฐพ๊ธฐ
  function check_diagonal_bingo(check_type) {
    const center = board[1][1];
    if (check_type !== center) return false;

    //์ขŒ์šฐ ๋Œ€๊ฐ์„ 
    if (board[0][0] === center && board[2][2] === center) return true;

    //์šฐ์ขŒ ๋Œ€๊ฐ์„ 
    if (board[0][2] === center && board[2][0] === center) return true;

    return false;
  }

  //์„ ๊ณต์ด ์ด๋ฏธ ์ด๊ฒผ๋Š”๋ฐ ํ›„๊ณต์ด ์ด์–ด์„œ ์ง„ํ–‰ํ•œ ๊ฒฝ์šฐ
  const is_o_row_col_bingo = row_col_bingo('O');
  const is_o_diagnal_bingo = check_diagonal_bingo('O');
  if ((is_o_row_col_bingo || is_o_diagnal_bingo) && o_cnt <= x_cnt) return 0;

  //ํ›„๊ณต์ด ์ด๋ฏธ ์ด๊ฒผ๋Š”๋ฐ ์„ ๊ณต์ด ์ด์–ด์„œ ์ง„ํ–‰ํ•œ ๊ฒฝ์šฐ
  const is_x_row_col_bingo = row_col_bingo('X');
  const is_x_diagnal_bingo = check_diagonal_bingo('X');
  if ((is_x_row_col_bingo || is_x_diagnal_bingo) && o_cnt !== x_cnt) return 0;

  return 1;
}