library(data.table)

expedia_train <- fread('../input/train.csv', header=TRUE)
expedia_test <- fread('../input/test.csv', header=TRUE)

test <- expedia_test

top_n <- function(hc, v1, minVal = 5) {
  hc_sorted <- hc[order(v1, decreasing = T)]
  n <- min(minVal, length(hc_sorted))
  paste(hc_sorted[1:n], collapse = " ")
}

hotel_popularity <- expedia_train[,length(is_booking),by=list(hotel_market, srch_destination_id, hotel_cluster)]
market_top_n <-
  hotel_popularity[, top_n(hotel_cluster, V1), by = hotel_market]
  
market_destination_top_n <-
  hotel_popularity[, top_n(hotel_cluster, V1), by = list(hotel_market, srch_destination_id)]
  
res1<-merge(x=market_destination_top_n, y = expedia_test,by=c('hotel_market','srch_destination_id'), all.y=T)[, list(id, V1, hotel_market)]
remain<-res1[which(is.na(res1$V1)),]
remain$V1<-NULL
res1<-res1[which(!is.na(res1$V1)),]
res2<- merge(x=market_top_n, y=remain, by = "hotel_market")[, list(id, V1)]
res1$hotel_market<-NULL
output<-rbind(res1, res2)
names(output)[names(output)=='V1']<-"hotel_cluster"
write.csv(output, file = 'submission.csv', row.names = F)