Loading...

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

borislavsimonov avatar borislavsimonov 6 Точки

Treasure Finder-More Exercises: Strings and Text Processing

Здравейте,

Някой може ли да пусне решение на тази задча na java.

Благодаря

https://judge.softuni.bg/Contests/Practice/Index/1674#2

Write a program that decrypts a message by a given key and gathers information about hidden treasure type and its coordinates. On the first line you will receive a key (sequence of numbers). On the next few lines until you receive "find" you will get lines of strings. You have to loop through every string and decrease the ascii code of each character with a corresponding number of the key sequence. The way you choose a key number from the sequence is just looping through it. If the length of the key sequence is less than the string sequence, you start looping from the beginning of the key. For more clarification see the example below. After decrypting the message you will get a type of treasure and its coordinates. The type will be between the symbol '&' and the coordinates will be between the symbols '<' and '>'. For each line print the type and the coordinates in format "Found {type} at {coordinates}".

Example

Input

Output

Comment

1 2 1 3

ikegfp'jpne)bv=41P83X@

ujfufKt)Tkmyft'duEprsfjqbvfv=53V55XA

find

Found gold at 10N70W

Found Silver at 32S43W

We start looping through the first string and the key. When we reach the end of the key we start looping from the beginning of the key, but we continue looping through the string. (until the string is over)

 

The first message is: "hidden&gold&at<10N70W>" so we print we found gold at the given coordinates

 

We do the same for the second string

"thereIs&Silver&atCoordinates<32S43W>"(starting from the beginning of the key and the beginning of the string)

 

"Programming Fundamentals" course @ SoftUni.

Judge.

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

Ето примерно решение, което би трябвало да използва само неща, които вече сте учили:

import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Pr03TreasureFinder {

    private static final Pattern MESSAGE_PATTERN = Pattern.compile("^.*&(?<type>.+)&.*<(?<coordinates>.+)>$");

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int[] keys = Arrays
                .stream(scanner.nextLine().trim().split("\\s+"))
                .mapToInt(Integer::parseInt)
                .toArray();

        String input;
        while (!"find".equals(input = scanner.nextLine())) {
            String message = decryptMessage(input, keys);
            Matcher matcher = MESSAGE_PATTERN.matcher(message);
            if (matcher.matches()) {
                String type = matcher.group("type");
                String coordinates = matcher.group("coordinates");
                System.out.printf("Found %s at %s%n", type, coordinates);
            }
        }
    }

    private static String decryptMessage(String encryptedMessage, int[] keys) {
        char[] chars = new char[encryptedMessage.length()];
        encryptedMessage.getChars(0, encryptedMessage.length(), chars, 0);

        int keysIndex = 0;
        for (int charsIndex = 0; charsIndex < chars.length; charsIndex++) {
            if (keysIndex >= keys.length) {
                keysIndex = 0;
            }
            chars[charsIndex] -= keys[keysIndex++];
        }

        return String.valueOf(chars);
    }
}

 

А това е алтернативно решение с използване на Stream API и итератор.

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