Advertisement
CR7CR7

Memory

Oct 22nd, 2022
1,058
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.stream.Collectors;
  3.  
  4. public class MemoryGame {
  5.  
  6.     public static void main(String[] args) {
  7.  
  8.         Scanner scan = new Scanner(System.in);
  9.         List<String> elements = Arrays.stream((scan.nextLine().split("\\s+"))).collect(Collectors.toList());
  10.         String input;
  11.         int moves = 0;
  12.  
  13.         while (!"end".equals(input = scan.nextLine())) {
  14.             moves++;
  15.             int[] index = Arrays.stream(input.split("\\s+")).mapToInt(Integer::parseInt).toArray();
  16.             if ((index[0] == index[1]) || (index[0] < 0 || index[0] >= elements.size()) || (index[1] < 0 || index[1] >= elements.size())) {
  17.                 System.out.println("Invalid input! Adding additional elements to the board");
  18.                 elements.add(elements.size() / 2, "-" + moves + "a");
  19.                 elements.add(elements.size() / 2, "-" + moves + "a");
  20.             } else {
  21.                 if (elements.get(index[0]).equals(elements.get(index[1]))) {
  22.                     System.out.printf("Congrats! You have found matching elements - %s!%n", elements.get(index[0]));
  23.                     elements.remove(Math.max(index[0], index[1]));
  24.                     elements.remove(Math.min(index[0], index[1]));
  25.                 } else {
  26.                     System.out.println("Try again!");
  27.                 }
  28.                 if (elements.isEmpty()) {
  29.                     System.out.printf("You have won in %d turns!%n", moves);
  30.                     return;
  31.                 }
  32.             }
  33.         }
  34.         System.out.println("Sorry you lose :(");
  35.         System.out.println(String.join(" ", elements));
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement