Simplified Chess Engine

  • + 0 comments

    C++ solution. I tried to fit in 30 lines. Without success :) The main part of the algorithm is explained by nickww718 https://www.hackerrank.com/challenges/simplified-chess-engine/forum/comments/447437

    int getCell(uint64_t board, int idx) { 
      return (board&(15LL<<(idx<<2)))>>(idx<<2); 
    }
    void setCell(uint64_t &board, int idx, int value) { 
      board = board &(~(15LL<<(idx<<2)))|(uint64_t(value)<<(idx<<2));
    }
    string simplifiedChessEngine(vector<vector<char>> const& whites,
    vector<vector<char>> const& blacks, int moves, 
    int curMove = 1, uint64_t board = 0) {
      if (curMove==1)             //board=4*4*{0FFP},F:figute,P:player
        for (int plr = 0; plr < 2; plr++)           
          for (auto& f : plr?blacks:whites)                    //ABCDE
            setCell(board, f[1]-'A' + ((f[2] - '1') << 2),     //FGHIJ
              plr | "60000000000040028"[f[0] - 'B'] - '0');    //KL*NO
      int plr = (curMove & 1) ^ 1, cell1 = 0, x = 0, y = 0;    //PQRST
      if (curMove > moves) return plr ? "YES" : "NO";          //UVWXY
      char figMoves[5][9]={"","NIHGLQRS","JDBFPVXT","IGQS","NHLR" };
      for (int i = 0; i < 16; i++)                            
        if ((cell1 = getCell(board, i)) && (cell1 & 1) == plr)                   
          for (char* m = figMoves[cell1 >> 1]; *m; m++)   
            for (int d = 1, e = ((cell1>>1)==2?1:3); d <= e; d++) {
              if ((x = (i & 3) + d * ((*m-'A')%5-2)) >= 0 && x < 4 &&
              (y = (i >> 2) + d * ((*m-'A')/5-2)) >= 0 && y < 4) {
                uint64_t oldBoard = board;
                int cell2 = getCell(board, x | (y << 2));
                if (cell2) {
                  if ((cell2 & 1) == plr) break;
                  else if ((cell2 >> 1) == 1) return"YES";
                }
                setCell(board, i, 0);
                setCell(board, x | (y << 2), cell1);
                if (simplifiedChessEngine(
                  whites, blacks, moves, curMove + 1, board) == "NO")
                  return "YES";
                board = oldBoard;
                if (cell2)break;
              } else break;
            }
      return "NO";
    }