Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Scanner;
- public class RedditScrabble {
- public RedditScrabble(String word, String letters) {
- this.word = word;
- this.letters = letters;
- }
- private Map<Integer, Integer> occurences = new HashMap<>();
- private final String word;
- private final String letters;
- public static void main(String... args) {
- try(Scanner kb = new Scanner(System.in)) {
- // Yeah, if they're not being dicks with the input we won't need this.
- // But why take the chance?
- String word = kb.nextLine().trim().toUpperCase();
- String letters = kb.nextLine().trim().toUpperCase();
- // It's not proper java unless we create a new object.
- // And java.lang.String doesn't count!
- RedditScrabble rs = new RedditScrabble(word, letters);
- if(rs.canMakeWord()) {
- System.out.println("We can make the word");
- }
- else {
- System.out.println("We can not make the word");
- }
- }
- }
- public boolean canMakeWord() {
- setupIncidenceCounter();
- int errors = word.chars().map(this::consumeChar).reduce(Integer::sum).orElse(0);
- // In a more enterprisey application we would have logged the remainders in the incidence counters for that sweet Business Intelligence OLAP cube running on Hadoop.
- // But this is /g/ so we just return.
- return 0 == errors;
- }
- private void setupIncidenceCounter() {
- // This is slower than using a loop, but it reads much better.
- letters.chars().forEach(this::countChar);
- }
- public int consumeChar(int c) {
- int questionMark = Character.getNumericValue('?');
- int counter = occurences.getOrDefault(c, 0);
- if(c == questionMark && counter <= 0) {
- return 1;
- }
- else if(counter <= 0) {
- return consumeChar(questionMark);
- }
- else {
- // of course some retard is going to change --var to var-- and get burned.
- occurences.put(c, --counter);
- return 0;
- }
- }
- public void countChar(int c) {
- if(!occurences.containsKey(c)) {
- occurences.put(c, 1);
- }
- else {
- occurences.put(c, occurences.get(c) + 1);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement