Advertisement
Spocoman

03. Memory Game

Nov 5th, 2023 (edited)
700
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function memoryGame(input) {
  2.     let game = input[0].split(' ');
  3.  
  4.     for (let i = 1; i < input.length - 1; i++) {
  5.         [index1, index2] = input[i].split(' ').map(Number).sort();
  6.         if (index1 >= 0 && index1 < game.length && index2 >= 0 && index2 < game.length && index1 != index2) {
  7.             if (game[index1] === game[index2]) {
  8.                 console.log(`Congrats! You have found matching elements - ${game[index1]}!`);
  9.                 game.splice(index2, 1);
  10.                 game.splice(index1, 1);
  11.                 if (game.length == 0) {
  12.                     console.log(`You have won in ${i} turns!`);
  13.                     return;
  14.                 }
  15.             } else {
  16.                 console.log("Try again!");
  17.             }
  18.         } else {
  19.             game.splice(game.length / 2, 0, `-${i}a`, `-${i}a`);
  20.             console.log("Invalid input! Adding additional elements to the board");
  21.         }
  22.     }
  23.  
  24.     console.log(`Sorry you lose :(\n${game.join(" ")}`);
  25.     return;
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement