Categories
Algorithm

Sort hotel list challenge

Solution

public class SortHotelList {
    public static void main(String[] args) throws FileNotFoundException {
        System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in.txt"));
        Scanner in = new Scanner(System.in);

        // Read dictionary
        String[] words = in.nextLine().split(" ");
        Set dict = new HashSet();
        for (String word : words) {
            dict.add(word.toLowerCase());
        }

        // Read number of reviews
        int m = in.nextInt();

        // Read review
        Map hotel2count = new HashMap(); // hotel ID -> Word Count
        for (int i = 0; i < m; i++) {
            // Read hotel id
            int id = Integer.parseInt(in.next());
            in.nextLine();

            // Put id in map in case of new
            if (!hotel2count.containsKey(id)) {
                hotel2count.put(id, 0);
            }

            // Read review text
            String[] review = in.nextLine().split(" ");
            for (String word : review) {
                // Remove any ' ', ',', '.', '!' or '?' from word
                word = word.replaceAll("[$,.!?]", "").toLowerCase();
                if (dict.contains(word)) {
                    hotel2count.put(id, hotel2count.get(id) + 1);
                }
            }
        }

        // Sort
        List> sorted = new ArrayList(hotel2count.entrySet());
        Collections.sort(sorted, new Comparator>() {
            @Override
            public int compare(Map.Entry o1, Map.Entry o2) {
                if (o1.getValue() == o2.getValue()) {
                    return o1.getKey() - o2.getKey();
                } else {
                    return o2.getValue() - o1.getValue();
                }
            }
        });

        // Print sorted list
        for (Map.Entry hotelEntry : sorted) {
            System.out.print(hotelEntry.getKey() + " ");
        }
    }
}
'Coz sharing is caring

By Swatantra Kumar

Swatantra is an Open Source evangelist, a technologist and researcher. Professionally, he does software development, software architecture, server administration and project management. When he's not writing software, he enjoys building web entities and servers, reading about and working with new technologies, and trying to get his friends to make the move to open source software. He's written, co-written and published many articles in international journals, on various domains/topics including Open Source, Networks, Computer Organization, Mobile Technologies, and Business Intelligence. He made a proposal for an information management system at University level during graduation days.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.