LardaX

AshesOfRoses

Feb 13th, 2017
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.37 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8.  
  9. public class AshesOfRosesWithOneMap {
  10.     public static void main(String[] args) throws IOException {
  11.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  12.         String regex = "^Grow <(?<region>[A-Z][a-z]+)> <(?<color>[a-zA-Z0-9]+)> (?<amount>[0-9]+)$";
  13.         Pattern pattern = Pattern.compile(regex);
  14.  
  15.         Map<String, Map<String, Long>> regions = new HashMap<>();
  16.  
  17.         String line = "";
  18.  
  19.         while (!"Icarus, Ignite!".equals(line = reader.readLine())) {
  20.             Matcher matcher = pattern.matcher(line);
  21.  
  22.             if (matcher.find()) {
  23.                 String region = matcher.group("region");
  24.                 String color = matcher.group("color");
  25.                 long amount = Long.parseLong(matcher.group("amount"));
  26.  
  27.                 if (!regions.containsKey(region)) {
  28.                     regions.put(region, new HashMap<>());
  29.                 }
  30.                 if (!regions.get(region).containsKey(color)) {
  31.                     regions.get(region).put(color, 0L);
  32.                 }
  33.                 regions.get(region).put(color, regions.get(region).get(color) + amount);
  34.             }
  35.         }
  36.  
  37.         regions.entrySet().stream().sorted((region1, region2) -> {
  38.             long totalAmount1 = region1.getValue().values().stream().mapToLong(e -> e).sum();
  39.             long totalAmount2 = region2.getValue().values().stream().mapToLong(e -> e).sum();
  40.  
  41.             if (totalAmount1 == totalAmount2) {
  42.                 return region1.getKey().compareTo(region2.getKey());
  43.             }
  44.             return Long.compare(totalAmount2, totalAmount1);
  45.         }).forEach(region -> {
  46.             System.out.println(region.getKey());
  47.  
  48.             region.getValue().entrySet().stream().sorted((color1, color2) -> {
  49.                 if (Long.compare(color1.getValue(), color2.getValue()) == 0) {
  50.                     return color1.getKey().compareTo(color2.getKey());
  51.                 }
  52.                 return Long.compare(color1.getValue(), color2.getValue());
  53.             }).forEach(color -> {
  54.                 System.out.println("*--" + color.getKey() + " | " + color.getValue());
  55.             });
  56.         });
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment