predict_word_live <- function(ngram_list, previous_string) {
highest_order_ngram <- length(ngram_list)
previous_words <- str_split(previous_string," ")[[1]]
str_len <- length(previous_words)
begin_index <- str_len+1
if(begin_index > highest_order_ngram) { begin_index <- highest_order_ngram}
for(i in begin_index:2){
curr_text <- paste0(previous_words[abs(str_len-i+2):str_len],collapse=" ")
search_string <- paste0("^", curr_text,collapse=" ")
candidates <- ngram_list[[i]][grep(search_string, ngram_list[[i]]$ngrams),1]
length_candidates <- length(candidates)
if(length_candidates>0)
{
if (length_candidates >= 4) {
next_word <- str_split(candidates[1:4]," ")
}
else{
next_word <- str_split(candidates[1:length_candidates]," ")
}
result <- lapply(next_word,function(x){x[begin_index]})
result <- replace(result, is.na(result), "")
return(result)
}
}
return(sample(ngram_list[[1]]$ngrams[1:100], 4))
}