Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.nio.charset.StandardCharsets;
- import java.util.Arrays;
- import java.util.NoSuchElementException;
- import java.util.Optional;
- import java.util.PrimitiveIterator;
- import java.util.function.Function;
- import java.util.function.UnaryOperator;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import java.util.stream.Collectors;
- public class Pr03TreasureFinder {
- private static final Pattern MESSAGE_PATTERN = Pattern.compile("^.*&(?<type>.+)&.*<(?<coordinates>.+)>$");
- public static void main(String[] args) throws IOException {
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
- int[] keys = Arrays.stream(reader.readLine().split("\\s+"))
- .mapToInt(Integer::parseInt)
- .toArray();
- KeySupplier keySupplier = new KeySupplier(keys);
- UnaryOperator<String> decryptMessage = encryptedMessage -> {
- keySupplier.reset();
- return encryptedMessage.chars()
- .map(charValue -> charValue - keySupplier.nextInt())
- .mapToObj(charValue -> (char) charValue)
- .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
- .toString();
- };
- Function<String, Optional<String>> treasureOptional = decryptedMessage -> {
- Matcher matcher = MESSAGE_PATTERN.matcher(decryptedMessage);
- if (!matcher.matches()) {
- return Optional.empty();
- }
- String type = matcher.group("type");
- String coordinates = matcher.group("coordinates");
- return Optional.of(String.format("Found %s at %s", type, coordinates));
- };
- System.out.println(reader
- .lines()
- .takeWhile(message -> !"find".equals(message))
- .map(decryptMessage)
- .map(treasureOptional)
- .filter(Optional::isPresent)
- .map(Optional::get)
- .collect(Collectors.joining(System.lineSeparator()))
- );
- }
- private static final class KeySupplier implements PrimitiveIterator.OfInt {
- private final int[] keys;
- private int index;
- private KeySupplier(int[] keys) {
- this.keys = keys;
- index = 0;
- }
- public void reset() {
- index = 0;
- }
- @Override
- public boolean hasNext() {
- if (keys.length == 0) {
- return false;
- }
- if (index >= keys.length) {
- index = 0;
- }
- return true;
- }
- @Override
- public int nextInt() {
- if (!hasNext()) {
- throw new NoSuchElementException();
- }
- return keys[index++];
- }
- @Override
- public Integer next() {
- return nextInt();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement