Untitled

mail@pastecode.io avatar
unknown
r
2 years ago
1.9 kB
2
Indexable
Never
library(rjson)
words <- fromJSON(file="words.json")
words <- words$solutions

rng <- 1:5

guess <- function(words)
{
  # Frequency by position
  freq_in_pos <- lapply(
    rng,
    function(n) table(
      factor(unlist(lapply(strsplit(words, ""), function(x) x[n])), levels=letters)
    )
  )
  
  freq_all <- table(unlist(strsplit(words, "")))
  
  freq_out_pos <- lapply(
    rng,
    function(n) (freq_all[[n]] - freq_in_pos[[n]]) / 4
  )
  
  weight <- Vectorize(function(word)
  {
    contents <- strsplit(word, "")[[1]] 
    sum(sapply(rng, function(n) freq_in_pos[[n]][contents[n]] + 
                                freq_out_pos[[n]][contents[n]])) 
  })
  
  result <- data.frame(row.names = NULL, word=words, weight=weight(words))
  result[order(result$weight, decreasing = TRUE),1]
}

cmd = ''
while(cmd != 'q')
{
  suggested <- guess(words)
  cat("Best guess: '", suggested[1], "' 1 of ", length(words), " possible\n", sep='')
  
  if(length(words) <= 1) {cmd <- 'q'; next;}
  
  cat("\nCommands are\n  'p' : print possible list.\n  'gyxxx' : 5 characters showing results of guess.\n  'q' : quit.\n\n")
  cmd <- readline("* ")
  
  if(cmd == 'q') next;
  if(cmd == 'p') {print(suggestedp); next;}
  if(!grepl("^[gyx]{5}$", "gyxxx", perl=TRUE)) {cat("Unrecognized command.\n\n"); next;}
  
  pieces <- strsplit(suggested[1], "")[[1]]
  results <- strsplit(cmd, "")[[1]]
  
  for(i in 1:5)
  {
    # Remaining dictionary must contain the letter in this position
    if(results[i] == 'g')
      words <- words[substr(words, i, i) == pieces[i]]
    
    # Remaining dictionary must not contain this letter at all
    if(results[i] == 'x')
      words <- words[!grepl(pieces[i], words)]
    
    # Remaining dictionary must contain the letter in a different position
    if(results[i] == 'y')
      words <- words[grepl(pieces[i], words) &
                     !substr(words, i, i) == pieces[i]]
  }
}