Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.List;
- import java.util.Scanner;
- import java.util.stream.Collectors;
- public class MemoryGame {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- List<String> sequenceOfElements = Arrays.stream(scanner.nextLine().split("\\s+")).collect(Collectors.toList());
- int twinElement = 0;
- String input = scanner.nextLine();
- while (!input.equals("end")) {
- twinElement++;
- String[] element = input.split("\\s+");
- int firstDigit = Integer.parseInt(element[0]);
- int secondDigit = Integer.parseInt(element[1]);
- boolean isValid = checkIsValid(sequenceOfElements, firstDigit, secondDigit, twinElement);
- if (isValid) {
- checkAndRemove(sequenceOfElements, firstDigit, secondDigit);
- }
- if (sequenceOfElements.isEmpty()) {
- System.out.printf("You have won in %d turns!%n", twinElement);
- return;
- }
- input = scanner.nextLine();
- }
- System.out.println("Sorry you lose :(");
- System.out.println(String.join(" ", sequenceOfElements));
- }
- private static void checkAndRemove(List<String> numberSequence, int numberOne, int numberTwo) {
- if (numberSequence.get(numberOne).equals(numberSequence.get(numberTwo))) {
- System.out.printf("Congrats! You have found matching elements - %s!%n", numberSequence.get(numberOne));
- String currentElement = numberSequence.get(numberOne);
- for (int i = 0; i < numberSequence.size(); i++) {
- if (numberSequence.get(i).equals(currentElement)) {
- numberSequence.remove(i);
- i = -1;
- }
- }
- } else {
- System.out.println("Try again!");
- }
- }
- private static boolean checkIsValid(List<String> numberSequence, int numberOne, int numberTwo, int moves) {
- if ((numberOne == numberTwo) ||
- (numberOne < 0) ||
- (numberTwo < 0) ||
- (numberOne >= numberSequence.size()) ||
- (numberTwo >= numberSequence.size())) {
- numberSequence.add(numberSequence.size() / 2, "-" + moves + "a");
- numberSequence.add(numberSequence.size() / 2 + 1, "-" + moves + "a");
- System.out.println("Invalid input! Adding additional elements to the board");
- return false;
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment