填字游戏:将一串字母分成字典中的有效单词

时间:2014-03-03 17:53:29

标签: regex perl dictionary crossword

鉴于:

  1. 删除空格并转换为小写的短语 - 例如“ashotinthearm”来自“一臂之力”;
  2. 如果一个单词存在(“a”,“as”,“ash”,“shot”,“hot”等),则返回true或false的字典将全部返回true)
  3. 找到单个单词的有效方法是什么?当用空格粘在一起时,这些单词组成了这个短语?

    可能有多个解决方案,即使有些是胡言乱语:

    • ashotinthearm(手臂一枪,手臂热)
    • asintended(按预期,如在倾向)
    • brothersinlaw(法律上的兄弟,兄弟罪法)
    • guysanddolls(男人和玩偶,男人沙娃娃)
    • hasascrewloose(螺丝松动,船员松动)
    • ifeelthepinch(我觉得捏,如果捏捏)
    • isinyourcourt(在你的法庭上,我在你的法庭上犯罪)
    • manorhouse(庄园,男人或房子)
    • manormouse(人或鼠,庄园鼠)
    • newzealand(新西兰,新热情和)
    • oneatatime(一次一个,吃一次)
    • portableradio(便携式无线电,可移植无线电)
    • scotspine(苏格兰松树,苏格兰脊柱)
    • shopsoiled(商店弄脏,商店上油)

    理想情况下更喜欢PERL和/或正则表达式解决方案,但感谢任何建议。

1 个答案:

答案 0 :(得分:1)

这个递归解决方案怎么样?

#!/usr/bin/perl -wW

use strict;

#global "constants"
my @words=("a", "as", "ash", "shot", "hot", "in", "the", "arm");
my %wordsHash = map { $_ => 1 } @words;

sub getParts($@);
sub dictionary($);

# returns true if in dict
sub dictionary($) {
    my ($str) = @_;
    return(defined($wordsHash{$str}));
}

# recursive function
sub getParts($@) {
    my ($phrase, @priorWords) = @_ ;
    print "DEBUG: step prior words(" . join(" ", @priorWords) . ") phrase($phrase) \n";

    #recursion end:
    if(!$phrase) {
        print "solution:" . join(" ", @priorWords) . "\n";
        return;
    }
    for my $i (1 .. length($phrase) ) {
        my $word = substr($phrase,0,$i);
        if(dictionary($word)) {
            getParts(substr($phrase,$i),(@priorWords,$word));
        }
    }
}

getParts("ashotinthearm", () );

输出是:

DEBUG: step prior words() phrase(ashotinthearm) 
DEBUG: step prior words(a) phrase(shotinthearm) 
DEBUG: step prior words(a shot) phrase(inthearm) 
DEBUG: step prior words(a shot in) phrase(thearm) 
DEBUG: step prior words(a shot in the) phrase(arm) 
DEBUG: step prior words(a shot in the a) phrase(rm) 
DEBUG: step prior words(a shot in the arm) phrase() 
solution:a shot in the arm
DEBUG: step prior words(as) phrase(hotinthearm) 
DEBUG: step prior words(as hot) phrase(inthearm) 
DEBUG: step prior words(as hot in) phrase(thearm) 
DEBUG: step prior words(as hot in the) phrase(arm) 
DEBUG: step prior words(as hot in the a) phrase(rm) 
DEBUG: step prior words(as hot in the arm) phrase() 
solution:as hot in the arm
DEBUG: step prior words(ash) phrase(otinthearm)