Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

Olegati avatar Olegati 7 Точки

Memory Game 83/100 (01. Programming Fundamentals Mid Exam Retake)

Здравейте, на следната задача Judge ми дава 83/100 (един неминаващ тест). Видях другите решения във форума за тази задача, обаче не намерих решение. 

Линк към кода: https://pastebin.com/ABKkV3xG

Линк към Judge: https://judge.softuni.bg/Contests/Practice/Index/2517#2

Условието на задачата: 

Memory game

Write a program, which receives a sequence of elements. Each element in the sequence will have a twin. Until the player receives "end" from the console, he will receive strings with two integers separated by space, which represent the indexes of elements in the sequence. 

If the player tries to cheat and enters two equal indexes or indexes which are out of bounds of the sequence you should add two matching elements in the following format "-{number of moves until now}a" at the middle of the sequence and print this message on the console:

"Invalid input! Adding additional elements to the board"

Input

  • On the first line you will receive sequence of elements.

Output

  • Every time the player hit two matching elements you should remove them from the sequence and print on the console the following message:

"Congrats! You have found matching elements - ${element}!"

  • If the player hit two different elements, you should print on the console the following message:

"Try again!"

  • If the player hit all matching elements before he receives "end" from the console, you should print on the console the following message:

"You have won in {number of moves until now} turns!"

  • If the player receives "end" before he hits all matching elements, you should print on the console the following message:

"Sorry you lose :(

              {the current sequence's state}"

Constraints

  • All elements in the sequence will always have a matching element.

 

Examples

Input

Output

1 1 2 2 3 3 4 4 5 5

1 0

-1 0

1 0

1 0

1 0

end

Congrats! You have found matching elements - 1!

Invalid input! Adding additional elements to the board

Congrats! You have found matching elements - 2!

Congrats! You have found matching elements - 3!

Congrats! You have found matching elements - -2a!

Sorry you lose :(

4 4 5 5

Comment

1)

1 0

1 1 2 2 3 3 4 4 5 5 –> 1 = 1, equal elements, so remove them. Moves: 1

2)

-1 0

-1 is invalid index so we add additional elements

2 2 3 3 -2а -2а 4 4 5 5, Moves: 2

3)

1 0

2 2 3 3 -2а -2а 4 4 5 5 -> 2 = 2, equal elements, so remove them. Moves: 3

4)

1 0

3 3 -2а -2а 4 4 5 5 -> 3 = 3, equal elements, so remove them. Moves: 4

5)

1 0

-2а -2а 4 4 5 5 -> -2а = -2а, equal elements, so remove them. Moves: 5

6)

We receive end command.

There are still elements in the sequence, so we loose the game.

Final state - 4 4 5 5

a 2 4 a 2 4

0 3

0 2

0 1

0 1

end

Congrats! You have found matching elements - a!

Congrats! You have found matching elements - 2!

Congrats! You have found matching elements - 4!

You have won in 3 turns!

a 2 4 a 2 4

4 0

0 2

0 1

0 1

end

Try again!

Try again!

Try again!

Try again!

Sorry you lose :(

a 2 4 a 2 4

Тагове:
0
Java Fundamentals 24/06/2021 12:10:34
Axiomatik avatar Axiomatik 2422 Точки

Yeah, that is a well known problem for this Exam (fails test 6) and is triggered when inserting new elements at below validation

            } else {
                String penaltyElement = String.format("-%da", countMoves);
                int midElement = inputList.size() / 2;
                inputList.add(midElement, penaltyElement);
                inputList.add(midElement + 1, penaltyElement);
                System.out.println("Invalid input! Adding additional elements to the board");
            }

Change to following and should give 100%

            } else {
                String penaltyElement = String.format("-%da", countMoves);
                int midElement = inputList.size() / 2;
                inputList.add(midElement, penaltyElement);
                midElement = inputList.size() / 2;
                inputList.add(midElement, penaltyElement);
                System.out.println("Invalid input! Adding additional elements to the board");
            }

C# variant:

                    Console.WriteLine("Invalid input! Adding additional elements to the board");
                    counter++;
                    string added = "-" + counter + "a";
                    list.Insert(list.Count / 2, added);
                    list.Insert(list.Count / 2, added);

 

0
Olegati avatar Olegati 7 Точки

Hi, 

Thanks for the response, but that isn't the problem.

Both versions of the code get 83/100. And the test which fails is the 5th one, not the 6th.

0
Axiomatik avatar Axiomatik 2422 Точки

Hmm,

Then what's probably not working is the removal of matching elements, either remove both elements at once as with JS splice or remove by given element and not the index, since when removing with the first index the position of the second index gets modified and the wrong element can get removed.

C# example:

                        Console.WriteLine($"Congrats! You have found matching elements - {list[startIndex]}!");
                        string target1 = list[startIndex];
                        string target2 = list[endIndex];

                        int targetIndex1 = list.FindIndex(x => x == target1);
                        list.RemoveAt(targetIndex1);

                        int targetIndex2 = list.FindIndex(x => x == target2);
                        list.RemoveAt(targetIndex2);

 

0
Olegati avatar Olegati 7 Точки

Actually, the problem was I didn't check whether the List was empty before the while loop reads a new input.I did check it but in the beginning of the loop: 

while (!input.equals("end")) {
            if (inputList.size() == 0) {
                isWinner = true;
                break;
            }
            countMoves += 1;
            String[] tokens = input.split(" ");
            int index1 = Integer.parseInt(tokens[0]);
            int index2 = Integer.parseInt(tokens[1]);
            if (areIndexesValid(index1, index2, inputList)) {
                if (inputList.get(index1).equals(inputList.get(index2))) {
                    System.out.printf("Congrats! You have found matching elements - %s!%n", inputList.get(index1));
                    if (index1 < index2) {
                        inputList.remove(index2);
                        inputList.remove(index1);
                    } else {
                        inputList.remove(index1);
                        inputList.remove(index2);
                    }
                } else {
                    System.out.println("Try again!");
                }
            } else {
                String penaltyElement = String.format("-%da", countMoves);
                int midElement = inputList.size() / 2;
                inputList.add(midElement, penaltyElement);
                inputList.add(midElement, penaltyElement);
                System.out.println("Invalid input! Adding additional elements to the board");
            }
            input = scan.nextLine();
        } 

Therefore, the failed test didn't break from the loop when the list was empty and was trying to read new input from the console. That was the problem. Here is the correct code:

while (!input.equals("end")) {
    countMoves += 1;
    String[] tokens = input.split(" ");
    int index1 = Integer.parseInt(tokens[0]);
    int index2 = Integer.parseInt(tokens[1]);
    if (areIndexesValid(index1, index2, inputList)) {
        if (inputList.get(index1).equals(inputList.get(index2))) {
            System.out.printf("Congrats! You have found matching elements - %s!%n", inputList.get(index1));
            if (index1 < index2) {
                inputList.remove(index2);
                inputList.remove(index1);
            } else {
                inputList.remove(index1);
                inputList.remove(index2);
            }
            if (inputList.size() == 0) {
                isWinner = true;
                break;
            }
        } else {
            System.out.println("Try again!");
        }
    } else {
        String penaltyElement = String.format("-%da", countMoves);
        int midIndex = inputList.size() / 2;
        inputList.add(midIndex, penaltyElement);
        inputList.add(midIndex, penaltyElement);
        System.out.println("Invalid input! Adding additional elements to the board");
    }
    input = scan.nextLine();
}

 

0
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.