查看有多少个单词具有相同的字母

查看有多少个单词具有相同的字母

我有 2 个字符串:

answer="spaghetti"
guess="spgheti"

我想知道是否有某种方法可以计算 $answer 中与 $guess 相同的字母数量,在这种情况下我应该得到数字 7。一些注意事项是 $answer 和 $guess 会改变。

由于有人指责我发布了重复内容,因此建议询问字数;我问两个字符串中有多少个字母相等。例如,“Stackoverflow”和“stkflw”。想要计算“stkflw”中有多少个字母等于“Stackoverflow”中的字母。我需要它来计算一个单词中的所有字母,例如,“Test”应该返回 4,因为它有 4 个字母(答案有一个在 test 中返回 3,这是不可取的)

如果这可以在 bash 中完成,那就太好了! :)

答案1

在 Perl 中,音译运算符tr//(其工作方式与 shell 实用程序非常相似tr)将返回音译的字符数。

$ perl -e 'print("spgheti" =~ tr/spaghetti/spaghetti/, "\n")'
7

spgheti即“在”中找到了七个字符spaghetti

$ perl -e 'print("spaghetti" =~ tr/spgheti/spgheti/, "\n")'
8

spaghetti即“在 中找到了8 个字符spgheti”(因为t在 中出现了两次spaghetti,所以被计数两次)。

在它周围放置一个循环:

while read word1 word2; do
  perl -e 'printf("%s / %s: %d\n", $ARGV[0], $ARGV[1],
    eval "$ARGV[0] =~ tr/$ARGV[1]/$ARGV[1]/")' "$word1" "$word2"
done <<LIST_END
stkflw Stackoverflow
fete feet
good goodness
par rap
LIST_END

Perleval()调用必须能够插入$ARGV[1]到 的搜索和替换列表中tr//

输出:

stkflw / Stackoverflow: 5
fete / feet: 4
good / goodness: 4
par / rap: 3

或者,从每行两个单词的文件中读取:

while read word1 word2; do
  # as before
done <wordpairs

答案2

以下是如何在 bash 中执行此操作。

# ----------------------------------------------------------------------------
# INPUT:
# $1 answer (contains the "source" string)
# $2 guess (contains individual characters to be counted from $answer)
#
# OUTPUT:
# prints to standard output a count of the characters from 'guess' which
# appear in 'answer'
# ----------------------------------------------------------------------------
answer=$1
guess=$2
count=0

# for each character in $guess, observe whether its elimination from
# $answer causes the resultant string to be different; if so, it exists,
# therefore increment a counter

# iterate over the characters of $guess
for (( i=0; i < ${#guess}; i=i+1 )); do
    current_char=${guess:$i:1}

    # attempt to extract current character
    answer_after_extract=${answer//$current_char}

    # has $answer changed?
    if [[ $answer_after_extract != $answer ]]; then
        count=$(( count + 1 ))
    fi
    answer=$answer_after_extract
done

echo $count

样本输出

$ ./answer spaghetti spgheti
7

$ ./answer abcdefghijklmnopqrstuvwxyz aeiou
5

$ ./answer abcdefghijklmnopqrstuvwxyz xyzzy
3

答案3

answer=spaghetti
guess=aeghipstt

# find the individual letters in the answer
# use an associative array to manage duplicates
declare -A letters=()
for ((i=0; i < ${#answer}; i++)); do
    letters[${answer:i:1}]=1
done

# remove duplicate letters in the guess.
# could use the above technique, but here's another one
guess_uniq=$( sed 's/./&\n/g' <<< "$guess" | sort -u | tr -d '\n' )

# loop over the unique letters of the guess, 
# and count how many letters are in the answer
matches=0
for ((i=0; i < ${#guess_uniq}; i++)); do
    [[ ${letters[${guess_uniq:i:1}]} = "1" ]] && (( matches++ ))
done

if (( matches == ${#guess_uniq} )); then echo "Correct"; fi

相关内容