Advertisement
Guest User

Untitled

a guest
Apr 6th, 2020
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const readline = require('readline');
  2. const rl = readline.createInterface({
  3.     input: process.stdin,
  4.     output: process.stdout
  5. });
  6.  
  7. function isValidPosition(x, y) {
  8.     $pass = 1 <= x <= 8 && 1 <= y <= 8;
  9.  
  10.     if (x == '' || y == '' || !$pass) {
  11.         return false;
  12.     }
  13.  
  14.     return true;
  15. }
  16.  
  17. function blackOrWhite(x, y) {
  18.     if ((x % 2 == 0 && y % 2 == 0) || (x % 2 != 0 && y % 2 != 0)) {
  19.         return 'black';
  20.     }
  21.  
  22.     return 'white';
  23. }
  24.  
  25. function findKnightNextMove(x, y) {
  26.     const next = [];
  27.     const curColor = blackOrWhite(x, y);
  28.  
  29.     // Lap qua cac vi tri xung quanh con ma trong vong ban kinh 2 o
  30.     for (let i = x - 2; i <= x + 2; i++) {
  31.         for (let j = y - 2; j <= y + 2; j++) {
  32.             // giong voi vi tri hien tai cua con ma
  33.             const isCurPos = x == i && y == j;
  34.             // trong vong ban kinh 1 o
  35.             let isRadiusLTE1 = false;
  36.  
  37.             if ((x - i === 1 || x === i || i - x === 1) && (y - j === 1 || y === j || j - y === 1)) {
  38.                 isRadiusLTE1 = true;
  39.             }
  40.  
  41.             if (!isValidPosition(i, j) || isCurPos || isRadiusLTE1) {
  42.                 continue;
  43.             }
  44.  
  45.             if (blackOrWhite(i, j) != curColor) {
  46.                 next.push(`${i}|${j}`);
  47.             }
  48.         }
  49.     }
  50.  
  51.     return next;
  52. }
  53.  
  54. function ham() {
  55.     rl.question('Nhap vi tri truc X ', function (A) {
  56.         rl.question('Nhap vi tri truc y ', function (B) {
  57.             A = +A;
  58.             B = +B;
  59.  
  60.             if (!isValidPosition(A, B)) {
  61.                 console.log('Vi tri khong hop le');
  62.                 ham();
  63.                 return;
  64.             }
  65.  
  66.             console.log('Cac vi tri con ma duoc di la: ', findKnightNextMove(A, B));
  67.             rl.close();
  68.         });
  69.     });
  70. }
  71.  
  72. ham();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement