【发布时间】:2021-06-14 07:52:17
【问题描述】:
我正在尝试在由 _ 和其他字母组成的字符串中生成输入字符的所有可能位置,其中输入字符只能替换 _ 代表的位置。
到目前为止我所做的代码在这里:
possibleNewWords currentString letterInput listOfPossibleStrings currentColumn iterations
| iterations == length currentString = removeDuplicates listOfPossibleStrings
| (currentColumn == length currentString) && (currentString!!iterations == '_') = possibleNewWords iteredString letterInput listOfPossibleStrings 0 (iterations+1)
| (currentColumn == length currentString) && (currentString!!iterations /= '_') = possibleNewWords currentString letterInput listOfPossibleStrings 0 (iterations+1)
| currentString!!currentColumn == '_' = possibleNewWords currentString letterInput (possibleStringNormal:listOfPossibleStrings) (currentColumn+1) iterations
| currentString!!currentColumn /= '_' = possibleNewWords currentString letterInput listOfPossibleStrings (currentColumn+1) iterations
where
possibleStringNormal = replaceInString currentColumn letterInput currentString
iteredString = replaceInString iterations letterInput currentString
possibleNewWordsBlank currentString letterInput listOfPossibleStrings currentColumn iterations
| iterations == length currentString = removeDuplicates listOfPossibleStrings
| (currentColumn == length currentString) && (currentString!!iterations == '_') = possibleNewWordsBlank iteredString letterInput listOfPossibleStrings 0 (iterations+1)
| (currentColumn == length currentString) && (currentString!!iterations /= '_') = possibleNewWordsBlank currentString letterInput listOfPossibleStrings 0 (iterations+1)
| (currentString!!currentColumn == '_') && (currentColumn > (iterations+1)) = possibleNewWordsBlank currentString letterInput (possibleStringNormal:listOfPossibleStrings) (currentColumn+1) iterations
| (currentString!!currentColumn /= '_') || (currentColumn <= (iterations+1)) = possibleNewWordsBlank currentString letterInput listOfPossibleStrings (currentColumn+1) iterations
where
possibleStringNormal = replaceInString currentColumn letterInput currentString
halfIteredString = replaceInString iterations '_' currentString
iteredString = replaceInString (iterations+1) letterInput currentString
顶部函数可以产生绝大多数可能性(它基本上在每个可用的下划线中放置一个输入字符,然后在字符串的第一个位置永久放置一个字符,重复该过程直到每个 _ 都被替换为输入字符),但我意识到它没有考虑诸如"_F_F_"之类的情况,所以我尝试编写第二个函数(possibleNewWordsBlank)并计划合并结果并删除最终集的重复项,但我无法得到剩余的要输出的潜在组合。那时我意识到我可能错误地处理了整个问题,并认为寻求帮助是谨慎的做法。
我想要做的一个例子是,如果我们试图找到"____" 的所有可能性并且输入字符是'F',那么["____", "F___", "_F__", "__F_", "___F", "FF__", "F_F_", "F__F", "FFF_", "FF_F", "FFFF", "_FFF", "_FF_", "_F_F", "__FF", "F_FF"] 将被输出。我曾想过尝试从我的第一个函数输出中反转字符串,但意识到这并不能涵盖较大 n 的所有情况。
我尝试以方式处理预先存在的字母的一个示例是"__F_W",其中输入字符为“G”将输出["G_F_W", "_GF_W", "__FGW", "GGF_W", "G_FGW", "GGFGW", "_GFGW", "__F_W"]
【问题讨论】:
标签: string list haskell recursion filter