Booking.com Interview Question for Software Engineer / Developers


Country: India
Interview Type: Written Test




Comment hidden because of low score. Click to expand.
3
of 3 vote

import java.util.*;

public class HotelReviews {

    public static void main(String[] args) {

        List<String> query = new ArrayList(Arrays.asList("good", "shit"));
        TreeSet<Rating> chart = new TreeSet();
        Map<Integer, List<String>> reviews = new HashMap();
        reviews.put(1, new ArrayList(Arrays.asList("good", "great", "awesome", "good")));
        reviews.put(2, new ArrayList(Arrays.asList("nasty", "shit", "disgusting")));
        reviews.put(3, new ArrayList(Arrays.asList("moderate", "good", "shit")));

        for(Map.Entry<Integer, List<String>> entry : reviews.entrySet()){
            List<String> description = new ArrayList(entry.getValue());
            description.retainAll(query);
            chart.add(new Rating(entry.getKey(), description.size()));
        }

        for(Rating rating : chart){
            System.out.println("hotel: " + rating.hotelId + ", rating: " + rating.rating);
        }

    }

    static class Rating implements Comparable{
        int hotelId;
        int rating;
        public Rating(int hotelId, int rating){
            this.hotelId = hotelId;
            this.rating = rating;
        }

        public int compareTo(Object other){
            Rating otherRating = (Rating) other;
            return 2 * Integer.compare(otherRating.rating, this.rating) + Integer.compare(this.hotelId, otherRating.hotelId);
        }
    }

}

- Anatolii June 28, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

import java.util.HashSet;
import java.util.Map;
import java.util.Comparator;
import java.util.HashMap;
import java.util.TreeMap;
// These guys are needed for searching and counting how many times the word appears in review
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Mentions {
	// Let's create a HashSet to store the words we want to find
	static HashSet<String> wordsToSearch = new HashSet<String>();
	// The final HashMap, it will include hotel IDs and mentions
	static Map<Integer,Integer> hotels = new HashMap<Integer,Integer>();
	
	private static String[] createDummyData(){
		String[] dummyData = {
				// First line,space-separated set of words
				"price accommodation view low best",
				// Second line, one integer which is the number of reviews
				"4",
				// From this point, we need to have as many hotel IDs and Reviews as we defined in the line above
				// Hotel ID->1
				"1", 
				// Review for Hotel ID->1
				"Do not make a reservation in this hotel even if has low low low price low price",
				// Hotel ID->2
				"2",
				// Review for Hotel ID->1
				"Great view and accommodation, best option for the price price price",				
				// Hotel ID->3
				"3",
				// Review for Hotel ID->3
				"Great view and accommodation, best option for the price",
				// Hotel ID->4
				"4",
				// Review for Hotel ID->4
				"Best option for the price price price price"
		};		
		return dummyData;
	}
	private static void fillWordsToSearch(String[] words){
		for(int i=0; i<words.length; i++){
			String word = words[i];
			// Add to our HashSet
			wordsToSearch.add( word.toLowerCase() );
		}		
	}
	private static void fillHotels(Integer totalReviews, String[] reviews){		
		for (int i=1; i<=(totalReviews*2); i+=2){
			int hotelId = Integer.parseInt( reviews[i+1] );
			int hotelReviews = countWords( reviews[i+2] );			
			hotels.put( hotelId, hotelReviews );
		}
	}
	private static Map<Integer, Integer> sortHotelsByReviews(final Map<Integer, Integer> map) {
        Comparator<Integer> valueComparator =  new Comparator<Integer>() {
            public int compare(Integer k1, Integer k2) {
                int compare = map.get(k2).compareTo(map.get(k1));
                if (compare == 0) return 1;
                else return compare;
            }
        };
        Map<Integer, Integer> sortedByValues = new TreeMap<Integer, Integer>(valueComparator);
        sortedByValues.putAll(map);
        return sortedByValues;
    }
	private static void showHotelList(){		
		Map<Integer,Integer> sortedHotels = sortHotelsByReviews(hotels);		
		for(Integer hotelId : sortedHotels.keySet() ){
			System.out.println( "Hotel ID->" + hotelId + ", reviews " + hotels.get(hotelId) );
		}
	}
	private static int countWords(String review){
		int counter = 0;		
		for(String word : wordsToSearch ){
			Pattern pattern = Pattern.compile(word);
			Matcher matcher = pattern.matcher(review.toLowerCase());
			while( matcher.find() ){
				counter++;
			}
		}				
		return counter;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// If line arguments are empty, let's create some dummy data
		if( args.length==0 ){
			args = createDummyData();
		}
		// Fill HashSet
		String[] words = args[0].split(" ");
		fillWordsToSearch(words);		
		int totalReviews = Integer.parseInt(args[1]);
		fillHotels( totalReviews, args );
		showHotelList();				
	}

}

- Julio Molinero May 31, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hotels_guest_reviews_analysis
{
class Review
{
public string HotelName;
public string Revieww;
}
class Score
{
public string HotelName;
public int score;
}
class Program
{

static List<Score> Scores = new List<Score>();
static void Main(string[] args)
{
string[] BadWords = Console.ReadLine().Split(' ');
string endChar = "";
List<Review> Reviews = new List<Review>();
while (endChar != "===")
{
string r = Console.ReadLine();
if (r == "===")
{
endChar = "===";
break;
}
else
{
string[] RV = r.Split('+');
Review rev = new Review();
rev.HotelName = RV[0];
rev.Revieww = RV[1];
Reviews.Add(rev);
AddHotelToScores(rev.HotelName);
}
}
foreach (Review r in Reviews)
{
int BadW = FindArrayInString(r.Revieww, BadWords);
IncreaseHotelScore(r.HotelName, BadW);
}
List<Score> OrderedScores = Scores.OrderBy(o => o.score).ToList();
foreach (Score s in OrderedScores)
{
Console.WriteLine(s.HotelName + ":" + s.score);
}
Console.ReadLine();
}
public static void AddHotelToScores(string HotelName )
{
bool exist = false ;
foreach (Score a in Scores)
{
if (HotelName == a.HotelName)
{
exist = true;
}
}
if (exist == false)
{
Score n = new Score();
n.HotelName = HotelName;
n.score = 0;
Scores.Add(n);
}
}
public static void IncreaseHotelScore(string HotelName, int Increase)
{
foreach (Score a in Scores)
{
if (HotelName == a.HotelName)
{
a.score += Increase;
}
}
}
public static int FindArrayInString(string main, string[] Words)
{
int Count = 0;
foreach (string word in Words)
{
if (main.Contains(word) != false)
{
Count++;
}
}
return Count;
}
}
}

- Omar Mer April 30, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;

public class HotelReviews {

    public static void main(String[] args) {

        List<String> query = new ArrayList(Arrays.asList("good", "shit"));
        TreeSet<Rating> chart = new TreeSet();
        Map<Integer, List<String>> reviews = new HashMap();
        reviews.put(1, new ArrayList(Arrays.asList("good", "great", "awesome", "good")));
        reviews.put(2, new ArrayList(Arrays.asList("nasty", "shit", "disgusting")));
        reviews.put(3, new ArrayList(Arrays.asList("moderate", "good", "shit")));

        for(Map.Entry<Integer, List<String>> entry : reviews.entrySet()){
            List<String> description = new ArrayList(entry.getValue());
            description.retainAll(query);
            chart.add(new Rating(entry.getKey(), description.size()));
        }

        for(Rating rating : chart){
            System.out.println("hotel: " + rating.hotelId + ", rating: " + rating.rating);
        }

    }

    static class Rating implements Comparable{
        int hotelId;
        int rating;
        public Rating(int hotelId, int rating){
            this.hotelId = hotelId;
            this.rating = rating;
        }

        public int compareTo(Object other){
            Rating otherRating = (Rating) other;
            return 2 * Integer.compare(otherRating.rating, this.rating) + Integer.compare(this.hotelId, otherRating.hotelId);
        }
    }

}

- Anatolii June 28, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;

public class HotelReviews {

    public static void main(String[] args) {

        List<String> query = new ArrayList(Arrays.asList("good", "shit"));
        TreeSet<Rating> chart = new TreeSet();
        Map<Integer, List<String>> reviews = new HashMap();
        reviews.put(1, new ArrayList(Arrays.asList("good", "great", "awesome", "good")));
        reviews.put(2, new ArrayList(Arrays.asList("nasty", "shit", "disgusting")));
        reviews.put(3, new ArrayList(Arrays.asList("moderate", "good", "shit")));

        for(Map.Entry<Integer, List<String>> entry : reviews.entrySet()){
            List<String> description = new ArrayList(entry.getValue());
            description.retainAll(query);
            chart.add(new Rating(entry.getKey(), description.size()));
        }

        for(Rating rating : chart){
            System.out.println("hotel: " + rating.hotelId + ", rating: " + rating.rating);
        }

    }

    static class Rating implements Comparable{
        int hotelId;
        int rating;
        public Rating(int hotelId, int rating){
            this.hotelId = hotelId;
            this.rating = rating;
        }

        public int compareTo(Object other){
            Rating otherRating = (Rating) other;
            return 2 * Integer.compare(otherRating.rating, this.rating) + Integer.compare(this.hotelId, otherRating.hotelId);
        }
    }

}

- Anatolii.Stepaniuk June 28, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

My solution is O(h * k)
(h is hotel or reviews, k is keywords)

def sort_hotels(hotels, search_keywords):
    hotels_point = {}

    for hotel_id in range(0, len(hotels)):
        hotel = hotels[hotel_id]
        point = 0
        for keyword in search_keywords:
            point += hotel.count(keyword)

        hotels_point[hotel_id] = point

    return [x[0] for x in sorted(hotels_point.items(), key=lambda x: (x[1], x[0]), reverse=True)]

Test code

def test(self):
    hotels = [
        'Do not make a reservation in this hotel even if has low low low price low price',
        'Great view and accommodation, best option for the price price price',
        'Great view and accommodation, best option for the price',
        'Best option for the price price price price'
    ]

    search_keywords = [
        'price',
        'accommodation',
        'view',
        'low',
        'best'
    ]

    self.assertTrue([1, 0, 3, 2], sort_hotels(hotels, search_keywords))

- reaperes July 09, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

We can use Priority Queue to store the object which contains Hotel Id and number of words occurred in its review.
The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.
Natural Ordering will be dependent first on no (no of words occurred in hotel's review) and secondly on hotel ID.
I'll upload the code in a while :)
Cheers

- Harshil August 09, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.company;

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] searchWords = scanner.nextLine().split(" ");

        int count = scanner.nextInt();

        int hotelId;
        Map<Integer, ArrayList<String>> hotelReviewWordsMap = new HashMap<>();


        String review;
        while (count>0) {
            count--;

            hotelId = scanner.nextInt();
            scanner.nextLine();

            review = scanner.nextLine();
            review = review.replaceAll("\\.|,|!|\\?", "");

            String[] reviewWords = review.split("\\s+");

            ArrayList<String> reviewWordsList = new ArrayList<>();
            if (hotelReviewWordsMap.containsKey(hotelId)){
                reviewWordsList = hotelReviewWordsMap.get(hotelId);
            }

            reviewWordsList.addAll(Arrays.asList(reviewWords));
            hotelReviewWordsMap.put(hotelId, reviewWordsList);
        }

        Map<Integer, Hotel> result = new HashMap<>();

        for (String s: searchWords) {
            for (Integer hotel : hotelReviewWordsMap.keySet()) {
                ArrayList<String> list = hotelReviewWordsMap.get(hotel);
                for (String aList : list) {
                    if (aList.equalsIgnoreCase(s)) {

                        if (result.containsKey(hotel)) {
                            Hotel hotelObject = result.get(hotel);
                            hotelObject.updateRating();
                            result.put(hotel, hotelObject);
                        } else {

                            result.put(hotel, new Hotel(hotel, 1));
                        }
                    }
                }
            }
        }

        TreeSet<Hotel> set = new TreeSet<>(result.values());

        for (Hotel hotel: set){
            System.out.print(hotel.getId() + " ");
        }

        System.out.println();
    }

    public static class Hotel implements Comparable<Hotel> {
        private int id;
        private int rating;

        Hotel(int id, int rating) {
            this.id = id;
            this.rating = rating;
        }

        int getId() {
            return id;
        }

        int getRating() {
            return rating;
        }

        void updateRating(){
            this.rating++;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Hotel hotel = (Hotel) o;

            return id == hotel.id;
        }

        @Override
        public int hashCode() {
            return id;
        }

        @Override
        public int compareTo(Hotel o) {

            if (this.getRating() > o.getRating())
                return -1;
            else if (this.getRating() < o.getRating())
                return 1;
            else{
                if (this.getId() > o.getId())
                    return -1;
                else if(this.getId() < o.getId())
                    return 1;
            }

            return 0;
        }
    }
}

- vfizuli August 28, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*
Given a set of hotels and its guests reviews, sort the hotels based on a list of words specified by a user. The criteria to sort the hotels should be how many times the words specified by the user is mentioned in the hotel reviews. 

Input 
The first line contains a space-separated set of words which we want to find mentions in the hotel reviews. 
The second line contains one integer M, which is the number of reviews. 
This is followed by M+M lines, which alternates an hotel ID and a review belonging to that hotel. 

Output 
A list of hotel IDs sorted, in descending order, by how many mentions they have of the words specified in the input. If the count is same, sort according to the hotel IDs.

===> Sample input at the end of this code
*/

import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.regex.*;

class GFG {
	public static void main (String[] args) {
		Scanner scan = new Scanner(System.in);
		scan.useDelimiter("[;\r\n]+");
		
		HashMap<Integer, Integer> hotelsByReviewReference = new HashMap<Integer, Integer>();
		
		String words = scan.nextLine().replaceAll("\\s+", "|");
        Pattern wordsRegex = Pattern.compile("(" + words + ")");
        
		int numberOfReviews = scan.nextInt();
		for(int i = 0; i < numberOfReviews; i++) {
		    int hotelId = scan.nextInt();
		    scan.nextLine();
		    String review = scan.nextLine();
		    
		    Integer numberOfReferences = hotelsByReviewReference.get(hotelId);
		    if(numberOfReferences == null) {
		        numberOfReferences = 0;
		    }
		    
		    Matcher m = wordsRegex.matcher(review);
            while (m.find()) {
                numberOfReferences++;
            }
		    
		    hotelsByReviewReference.put(hotelId, numberOfReferences);
		}
		
		Map<Integer, Integer> sortedMap = new TreeMap<Integer, Integer>(
		    new Comparator<Integer>() {
                public int compare(Integer k1, Integer k2) {
                    Integer v1 = hotelsByReviewReference.get(k1);
                    Integer v2 = hotelsByReviewReference.get(k2);
                    if(v1.equals(v2)) {
                        return k1.compareTo(k2);
                    } else {
                        return v2.compareTo(v1);
                    }
                }
		    }
        );
        sortedMap.putAll(hotelsByReviewReference);
        
		for(Integer hotelId : sortedMap.keySet()) {
		    System.out.println("Hotel " + hotelId + " -> " + hotelsByReviewReference.get(hotelId));
		}
	}
}

/*
nice lovely near
14
1
Maids were nice, most good, but room usually not cleaned until 5 pm. Tough if you wanted to rest before going out later.
2
Overall, the suite was a nice space. We had a corner room with a view of the square. Not as noisy as others reported due to multi-paned Windows.
1
No option of a late checkout, 2 single beds instead of a double
3
Staff were very helpful at our departure we were allowed to leave our bags for a full day and the hotel ordered a taxi for us without even having to ask, very good service
5
What was really super annoying was that the guy from cleaning was tapping at my door with a key for 10 minutes (around 11), and waking me up, check-out is at 12 I really did not understand this action. And was not pleased at all.
3
Dear Amber, Thank you for taking the time to share your experiences. We are happy to read you enjoyed your stay in our hotel and found our location convenient for your stay. We will take your comments concerning our cleaning guy into consideration, as we strive to continuously improve the quality of our hotel. We hope to welcome you again in the future. Kind regards, Patricia
2
The carpet that was not hoovered and I would have liked to have an iron and iron board in the room but overall highly recommended. I would consider to change the sign of the hotel name as it is not very visible
1
The breakfast was fantastic, very professional and welcoming staff.  the location is very central and close to all the trams restaurants and cafes. The bed is extremely comfortable and the bathroom is clean and well designed
2
Staff not knowledgeable about attractions and the age limits for entry.
4
Just before I departed the hotel for my journey home, I had collected my luggage from the luggage storage. The concierge who assisted me and my friends was lovely. However, as I fixed my case (crouched down as it was on the floor) another concierge appeared and talked to me in an extremely patronising and condescending way. He was asking me to get off the floor but instead of simply asking, he told me how "you know, it doesn't look very nice". Even after I told him I was just fixing my bag he then directed me to the nearby table.. Which looked like an antique check in desk with a computer on it! Needless to say, I was disgusted with his treatment of me. I was also so disappointed as it was just as I was preparing to leave. He was dismissive and rude even when it was clear I wasn't "lounging" on the floor.. I was crouched over my suitcase!
5
The rooms were really lovely and comfortable! Also the main tram lines were a stones throw away.. Couldn't have been any better! The Rembrandt Square itself was an amazing asset to the hotel. Even if you weren't in the main hub (around the Dam stop or the Centraal), the Rembrandt Square was filled with restaurants
2
That it's labelled a 4 star hotel when it's not and over priced but then again most hotels are in Amsterdam now.
3
The hotel make you sign multiple no-smoking declarations then the first room we were given was riddled with smoke!
5
Location, big rooms, mostly the staff was smiling and helpfull, over all clean rooms, free coffee machine in the room. All in all a nice hotel, we got what we expected, and if we ever go to Amsterdam again we will certainly consider staying here again. 
*/

- Alex March 19, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*
Given a set of hotels and its guests reviews, sort the hotels based on a list of words specified by a user. The criteria to sort the hotels should be how many times the words specified by the user is mentioned in the hotel reviews. 

Input 
The first line contains a space-separated set of words which we want to find mentions in the hotel reviews. 
The second line contains one integer M, which is the number of reviews. 
This is followed by M+M lines, which alternates an hotel ID and a review belonging to that hotel. 

Output 
A list of hotel IDs sorted, in descending order, by how many mentions they have of the words specified in the input. If the count is same, sort according to the hotel IDs.

===> Sample input at the end of this code
*/

import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.regex.*;

class GFG {
	public static void main (String[] args) {
		Scanner scan = new Scanner(System.in);
		scan.useDelimiter("[;\r\n]+");
		
		HashMap<Integer, Integer> hotelsByReviewReference = new HashMap<Integer, Integer>();
		
		String words = scan.nextLine().replaceAll("\\s+", "|");
        Pattern wordsRegex = Pattern.compile("(" + words + ")");
        
		int numberOfReviews = scan.nextInt();
		for(int i = 0; i < numberOfReviews; i++) {
		    int hotelId = scan.nextInt();
		    scan.nextLine();
		    String review = scan.nextLine();
		    
		    Integer numberOfReferences = hotelsByReviewReference.get(hotelId);
		    if(numberOfReferences == null) {
		        numberOfReferences = 0;
		    }
		    
		    Matcher m = wordsRegex.matcher(review);
            while (m.find()) {
                numberOfReferences++;
            }
		    
		    hotelsByReviewReference.put(hotelId, numberOfReferences);
		}
		
		Map<Integer, Integer> sortedMap = new TreeMap<Integer, Integer>(
		    new Comparator<Integer>() {
                public int compare(Integer k1, Integer k2) {
                    Integer v1 = hotelsByReviewReference.get(k1);
                    Integer v2 = hotelsByReviewReference.get(k2);
                    if(v1.equals(v2)) {
                        return k1.compareTo(k2);
                    } else {
                        return v2.compareTo(v1);
                    }
                }
		    }
        );
        sortedMap.putAll(hotelsByReviewReference);
        
		for(Integer hotelId : sortedMap.keySet()) {
		    System.out.println("Hotel " + hotelId + " -> " + hotelsByReviewReference.get(hotelId));
		}
	}
}

/*
nice lovely near
14
1
Maids were nice, most good, but room usually not cleaned until 5 pm. Tough if you wanted to rest before going out later.
2
Overall, the suite was a nice space. We had a corner room with a view of the square. Not as noisy as others reported due to multi-paned Windows.
1
No option of a late checkout, 2 single beds instead of a double
3
Staff were very helpful at our departure we were allowed to leave our bags for a full day and the hotel ordered a taxi for us without even having to ask, very good service
5
What was really super annoying was that the guy from cleaning was tapping at my door with a key for 10 minutes (around 11), and waking me up, check-out is at 12 I really did not understand this action. And was not pleased at all.
3
Dear Amber, Thank you for taking the time to share your experiences. We are happy to read you enjoyed your stay in our hotel and found our location convenient for your stay. We will take your comments concerning our cleaning guy into consideration, as we strive to continuously improve the quality of our hotel. We hope to welcome you again in the future. Kind regards, Patricia
2
The carpet that was not hoovered and I would have liked to have an iron and iron board in the room but overall highly recommended. I would consider to change the sign of the hotel name as it is not very visible
1
The breakfast was fantastic, very professional and welcoming staff.  the location is very central and close to all the trams restaurants and cafes. The bed is extremely comfortable and the bathroom is clean and well designed
2
Staff not knowledgeable about attractions and the age limits for entry.
4
Just before I departed the hotel for my journey home, I had collected my luggage from the luggage storage. The concierge who assisted me and my friends was lovely. However, as I fixed my case (crouched down as it was on the floor) another concierge appeared and talked to me in an extremely patronising and condescending way. He was asking me to get off the floor but instead of simply asking, he told me how "you know, it doesn't look very nice". Even after I told him I was just fixing my bag he then directed me to the nearby table.. Which looked like an antique check in desk with a computer on it! Needless to say, I was disgusted with his treatment of me. I was also so disappointed as it was just as I was preparing to leave. He was dismissive and rude even when it was clear I wasn't "lounging" on the floor.. I was crouched over my suitcase!
5
The rooms were really lovely and comfortable! Also the main tram lines were a stones throw away.. Couldn't have been any better! The Rembrandt Square itself was an amazing asset to the hotel. Even if you weren't in the main hub (around the Dam stop or the Centraal), the Rembrandt Square was filled with restaurants
2
That it's labelled a 4 star hotel when it's not and over priced but then again most hotels are in Amsterdam now.
3
The hotel make you sign multiple no-smoking declarations then the first room we were given was riddled with smoke!
5
Location, big rooms, mostly the staff was smiling and helpfull, over all clean rooms, free coffee machine in the room. All in all a nice hotel, we got what we expected, and if we ever go to Amsterdam again we will certainly consider staying here again. 
*/

- Alex March 19, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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<String> dict = new HashSet<String>();
for (String word : words) {
dict.add(word.toLowerCase());
}

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

// Read review
Map<Integer, Integer> hotel2count = new HashMap<Integer, Integer>(); // 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<Map.Entry<Integer, Integer>> sorted = new ArrayList(hotel2count.entrySet());
Collections.sort(sorted, new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
if (o1.getValue() == o2.getValue()) {
return o1.getKey() - o2.getKey();
} else {
return o2.getValue() - o1.getValue();
}
}
});

// Print sorted list
for (Map.Entry<Integer, Integer> hotelEntry : sorted) {
System.out.print(hotelEntry.getKey() + " ");
}
}
}

- Anonymous April 29, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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<String> dict = new HashSet<String>();
        for (String word : words) {
            dict.add(word.toLowerCase());
        }
 
        // Read number of reviews
        int m = in.nextInt();
 
        // Read review
        Map<Integer, Integer> hotel2count = new HashMap<Integer, Integer>(); // 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<Map.Entry<Integer, Integer>> sorted = new ArrayList(hotel2count.entrySet());
        Collections.sort(sorted, new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                if (o1.getValue() == o2.getValue()) {
                    return o1.getKey() - o2.getKey();
                } else {
                    return o2.getValue() - o1.getValue();
                }
            }
        });
 
        // Print sorted list
        for (Map.Entry<Integer, Integer> hotelEntry : sorted) {
            System.out.print(hotelEntry.getKey() + " ");
        }
    }

}

- Sumit Saha April 29, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int main()
{
    string line;
    getline(cin, line);
    istringstream ss(line);
    unordered_set<string> keywords;
    string word;
    while (ss >> word)
    {
        transform(cbegin(word), cend(word), begin(word), tolower);
        keywords.emplace(word);
    }

    unordered_map<int, int> hotel_keywords_count;
    int review_count;
    cin >> review_count;
    int hotel_id;
    for (int i = 0; i < review_count; ++i)
    {
        cin >> hotel_id;
        int& keywords_count = hotel_keywords_count[hotel_id];
        cin.ignore();
        getline(cin, line);
        ss.clear();
        ss.str(line);
        while (ss >> word)
        {
            transform(cbegin(word), cend(word), begin(word), tolower);
            regex e("[^[:alpha:]]");
            word = regex_replace(word, e, "");
            if (keywords.find(word) != cend(keywords))
                ++keywords_count;
        }
    }

    list<pair<int, int>> hotels_list;
    copy(cbegin(hotel_keywords_count), cend(hotel_keywords_count), back_inserter(hotels_list));
    hotels_list.sort([](const pair<int, int>& p1, const pair<int, int>& p2){
        if (p1.second == p2.second)
            return p1.first < p2.first;
        return p1.second > p2.second;
    });

    for (auto& item : hotels_list)
        cout << item.first << " ";
    cout << endl;
}

- shayan.eftekhari April 04, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import re
import operator

class SortHotelsOnWordFrequency:
	def compressValuesOfMap(self, hotel_map_with_count):
		compressed_hotel_map = {}

		for hotel_id, hotel_map in hotel_map_with_count.items():
			total_freq = 0
			for word, freq in hotel_map.items():
				total_freq += freq
			compressed_hotel_map[hotel_id] = total_freq
		return compressed_hotel_map


	def getHotelsWithCount(self, hotel_map, words):
		hotel_map_with_count = {}
		for hotel_id, reviews in hotel_map.items():
			map_word_count = {}
			for word in words:
				for review in reviews:
					for r in review:
						if r.lower() == word:
							if word in map_word_count:
								map_word_count[word]+=1
							else:
								map_word_count[word]=1
			hotel_map_with_count[hotel_id] = map_word_count
		return hotel_map_with_count



	def parseFile(self, input_file):
		file  = open(input_file, "r")
		lines = file.readlines()
		words = lines[0].strip("\n").split(" ")
		m     = int(lines[1])
		hotel_map = {}

		for i in range(2,m*2+2,2):
			hotel_id = int(lines[i])
			reviews  = re.sub(r'[^\w\s]','',lines[i+1].strip("\n")).split(" ")
			if hotel_id in hotel_map:
				hotel_map[hotel_id].append(reviews)
			else:
				hotel_map[hotel_id] = []
				hotel_map[hotel_id].append(reviews)
			
		hotel_map_with_count = self.getHotelsWithCount(hotel_map, words)
		compressed_hotel_map = self.compressValuesOfMap(hotel_map_with_count)
		sorted_hotels_tuples = sorted(compressed_hotel_map.items(), key=operator.itemgetter(1), reverse=True) 
		sorted_hotels 		 = []
		for hotel_tuple in sorted_hotels_tuples:
			sorted_hotels.append(hotel_tuple[0])
		return sorted_hotels


sort_hotels = SortHotelsOnWordFrequency()
print(sort_hotels.parseFile("reviews.txt"))

- Saurabh September 19, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import re
import operator

class SortHotelsOnWordFrequency:
	def compressValuesOfMap(self, hotel_map_with_count):
		compressed_hotel_map = {}

		for hotel_id, hotel_map in hotel_map_with_count.items():
			total_freq = 0
			for word, freq in hotel_map.items():
				total_freq += freq
			compressed_hotel_map[hotel_id] = total_freq
		return compressed_hotel_map


	def getHotelsWithCount(self, hotel_map, words):
		hotel_map_with_count = {}
		for hotel_id, reviews in hotel_map.items():
			map_word_count = {}
			for word in words:
				for review in reviews:
					for r in review:
						if r.lower() == word:
							if word in map_word_count:
								map_word_count[word]+=1
							else:
								map_word_count[word]=1
			hotel_map_with_count[hotel_id] = map_word_count
		return hotel_map_with_count



	def parseFile(self, input_file):
		file  = open(input_file, "r")
		lines = file.readlines()
		words = lines[0].strip("\n").split(" ")
		m     = int(lines[1])
		hotel_map = {}

		for i in range(2,m*2+2,2):
			hotel_id = int(lines[i])
			reviews  = re.sub(r'[^\w\s]','',lines[i+1].strip("\n")).split(" ")
			if hotel_id in hotel_map:
				hotel_map[hotel_id].append(reviews)
			else:
				hotel_map[hotel_id] = []
				hotel_map[hotel_id].append(reviews)
			
		hotel_map_with_count = self.getHotelsWithCount(hotel_map, words)
		compressed_hotel_map = self.compressValuesOfMap(hotel_map_with_count)
		sorted_hotels_tuples = sorted(compressed_hotel_map.items(), key=operator.itemgetter(1), reverse=True) 
		sorted_hotels 		 = []
		for hotel_tuple in sorted_hotels_tuples:
			sorted_hotels.append(hotel_tuple[0])
		return sorted_hotels


sort_hotels = SortHotelsOnWordFrequency()
print(sort_hotels.parseFile("reviews.txt"))

- saurabh September 19, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/**
     * @author Omid Ghiasi Tarzi
     */
    List<Integer> getPopulars(Map<Integer,Set<String>> reviews, Set<String> keyWords){
        Map<Integer,Integer> scores=new HashMap<>();
        for(int hotel:reviews.keySet()){
            Set<String> review=new HashSet<>(reviews.get(hotel));
            review.retainAll(keyWords);
            scores.put(hotel,review.size());
        }
        return scores.entrySet().stream()
                     .sorted(Comparator.comparing(Map.Entry::getKey))
                     .sorted((e1,e2)->e2.getValue()-e1.getValue())
                     .map(Map.Entry::getKey)
                     .collect(Collectors.toList());
    }

- omid095 October 12, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
	    List<String> query = new ArrayList<String>(Arrays.asList("good","bad"));
	    Map<Integer,Integer> result = new HashMap<Integer,Integer>();
	    Map<Integer,List<String>> reviews = new HashMap<Integer, List<String>>();
	    reviews.put(1, new ArrayList<String>(Arrays.asList("good", "great", "awesome", "good")));
	    reviews.put(2, new ArrayList<String>(Arrays.asList("nasty", "bad", "disgusting")));
	    reviews.put(3, new ArrayList<String>(Arrays.asList("moderate", "good", "bad")));
	    
	    for(Map.Entry<Integer, List<String>> entry: reviews.entrySet()) {
	    	List<String> description = new ArrayList<String>(entry.getValue());
	    	description.retainAll(query);
	    	result.put(entry.getKey(),description.size());
	    	
	    }
	    Map<Integer,Integer> sortMap = sortByValue(result);
	    for(Map.Entry<Integer,Integer> rating : sortMap.entrySet()) {
	    	 System.out.println("hotel: " + rating.getKey() + ", rating: " + rating.getValue());        
	    }
	 }
	 
	 static HashMap<Integer,Integer> sortByValue(Map<Integer, Integer> unsortedMap){
		 
		 LinkedHashMap<Integer,Integer> sortedMap = new LinkedHashMap<>();
		 unsortedMap.entrySet()
					 .stream()
					 .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
					 .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
					 
		 return (HashMap<Integer, Integer>) sortedMap;
		 
	 }

- Tomas March 17, 2021 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More