从一串随机字母中提取一个子字符串



我有字符串,这是随机的性质,例如'CBLBTTCCBB'。我的目标是计算字符串CTLBT在字符串CBLBTTCCBB中出现的次数。不允许重复用于检查的字母。例如,一旦形成CTLBT,则下一次迭代剩下的随机字母将是BCCB

这个场景是我们有一张刮刮卡,用户可以赢得字母来组成单词CTLBT。根据用户的记录,他赢得的字母在一个字符串CBLBTTCCBB中,该字符串根据刮刮卡的购买从左到右排序。

我想使用strpos,但它似乎不合适,因为它使用了大字符串的子字符串的精确排列。

对于如何解决这个问题有什么想法吗?

谢谢!

注意:问题是不是一个重复的如何计算子字符串在字符串中出现的次数?因为解决方案张贴在给定的链接是不同的。substr_count计算子字符串在字符串中出现的次数,前提是该字符串的顺序是正确的,该子字符串将按照正确的顺序形成。

也许你可以使用preg_replace then:

function rand_substr_count($haystack, $needle)
{
    $result = $haystack;
    for($i=0; $i<strlen($needle); $i++) {
        $result = preg_replace('/'.$needle[$i].'/', '', $result, 1);
    }
    if (strlen($haystack) - strlen($result) == strlen($needle)) {
        return 1 + rand_substr_count($result, $needle);
    } else {
        return 0;
    }
}
echo rand_substr_count("CBLBTTCCBB", "CTLBT");

如果我理解正确的话,我会这样做(用打印来显示结果):

<?
# The string to test
$string="CBLBTTCCBBTLTCC";
# The winning word
$word="CTLBT";
# Get the letters from the word to use them as unique array keys
$letters=array_unique(str_split($word));
print("Letters needed are:n".print_r($letters,1)."n");
# Initialize the work array
$match=array("count" => array(),"length"=> array());
# Iterate over the keys to build the array with the number of time the letter is occuring
foreach ($letters as $letter) {
  $match['length'][$letter] = substr_count($word,$letter); #Number of time this letter appears in the winning word
  $match['count'][$letter] = floor(substr_count($string,$letter) / $match['length'][$letter]); # count the letter (will be 0 if none present) and divide by the number of time it should appear, floor it so we have integer
}
print("Count of each letter divided by their appearance times:n".print_r($match['count'],1)."n");
# Get the minimum of all letter to know the number of times we can make the winning word
$wins = min($match['count']);
# And print the result
print("Wins: $winsn");
?>

湿草地输出:

Letters needed are:
Array
(
    [0] => C
    [1] => T
    [2] => L
    [3] => B
)
Count of each letter divided by their appearance times:
Array
(
    [C] => 5
    [T] => 2
    [L] => 2
    [B] => 4
)
Wins: 2

由于您希望计数组合而不考虑顺序,因此字母的最小计数将是用户获胜的次数,如果没有一个字母,则为0。

我让您将其转换为一个函数并清除您不希望的打印行;)

最新更新