(UVA) Word Amalgamation - Solution

Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=583

For every word in the entry (dictionary or scrambled words), it is kept what characters compose each word and how many times they appear. In the end, for every scrambled word, it is checked if these information matches with one or more words in the dictionary. The approach used was grouping words that have the same amount of characters.


import java.io.*;
import java.util.*;

class Main {
    public static void process() throws NumberFormatException, IOException {
        Scanner sc = new Scanner(System.in);
       
        HashMap<HashMap<Character, Integer>, ArrayList<String>> words = new HashMap<>();
       
        String line = sc.next();
        while (!line.equals("XXXXXX")) {
            HashMap<Character, Integer> letters = new HashMap<>();
            // check which letters the word has
            for (int i = 0; i < line.length(); i++) {
                if (!letters.containsKey(line.charAt(i))) {
                    letters.put(line.charAt(i), 0);
                }
                letters.replace(line.charAt(i), letters.get(line.charAt(i))+1);
            }
            if (!words.containsKey(letters)) {
                words.put(letters, new ArrayList<String>());
            }
            ArrayList<String> w = words.get(letters);
            w.add(line);
            words.put(letters, w); // store the word and the map related to its letters
           
            line = sc.next();
        }
       
        line = sc.next();
        while (!line.equals("XXXXXX")) {
            HashMap<Character, Integer> scrambledWord = new HashMap<>();
            // check which letters the scrambled word has
            for (int i = 0; i < line.length(); i++) {
                if (!scrambledWord.containsKey(line.charAt(i))) {
                    scrambledWord.put(line.charAt(i), 0);
                }
                scrambledWord.replace(line.charAt(i), scrambledWord.get(line.charAt(i))+1);
            }
            ArrayList<String> list = words.get(scrambledWord);
            // retrieve the answer
            if (list == null) {
                System.out.println("NOT A VALID WORD");
            }
            else {
                Collections.sort(list);
                for (int i = 0; i < list.size(); i++) {
                    System.out.println(list.get(i));
                }
            }
                       
            System.out.println("******");
            line = sc.next();
        }
       
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
       
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução