6

Perl(5.8.8)に、配列内の他の単語と共通する文字が最も多い単語を見つけてもらいたいのですが、同じ場所にある文字だけです。(そして、できればライブラリを使用しないでください。)

例として、次の単語のリストを取り上げます。

  • ベイカー
  • サラー
  • ベーラー
  • 介護者
  • ラフ

彼女の BALER は、他の文字と共通する文字が最も多い単語です。BAKER では BAxER、SALER では xALER、CARER では xAxER、RUFFR では xxxxR に一致します。

Perl に、同じ長さと大文字と小文字の単語の任意のリストからこの単語を見つけてもらいたいのです。ここで壁にぶつかったようですので、助けていただければ幸いです。

今まで試したこと

現時点では、スクリプトはあまりありません。

use strict;
use warnings; 
my @wordlist = qw(BAKER SALER MALER BARER RUFFR);
foreach my $word (@wordlist) {
    my @letters = split(//, $word);
    # now trip trough each iteration and work magic...
}

コメントがある場所では、for ループと ++ 変数を多用した、いくつかの種類のコードを試しました。これまでのところ、私の試みはどれも私が必要とすることをしていません。

したがって、より適切に説明するには、文字の位置ごとにリストに対して単語ごとにテストし、その文字の位置で、リスト内の他の文字と共通する文字が最も多い単語を見つける必要があります。

考えられる方法の 1 つは、最初にどの単語が文字位置 0 で最も共通しているかを確認し、次に文字位置 1 をテストするというように、合計で共通する文字が最も多い単語が見つかるまで繰り返すことです。リスト内の他の単語。次に、DavidOが提案するものとは異なり、各文字位置のスコアと各単語の合計スコアを含むマトリックスのようにリストを印刷したいと思います。

最終的に得られるのは、各単語のマトリックス、各文字位置のスコア、およびマトリックス内の各単語の合計スコアです。

プログラムの目的

へへへ、私はそれを言うかもしれません: このプログラムは、ゲーム Fallout 3 で端末をハッキングするためのものです. :D 私の考えでは、ゲームを楽しみながら Perl を学ぶのに最適な方法です。

これは、私が調査に使用した Fallout 3 ターミナル ハッキング チュートリアルの 1 つです: FALLOUT 3: Hacking FAQ v1.2で、次のように単語のリストを短縮するプログラムを既に作成しています。

#!/usr/bin/perl
# See if one word has equal letters as the other, and how many of them are equal
use strict;
use warnings; 

my $checkword = "APPRECIATION"; # the word to be checked
my $match = 4; # equal to the match you got from testing your checkword
my @checkletters = split(//, $checkword); #/

my @wordlist = qw(
    PARTNERSHIPS
    REPRIMANDING
    CIVILIZATION
    APPRECIATION
    CONVERSATION
    CIRCUMSTANCE
    PURIFICATION
    SECLUSIONIST
    CONSTRUCTION
    DISAPPEARING
    TRANSMISSION
    APPREHENSIVE
    ENCOUNTERING
);

print "$checkword has $match letters in common with:\n";

foreach my $word (@wordlist) {
    next if $word eq $checkword;
    my @letters = split(//, $word);
    my $length = @letters; # determine length of array (how many letters to check)

    my $eq_letters = 0; # reset to 0 for every new word to be tested
    for (my $i = 0; $i < $length; $i++) {
        if ($letters[$i] eq $checkletters[$i]) {
            $eq_letters++;
        }
    }
    if ($eq_letters == $match) {
        print "$word\n";
    }
}
# Now to make a script on to find the best word to check in the first place...

このスクリプトは、ゲームの FAQ と同じように生成され、その結果としてCONSTRUCTION生成されます。TRANSMISSIONただし、元の質問の秘訣 (および私が自分で見つけることができなかったもの) は、最初に試すのに最適な単語を見つける方法APPRECIATIONです。

OK、あなたの助けに基づいて私自身の解決策を提供しました。このスレッドは閉じられたと考えてください。すべての貢献者に感謝します。あなたは途方もなく助けになりました、そして途中で私も多くを学びました. :D

4

8 に答える 8

7

これが1つの方法です。あなたの仕様を数回読み直して、それがあなたが探しているものだと思います。

同じ最高スコアを持つ単語が複数存在する可能性があることに注意してください。あなたのリストから勝者は 1 つしかありませんが、リストが長くなると、同じように勝者となる単語がいくつか存在する可能性があります。このソリューションはそれに対処します。また、私が理解しているように、文字の一致は、単語ごとに同じ列にある場合にのみカウントされます。その場合は、次の解決策があります。

use 5.012;
use strict;
use warnings;
use List::Util 'max';

my @words = qw/
    BAKER
    SALER
    BALER
    CARER
    RUFFR
/;

my @scores;
foreach my $word ( @words ) {
    my $score;
    foreach my $comp_word ( @words ) {
        next if $comp_word eq $word;
        foreach my $pos ( 0 .. ( length $word ) - 1 ) {
            $score++ if substr( $word, $pos, 1 ) eq substr( $comp_word, $pos, 1);
        }
    }
    push @scores, $score;
}
my $max = max( @scores );
my ( @max_ixs ) = grep { $scores[$_] == $max } 0 .. $#scores;

say "Words with most matches:";
say for @words[@max_ixs];

このソリューションは、文字列ごとに各単語の文字が他の単語と一致する回数をカウントします。たとえば、次のようになります。

Words:     Scores:       Because:
ABC        1, 2, 1 = 4   A matched once,  B matched twice, C matched once.
ABD        1, 2, 1 = 4   A matched once,  B matched twice, D matched once.
CBD        0, 2, 1 = 3   C never matched, B matched twice, D matched once.
BAC        0, 0, 1 = 1   B never matched, A never matched, C matched once.

これにより、ABC と ABD の勝者が得られ、それぞれ 4 つの位置マッチのスコアが得られます。つまり、列 1、行 1 が列 1、行 2、3、および 4 と一致した累積時間であり、後続の列についても同様です。さらに最適化して、より短い言葉に言い換えることができるかもしれませんが、ロジックをかなり読みやすくするように努めました。楽しみ!

更新/編集 私はそれについて考え、既存の方法は元の質問が要求したことを正確に実行しますが、O(n^2) 時間で実行され、比較的遅いことに気付きました。しかし、各列の文字 (キーごとに 1 文字) にハッシュ キーを使用し、各文字が列に出現する回数を (ハッシュ要素の値として) カウントすると、O(1 ) 時間、および O(n*c) 時間でのリストのトラバーサル (c は列の数、n は単語の数)。セットアップ時間もあります (ハッシュの作成)。しかし、まだ大きな改善点があります。ここでは、各手法の新しいバージョンと、それぞれのベンチマーク比較を示します。

use strict;
use warnings;
use List::Util qw/ max sum /;
use Benchmark qw/ cmpthese /;

my @words = qw/
    PARTNERSHIPS
    REPRIMANDING
    CIVILIZATION
    APPRECIATION
    CONVERSATION
    CIRCUMSTANCE
    PURIFICATION
    SECLUSIONIST
    CONSTRUCTION
    DISAPPEARING
    TRANSMISSION
    APPREHENSIVE
    ENCOUNTERING
/;


# Just a test run for each solution.
my( $top, $indexes_ref );

($top, $indexes_ref ) = find_top_matches_force( \@words );
print "Testing force method: $top matches.\n";
print "@words[@$indexes_ref]\n";

( $top, $indexes_ref ) = find_top_matches_hash( \@words );
print "Testing hash  method: $top matches.\n";
print "@words[@$indexes_ref]\n";



my $count = 20000;
cmpthese( $count, {
    'Hash'  => sub{ find_top_matches_hash( \@words ); },
    'Force' => sub{ find_top_matches_force( \@words ); },
} );


sub find_top_matches_hash {
    my $words = shift;
    my @scores;
    my $columns;
    my $max_col = max( map { length $_ } @{$words} ) - 1;
    foreach my $col_idx ( 0 .. $max_col ) {
        $columns->[$col_idx]{ substr $_, $col_idx, 1 }++ 
            for @{$words};
    }
    foreach my $word ( @{$words} ) {
        my $score = sum( 
            map{ 
                $columns->[$_]{ substr $word, $_, 1 } - 1
            } 0 .. $max_col
        );
        push @scores, $score;
    }
    my $max = max( @scores );
    my ( @max_ixs ) = grep { $scores[$_] == $max } 0 .. $#scores;
    return(  $max, \@max_ixs );
}


sub find_top_matches_force {
    my $words = shift;
    my @scores;
    foreach my $word ( @{$words} ) {
        my $score;
        foreach my $comp_word ( @{$words} ) {
            next if $comp_word eq $word;
            foreach my $pos ( 0 .. ( length $word ) - 1 ) {
                $score++ if 
                    substr( $word, $pos, 1 ) eq substr( $comp_word, $pos, 1);
            }
        }
        push @scores, $score;
    }
    my $max = max( @scores );
    my ( @max_ixs ) = grep { $scores[$_] == $max } 0 .. $#scores;
    return( $max, \@max_ixs );
}

出力は次のとおりです。

Testing force method: 39 matches.
APPRECIATION
Testing hash  method: 39 matches.
APPRECIATION
        Rate Force  Hash
Force 2358/s    --  -74%
Hash  9132/s  287%    --

提供された他のオプションのいくつかを見た後、元の仕様が変更されたことに気付きました。それはある程度の革新の性質ですが、パズルはまだ私の心の中で生きていました. ご覧のとおり、私のハッシュ法は元の方法よりも 287% 高速です。短時間でもっと楽しく!

于 2011-07-10T05:32:13.553 に答える
5

出発点として、共通の文字数を効率的に確認できます。

$count = ($word1 ^ $word2) =~ y/\0//;

ただし、これは可能なすべての単語のペアをループする場合にのみ役立ちます。この場合は必要ありません。

use strict;
use warnings;
my @words = qw/
    BAKER
    SALER
    BALER
    CARER
    RUFFR
/;

# you want a hash to indicate which letters are present how many times in each position:

my %count;
for my $word (@words) {
    my @letters = split //, $word;
    $count{$_}{ $letters[$_] }++ for 0..$#letters;
}

# then for any given word, you get the count for each of its letters minus one (because the word itself is included in the count), and see if it is a maximum (so far) for any position or for the total:

my %max_common_letters_count;
my %max_common_letters_words;
for my $word (@words) {
    my @letters = split //, $word;
    my $total;
    for my $position (0..$#letters, 'total') {
        my $count;
        if ( $position eq 'total' ) {
            $count = $total;
        }
        else {
            $count = $count{$position}{ $letters[$position] } - 1;
            $total += $count;
        }
        if ( ! $max_common_letters_count{$position} || $count >= $max_common_letters_count{$position} ) {
            if ( $max_common_letters_count{$position} && $count == $max_common_letters_count{$position} ) {
                push @{ $max_common_letters_words{$position} }, $word;
            }
            else {
                $max_common_letters_count{$position} = $count;
                $max_common_letters_words{$position} = [ $word ];
            }
        }
    }
}

# then show the maximum words for each position and in total: 

for my $position ( sort { $a <=> $b } grep $_ ne 'total', keys %max_common_letters_count ) {
    printf( "Position %s had a maximum of common letters of %s in words: %s\n",
        $position,
        $max_common_letters_count{$position},
        join(', ', @{ $max_common_letters_words{$position} })
    );
}
printf( "The maximum total common letters was %s in words(s): %s\n",
    $max_common_letters_count{'total'},
    join(', ', @{ $max_common_letters_words{'total'} })
);
于 2011-07-10T05:19:48.400 に答える
4

これが完全なスクリプトです。ysthが言及したのと同じアイデアを使用しています(ただし、私は独自に持っていました)。ビットごとの xor を使用して文字列を結合し、結果の NUL の数をカウントします。文字列が ASCII である限り、一致する文字がいくつあったかがわかります。(この比較では大文字と小文字が区別されます。文字列が UTF-8 の場合はどうなるかわかりません。おそらく何も良いことはありません。)

use strict;
use warnings;
use 5.010;

use List::Util qw(max);

sub findMatches
{
  my ($words) = @_;

  # Compare each word to every other word:
  my @matches = (0) x @$words;

  for my $i (0 .. $#$words-1) {
    for my $j ($i+1 .. $#$words) {
      my $m = ($words->[$i] ^ $words->[$j]) =~ tr/\0//;

      $matches[$i] += $m;
      $matches[$j] += $m;
    }
  }

  # Find how many matches in the best word:
  my $max = max(@matches);

  # Find the words with that many matches:
  my @wanted = grep { $matches[$_] == $max } 0 .. $#matches;

  wantarray ? @$words[@wanted] : $words->[$wanted[0]];
} # end findMatches

my @words = qw(
    BAKER
    SALER
    BALER
    CARER
    RUFFR
);

say for findMatches(\@words);
于 2011-07-10T05:29:50.670 に答える
2

しばらく perl に触れていないので、疑似コードです。これは最速のアルゴリズムではありませんが、単語数が少ない場合は問題なく機能します。

totals = new map #e.g. an object to map :key => :value

for each word a
  for each word b
    next if a equals b

    totals[a] = 0
    for i from 1 to a.length
      if a[i] == b[i]
        totals[a] += 1
      end
    end
  end
end

return totals.sort_by_key.last

perl がなくて申し訳ありませんが、これを perl にコーディングすると、魅力的に動作するはずです。

実行時間に関する簡単な注意: これはnumber_of_words^2 * length_of_wordsの時間で実行されるため、それぞれの長さが 10 文字の 100 単語のリストでは、これは 100,000 サイクルで実行され、ほとんどのアプリケーションに適しています。

于 2011-07-10T05:15:09.220 に答える
1

これが私の答えの試みです。これにより、必要に応じて個々の一致を確認することもできます。(つまり、BALERはBAKERの4文字に一致します)。編集:単語間に同点がある場合にすべての一致をキャッチするようになりました(テストするリストに「CAKER」を追加しました)。

#! usr/bin/perl

use strict;
use warnings;

my @wordlist = qw( BAKER SALER BALER CARER RUFFR CAKER);

my %wordcomparison;

#foreach word, break it into letters, then compare it against all other words
#break all other words into letters and loop through the letters (both words have same amount), adding to the count of matched characters each time there's a match
foreach my $word (@wordlist) {
    my @letters = split(//, $word);
    foreach my $otherword (@wordlist) {
        my $count;
        next if $otherword eq $word;
        my @otherwordletters = split (//, $otherword);
        foreach my $i (0..$#letters) {
            $count++ if ( $letters[$i] eq $otherwordletters[$i] );
        }
        $wordcomparison{"$word"}{"$otherword"} = $count;
    }
}

# sort (unnecessary) and loop through the keys of the hash (words in your list)
# foreach key, loop through the other words it compares with
#Add a new key: total, and sum up all the matched characters.
foreach my $word (sort keys %wordcomparison) {
    foreach ( sort keys %{ $wordcomparison{$word} }) {
        $wordcomparison{$word}{total} += $wordcomparison{$word}{$_};
    }
}

#Want $word with highest total

my @max_match = (sort { $wordcomparison{$b}{total} <=> $wordcomparison{$a}{total} } keys %wordcomparison );

#This is to get all if there is a tie:
my $maximum = $max_match[0];
foreach (@max_match) {
print "$_\n" if ($wordcomparison{$_}{total} >= $wordcomparison{$maximum}{total} )
}

出力は単純です:CAKERBALERとBAKER。

ハッシュ%wordcomparisonは次のようになります。

'SALER'
        {
          'RUFFR' => 1,
          'BALER' => 4,
          'BAKER' => 3,
          'total' => 11,
          'CARER' => 3
        };
于 2011-07-10T09:09:32.943 に答える
1

これは、同一の文字を数えるために単語を転置することに依存するバージョンです。コードではなく、元の比較の言葉を使用しました。

これは、任意の長さの単語と長さのリストで機能するはずです。出力は次のとおりです。

Word    score
----    -----
BALER   12
SALER   11
BAKER   11
CARER   10
RUFFR   4

コード:

use warnings;
use strict;

my @w = qw(BAKER SALER BALER CARER RUFFR);
my @tword = t_word(@w);

my @score;
push @score, str_count($_) for @tword;
@score = t_score(@score);

my %total;

for (0 .. $#w) {
    $total{$w[$_]} = $score[$_];
}

print "Word\tscore\n";
print "----\t-----\n";
print "$_\t$total{$_}\n" for (sort { $total{$b} <=> $total{$a} } keys %total);

# transpose the words
sub t_word {
    my @w = @_;
    my @tword;
    for my $word (@w) {
        my $i = 0;
        while ($word =~ s/(.)//) {
            $tword[$i++] .= $1;
        }
    }
    return @tword;
}

# turn each character into a count
sub str_count {
    my $str = uc(shift);
    while ( $str =~ /([A-Z])/ ) {
        my $chr = $1;
        my $num = () = $str =~ /$chr/g;
        $num--;
        $str =~ s/$chr/$num /g;
    }
    return $str;
}

# sum up the character counts
# while reversing the transpose
sub t_score {
    my @count = @_;
    my @score;
    for my $num (@count) {
        my $i = 0;
        while( $num =~ s/(\d+) //) {
            $score[$i++] += $1;
        }
    }
    return @score;
}
于 2011-07-10T12:26:25.027 に答える
0

すべての貢献者に感謝します!あなたは私がまだ学ぶべきことがたくさんあることを確かに示してくれましたが、あなたはまた、私自身の答えを導き出すのに非常に役立ちました. おそらくもっと良い方法があるので、参照と可能なフィードバックのためにここに置いています。私にとって、これは私が自分で見つけることができる最も単純で最も簡単なアプローチでした. 楽しみ!:)

#!/usr/bin/perl
use strict;
use warnings; 

# a list of words for testing
my @list = qw( 
BAKER
SALER
BALER
CARER
RUFFR
);

# populate two dimensional array with the list, 
# so we can compare each letter with the other letters on the same row more easily 
my $list_length = @list;
my @words;

for (my $i = 0; $i < $list_length; $i++) {
    my @letters = split(//, $list[$i]);
    my $letters_length = @letters;
    for (my $j = 0; $j < $letters_length; $j++) {
        $words[$i][$j] = $letters[$j];
    }
}
# this gives a two-dimensionla array:
#
# @words = (    ["B", "A", "K", "E", "R"],
#               ["S", "A", "L", "E", "R"],
#               ["B", "A", "L", "E", "R"],
#               ["C", "A", "R", "E", "R"],
#               ["R", "U", "F", "F", "R"],
# );

# now, on to find the word with most letters in common with the other on the same row

# add up the score for each letter in each word
my $word_length = @words;
my @letter_score;
for my $i (0 .. $#words) {
    for my $j (0 .. $#{$words[$i]}) {
        for (my $k = 0; $k < $word_length; $k++) {
            if ($words[$i][$j] eq $words[$k][$j]) {
                $letter_score[$i][$j] += 1; 
            }
        }
        # we only want to add in matches outside the one we're testing, therefore
        $letter_score[$i][$j] -= 1;
    }
}

# sum each score up
my @scores;
for my $i (0 .. $#letter_score ) {
    for my $j (0 .. $#{$letter_score[$i]}) {
        $scores[$i] += $letter_score[$i][$j];
    }
}

# find the highest score
my $max = $scores[0];
foreach my $i (@scores[1 .. $#scores]) {
    if ($i > $max) {
        $max = $i;
    }
}

# and print it all out :D
for my $i (0 .. $#letter_score ) {
    print "$list[$i]: $scores[$i]";
    if ($scores[$i] == $max) {
        print " <- best";
    }   
    print "\n";
}

スクリプトを実行すると、次の結果が得られます。

BAKER: 11
SALER: 11
BALER: 12 <- best
CARER: 10
RUFFR: 4
于 2011-07-16T00:17:34.957 に答える
0

文字がその場所で一致する場合にコードを実行するダーティ正規表現のトリックを使用してこれを行うことができますが、そうでない場合はそうではありません。ありがたいことに、正規表現を作成するのは非常に簡単です。

正規表現の例は次のとおりです。

(?:(C(?{ $c++ }))|.)(?:(A(?{ $c++ }))|.)(?:(R(?{ $c++ }))|.)(?:(E(?{ $c++ }))|.)(?:(R(?{ $c++ }))|.)

これは速い場合とそうでない場合があります。

use 5.12.0;
use warnings;
use re 'eval';

my @words = qw(BAKER SALER BALER CARER RUFFR);

my ($best, $count) = ('', 0);
foreach my $word (@words) {
    our $c = 0;
    foreach my $candidate (@words) {
    next if $word eq $candidate;

    my $regex_str = join('', map {"(?:($_(?{ \$c++ }))|.)"} split '', $word);
    my $regex = qr/^$regex_str$/;

    $candidate =~ $regex or die "did not match!";
    }
    say "$word $c";
    if ($c > $count) {
    $best = $word;
    $count = $c;
    }
}

say "Matching: first best: $best";

xor トリックを使用すると高速になりますが、遭遇する可能性のある文字の範囲について多くのことを想定しています。その場合、utf-8 が壊れる多くの方法があります。

于 2011-07-10T05:38:57.067 に答える