Сообщество IT-специалистов
Ответы на любые вопросы об IT
Профессиональное развитие в IT
Удаленная работа для IT-специалистов
public class Main { private final static Pattern pattern = Pattern.compile("(?<left>\\d+)\\s(?<right>\\d+)"); private final static String fileSuffix = ".txt"; private final static String ifLeftIsBiggerMessage = "1"; private final static String ifRightIsBiggerMessage = "2"; private final static String ifEqualMessage = "DRAW"; private final static int defaultLimit = 5; @SuppressWarnings(value = "all") public static void main(String... args) throws Exception { //To set the limit when launching the application. var limit = getLimitFromArr(args); var inputFile = String.format("in.%s", fileSuffix); var outputFile = String.format("out.%s", fileSuffix); Files.lines(Paths.get(inputFile)) .limit(limit) // Limit if needed .map(Main::parseToResult) .filter(Optional::isPresent) .map(Optional::get) .reduce((identity, accumulator) -> new Result(identity.left + accumulator.left, identity.right + accumulator.right)) .map(Result::getResultAsString) .ifPresent(s -> { try (PrintWriter printWriter = new PrintWriter(outputFile)) { printWriter.write(s); } catch (Exception ignored) {/*NooP*/} }); } private static int getLimitFromArr(String... args) { return args.length > 0 ? Integer.parseInt(args[0]) : defaultLimit; } private static Optional<Result> parseToResult(String line) { Matcher matcher = pattern.matcher(line); return matcher.find() ? Optional.of(new Result( Integer.valueOf(matcher.group("left")), Integer.valueOf(matcher.group("right")) )) : Optional.empty(); } private record Result(Integer left, Integer right) { String getResultAsString() { return !Objects.equals(left, right) ? String.valueOf(Integer.compare(left, right)) .replace("-1", ifRightIsBiggerMessage) .replace("1", ifLeftIsBiggerMessage) : ifEqualMessage; } } }