【发布时间】:2021-04-06 15:49:55
【问题描述】:
我正在构建一个单词搜索游戏,并且正在寻找一种“R”方式来执行此表示的最后一行,这对于 2 个单词来说是微不足道的,但我希望它能够处理 n字。我在想*apply 函数之一可以在这里工作,但不知何故我无法解决。
library(tidyverse)
# Sample word list (173,000 words in reality)
words <- data.frame(word = c('test', 'word', 'active', 'angina', 'endite', 'endive', 'engine', 'entire', 'alanine', 'evening', 'escape', 'entered'),
word_length = c(4, 4, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7))
# Find a 6 letter word with 2nd letter n and a 7 letter word with letters 4 and 6 n
find <- '.n.... ...n.n.'
find_words <- unlist(str_split(find, ' '))
find_regex <- paste0('\\b', find_words, '\\b')
words %>%
filter(word_length == nchar(find_words[1])) %>%
filter(str_detect(word, find_regex[1])) %>%
full_join(
words %>%
filter(word_length == nchar(find_words[2])) %>%
filter(str_detect(word, find_regex[2]))
, by = character(), suffix = c('1', '2')) %>%
select(word1, word2)
另一个问题是做同样的事情,但数字代表未知字母,因为这会显着减少匹配
# Find a 6 letter word with 2nd letter n and a 7 letter word with letters 4 and 6 n
# where the 1st and 6th letters of the first word and 1st and 3rd letters of the second word are all the same (1 in find)
# and the 4th letter of the first word matches the 5th letter of the second word (3 in find)
find <- c('1n2341', '151n3n6')
# "Manual" solution
words %>%
filter(word_length == 6 & str_sub(word, 2, 2) == 'n') %>%
full_join(words %>% filter(word_length == 7 & str_sub(word, 4, 4) == 'n' & str_sub(word, 6, 6) == 'n'),
by = character(), suffix = c('1', '2')) %>%
# match letter represented by '1'
filter(str_sub(word1, 1, 1) == str_sub(word1, 6, 6)) %>%
filter(str_sub(word1, 1, 1) == str_sub(word2, 1, 1)) %>%
filter(str_sub(word1, 1, 1) == str_sub(word2, 3, 3)) %>%
# match letter represented by '3'
filter(str_sub(word1, 4, 4) == str_sub(word2, 5, 5)) %>%
select(word1, word2)
【问题讨论】:
-
对于您的进一步问题,它是否也需要泛化到许多单词,还是仅适用于对?而且还会跑上20万字的大名单吗?
-
@Alexlok,是的,它将在完整的单词列表中运行,理想情况下,我希望它被概括。