Loading...

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

borislavsimonov avatar borislavsimonov 6 Точки

4. *Star Enigma/Regular Expressions/Programming Fundamentals

Здравейте,

може ли някой да ми каже как да поправя тази грешка(няма съвпадение на ред 42) да даде и други насоки.

Exception in thread "main" java.lang.IllegalStateException: No match found
    at java.util.regex.Matcher.getMatchedGroupIndex(Matcher.java:1314)
    at java.util.regex.Matcher.group(Matcher.java:572)
    at StarEnigma.main(StarEnigma.java:42)

https://pastebin.com/3XJ36eKp

1.Star Enigma

The war is in its peak, but you, young Padawan, can turn the tides with your programming skills. You are tasked to create a program to decrypt the messages of The Order and prevent the death of hundreds of lives.

You will receive several messages, which are encrypted using the legendary star enigma. You should decrypt the messages, following these rules:

To properly decrypt a message, you should count all the letters [s, t, a, r]case insensitive and remove the count from the current ASCII value of each symbol of the encrypted message.

After decryption:

Each message should have a planet name, population, attack type ('A', as attack or 'D', as destruction) and soldier count.

The planet name starts after '@' and contains only letters from the Latin alphabet.

The planet population starts after ':' and is an Integer;

The attack type may be "A"(attack) or "D"(destruction) and must be surrounded by "!" (exclamation mark).

The soldier count starts after "->" and should be an Integer.

The order in the message should be: planet name -> planet population -> attack type -> soldier count. Each part can be separated from the others by any character except: '@', '-', '!', ':' and '>'.

Input / Constraints

  • The first line holds n – the number of messagesinteger in range [1…100];
  • On the next n lines, you will be receiving encrypted messages.

Output

After decrypting all messages, you should print the decrypted information in the following format:

First print the attacked planets, then the destroyed planets.
"Attacked planets: {attackedPlanetsCount}"
"-> {planetName}"
"Destroyed planets: {destroyedPlanetsCount}"
"-> {planetName}"

The planets should be ordered by name alphabetically.

Examples

Input

Output

Comments

2

STCDoghudd4=63333$D$0A53333

EHfsytsnhf?8555&I&2C9555SR

Attacked planets: 1

-> Alderaa

Destroyed planets: 1

-> Cantonica

We receive two messages, to decrypt them we calculate the key:

First message has decryption key 3. So we substract from each characters code 3.

PQ@Alderaa1:30000!A!->20000

The second message has key 5.

@Cantonica:3000!D!->4000NM

Both messages are valid and they contain planet, population, attack type and soldiers count.

After decrypting all messages we print each planet according the format given.

Input

Output

Comments

3

tt(''DGsvywgerx>6444444444%H%1B9444

GQhrr|A977777(H(TTTT

EHfsytsnhf?8555&I&2C9555SR

Attacked planets: 0

Destroyed planets: 2

-> Cantonica

-> Coruscant

We receive three messages.

Message one is decrypted with key 4:

pp$##@Coruscant:2000000000!D!->5000

Message two is decrypted with key 7:

@Jakku:200000!A!MMMM

This is invalid message, missing soldier count, so we continue.

The third message has key 5.

@Cantonica:3000!D!->4000NM

 

Благодаря предварително!

Тагове:
0
Fundamentals Module
MartinBG avatar MartinBG 4803 Точки
Best Answer

Има няколко проблема в решението:

  1. Грешен (непълен) регекс:
    "@(?<name>[A-Za-z]+)[^@:!\\->]*:(?<population>\\d+)[^@:!\\->]*!(?<command>[A|D])![^@:!\\->]*\\->(?<soldier>\\d+)"

    Променете го така, за да приеме и записи започващи или завършващи с произволни символи:
     

    ".*@(?<name>[A-Za-z]+)[^@:!\\->]*:(?<population>\\d+)[^@:!\\->]*!(?<command>[A|D])![^@:!\\->]*\\->(?<soldier>\\d+).*"

     

  2. Грешно име на група на 44-ти ред:
     

    String attackString = matcher.group("attack");

    Трабва да е:
     

    String attackString = matcher.group("command");

     

  3. Пропускате да извикате matcher.matches(), преди да опитате да достъпите групите на matcher:
     

                if (matcher.matches()) {
                    String name = matcher.group("name");
                    int population = Integer.parseInt(matcher.group("population"));
                    String attackString = matcher.group("command");
                    int soldier = Integer.parseInt(matcher.group("soldier"));
                    // ...
                }
    

     

  4. Не сортирате списъците с атакувани/унищожени планети, преди да ги отпечатате на конзлата:
     

    attack.sort(Comparator.naturalOrder()); // сортиране по азбучен ред
    destroyed.sort(Comparator.naturalOrder()); // сортиране по азбучен ред
    

     

Това е оправеното решение. 

0
borislavsimonov avatar borislavsimonov 6 Точки

Много ви благодаря за изчерпателния отговор,тотално се бях омотал.

Дали знаете защо няма толкова много решения на задачите с Java,обикновенно са с материал който не сме взели или пък са на C# най-вече.

Има ли някъде където мога да намеря такива решения.

Благодаря!

1
MartinBG avatar MartinBG 4803 Точки

@borislavsimonov

Java-рите са по-малко .. или се оправят по-добре със задачите wink, и затова темите с Java тук са по-малко от тези със C#.

Не ми е известно някъде да има еталонни решения на задачите.

На упражненията към модула би трябвало да ви показват решения на част от задачите. Може да погледнете и упражненията към минали издания на курса.

Някои колеги качват решенията си в github - потърсете кой от групата Ви се справя добре и вижте дали няма акаунт.

Аз имам решения на някои по-стари задачи тук, а тук понякога качвам решения на задачи от текущия Java Fundamentals модул.

 

0
borislavsimonov avatar borislavsimonov 6 Точки

Много Благодаря за инфото.

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