Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Scanner;
- import java.util.regex.Pattern;
- import java.util.stream.Stream;
- /**
- * The main class for OfficeParty.
- * @author ronnie
- *
- */
- public class Main
- {
- static final Pattern officeGoer = Pattern.compile("^(\\w+) (\\d+(?:.\\d+)?)(( (\\w+))*)$");
- public static void main(String[] args) throws FileNotFoundException
- {
- Scanner inputScanner = new Scanner(new File("office.dat"));
- int numOfficesRemaining = Integer.parseInt(inputScanner.nextLine()); //The first line is how many offices there are.
- while (numOfficesRemaining > 0) { //For each office
- int peopleInOffice = Integer.parseInt(inputScanner.nextLine()); //The next line is how many people are in this office.
- ArrayList<String> workerLines = new ArrayList<>(peopleInOffice);
- for (int i = 0; i < peopleInOffice; i++) { //Make a list of the lines in this office.
- workerLines.add(inputScanner.nextLine());
- }
- workerLines.stream().map(s -> officeGoer.matcher(s)).map(m -> {m.find(); return m;}) //Process the lines.
- .map(m -> new OfficeWorker(m.group(1), Double.parseDouble(m.group(2)), m.group(3).split(" ")))
- .collect(
- HashMap<String, Double>::new,
- (m, w) -> {
- m.put(w.us, m.getOrDefault(w.us, 0.) - w.money);
- double count = w.others.length - 1; //The results of splitting on spaces is an array one larger than the number of people we're giving money to.
- Stream.of(w.others).filter(s -> !s.isEmpty()).map(String::trim).
- forEach(s -> m.put(s, m.getOrDefault(s, 0.) + w.money/count));
- },
- (m1, m2) -> {throw new UnsupportedOperationException();})
- .entrySet().stream().map(e -> String.format("%s %.2f", e.getKey(), e.getValue())).sorted().
- forEachOrdered(s -> System.out.println(s));
- System.out.println(); //Blank line after an office.
- numOfficesRemaining--; //We handled an office.
- }
- inputScanner.close();
- }
- private static class OfficeWorker {
- public String us;
- public double money;
- public String[] others;
- private OfficeWorker(String us, double money, String[] others)
- {
- super();
- this.us = us;
- this.money = money;
- this.others = others;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement