【问题标题】:Comparing two strings for Anagram using hash [closed]使用哈希比较 Anagram 的两个字符串 [关闭]
【发布时间】:2019-08-15 02:04:23
【问题描述】:

我是 perl 新手。任何人都可以举一个perl代码的例子来检测使用哈希的给定字符串之间的字谜。两个字符串 - 游泳池和马球。

【问题讨论】:

  • 非常感谢您的帮助。罗塞塔代码:字谜对我来说似乎很复杂。你能告诉我一些基本语法的源代码吗?
  • 不客气。罗塞塔代码看起来很简单,请解释一下代码的哪一部分你不明白。您还可以查看Word::Anagram 模块的源代码。你可以找到它here

标签: perl hash anagram


【解决方案1】:
sub key(_) { join "", sort split //, $_[0] }

if (key("pool") eq key("polo") {
   say "Pool and polo are anagrams of each other.";
} else {
   say "Pool and polo aren't anagrams of each other.";
}

如果你有一本字典,

sub key(_) { join "", sort split //, $_[0] }

my $dict_qfn = "...";
my $search = "pool";

my %anagrams;
{
   open(my $fh, '<', $dict_qfn)
      or die("Can't open \"$dict_qfn\": $!\n");

   while (<$fh>) {
      chomp;
      push @{ $anagrams{ key($_) } }, $_;
   }
}

my @results = grep { $_ ne $search } @{ $anagrams{$search} // [] };
say "Anagrams of $search: ".( @results ? "@results" : "[none]" );

【讨论】:

  • 使用(_)有什么特别的原因吗? (因为你还在写key($_))只是最近想用原型,还是……?
  • @Dada,我没有利用它,但它正是原型可能有用的那种功能
猜你喜欢
  • 2017-07-18
  • 2016-02-20
  • 2015-03-07
  • 1970-01-01
  • 2014-03-31
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 2021-03-26
相关资源
最近更新 更多