Created
May 19, 2022 04:50
-
-
Save fwrq41251/0ea24bbdbb060b9039cd2226f4fb1999 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.nio.file.Files; | |
import java.nio.file.Paths; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.function.Predicate; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
public class PassportValidator { | |
public static void main(String[] args) throws IOException { | |
String content = Files.readString(Paths.get("input.txt")); | |
List<Map<String, String>> passports = new ArrayList<>(); | |
for (String line : content.split("\n\n")) { | |
Map<String, String> map = new HashMap<>(); | |
for (String pair : line.split("\n|\\s")) { | |
String[] pair1 = pair.split(":"); | |
map.put(pair1[0], pair1[1]); | |
} | |
passports.add(map); | |
} | |
Map<String, Predicate<String>> predicateMap = new HashMap<>(); | |
predicateMap.put("byr", s -> checkNumberBetween(s, 1920, 2002)); | |
predicateMap.put("iyr", s -> checkNumberBetween(s, 2010, 2020)); | |
predicateMap.put("eyr", s -> checkNumberBetween(s, 2020, 2030)); | |
predicateMap.put("hgt", s -> { | |
Pattern pattern = Pattern.compile("(\\d+)(cm|in)$"); | |
Matcher matcher = pattern.matcher(s); | |
if (matcher.matches()) { | |
String height = matcher.group(1); | |
String type = matcher.group(2); | |
return switch (type) { | |
case "cm" -> checkNumberBetween(height, 150, 193); | |
case "in" -> checkNumberBetween(height, 59, 76); | |
default -> false; | |
}; | |
} else return false; | |
}); | |
predicateMap.put("hcl", s -> s.matches("#[\\d|a-f]{6}")); | |
predicateMap.put("ecl", s -> s.matches("amb|blu|brn|gry|grn|hzl|oth")); | |
predicateMap.put("pid", s -> s.matches("^(?!0+$)0\\d{8}$")); | |
Predicate<Map<String, String>> passportValidator = p -> p.keySet().containsAll(predicateMap.keySet()); | |
long count = passports.stream().filter(passportValidator).count(); | |
System.out.println(count); | |
Predicate<Map<String, String>> passportValidator2 = | |
p -> predicateMap.entrySet().stream().allMatch(e -> e.getValue().test(p.getOrDefault(e.getKey(), ""))); | |
long count2 = passports.stream().filter(passportValidator2).count(); | |
System.out.println(count2); | |
} | |
private static boolean checkNumberBetween(String s, int min, int max) { | |
try { | |
int i = Integer.parseInt(s); | |
return i >= min && i <= max; | |
} catch (NumberFormatException e) { | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output:
206
14