我有一个句子作为输入。
我希望能够根据形成每个单词的字母计算句子(a=1, b=2, c=3)
的总分。
此外,如果一个句子有双字母i
想要加倍其值。
最后,我想过滤掉与a-z不同的字符。
代码(已编辑)
$words = "Try to do this";
$letters = str_split($words);
$value = '0 a b c d e f g h i j k l m n o p q r s u v w x y z';
$value = explode(' ',$value);
$value1 = array_flip($value);
$result = array_intersect($letters, $value);
这是我开始但无法完成的事情,我发布它只是为了看我的逻辑是否正确!
答案 0 :(得分:0)
// Input string
$str = 'Try to do this';
// Remove irrelevant characters, convert to lowercase
$str = preg_replace('/[^a-z]/', '', strtolower($str));
// Create a function to determine the value of a character
function my_char_value($char) {
return ord($char) - 96;
}
// Convert the string to an array and apply our function to each element
$arr = array_map('my_char_value', str_split($str));
// Add each array element to determine subtotal
$sum = array_sum($arr);
// Double the sum if two "i"s are present in the string
if (preg_match('/i.*?i/', $str)) {
$sum *= 2;
}
print $sum;
答案 1 :(得分:0)
怎么样:
function counter($string) {
// count the number of times each letter occurs, filtering out anything other than a-z
$counts = array_count_values(
str_split(
preg_replace('/[^a-z]/iS', '', strtolower($string))
)
);
// convert the counts to Caeser ciphers (a => 1, aa => 2, bb => 4, etc.)
array_walk(
$counts,
function (&$value, $letter) {
$value = $value * (ord($letter) - 96);
}
);
// sum up the encodings
$sum = array_sum($counts);
// if there's a double i, double again
if (preg_match('/ii/iS', $string)) {
$sum *= 2;
}
return $sum;
}
测试用例
echo counter("i"); // = 9
echo counter("ii"); // = 36
echo counter("abc0"); // = 6
echo counter("aabc0"); // = 7
echo counter("aabbcc00"); // = 12
echo counter("Try to do this"); // = 173
答案 2 :(得分:0)
我重写了你的代码&认为这将按预期工作。我已编辑此代码,因此它现在可以正确地考虑双重评分项目。请注意,$double_score_array
只有单个字母,但正则表达式有{2}
表示应该查看一行中的2个字母。有评论说明每个阶段:
// Set the '$words' string.
$words = "Try to do thiis.";
// Set an array for double score items.
$double_score_array = array('i');
// Init the '$raw_results' array
$raw_results = array();
// Create a '$value_array' using the range of 'a' to 'z'
$value_array = range('a','z');
// Prepend a '0' onto the '$value_array'
array_unshift($value_array, 0);
// Flip the '$value_array' so the index/key values can be used for scores.
$value_array_flipped = array_flip($value_array);
// Filter out any character that is not alphabetical.
$words = preg_replace('/[^a-zA-Z]/', '', strtolower($words));
// Let's roll through the double score items.
foreach ($double_score_array as $double_score_letter) {
preg_match('/' . $double_score_letter . '{2}/', $words, $matches);
$double_score_count = count($matches);
// With double score items accounted, let's get rid of the double score item to get normal scores.
$words = preg_replace('/' . $double_score_letter . '{2}/', '', $words);
}
// Split the '$words' string into a '$letters_array'
$letters_array = str_split($words);
// Now let's set the value for the double score items.
$raw_results[] = (($value_array_flipped[$double_score_letter] * 2) * $double_score_count);
// Roll through the '$letters_array' and assign values.
foreach ($letters_array as $letter_key => $letter_value) {
$raw_results[] = $value_array_flipped[$letter_value];
}
// Filter out the empty values from '$raw_results'.
$filtered_results = array_filter($raw_results);
// Run an 'array_sum()' on the '$filtered_results' to get a final score.
$final_results = array_sum($filtered_results);
// Echo the score value in '$final_results'
echo 'Score: ' . $final_results;
// Dump the '$filtered_results' for debugging.
echo '<pre>';
print_r($filtered_results);
echo '</pre>';
编辑在评论中,原始海报声明上述代码不会使得分加倍。不清楚,因为 - 根据例子 - 字母i
是字母表的第9个字母。所以得分是9.所以不会将得分加倍18
?或者你的意思是它应该36
意味着两个i
个项的得分加倍?
如果“双倍得分”实际上意味着取得两个单独项目的分数&amp;加倍,然后只需转到代码的这一部分:
// Now let's set the value for the double score items.
$raw_results[] = (($value_array_flipped[$double_score_letter] * 2) * $double_score_count);
并将2
更改为4
,以便有效地将双字母ietms的分数加倍:
// Now let's set the value for the double score items.
$raw_results[] = (($value_array_flipped[$double_score_letter] * 4) * $double_score_count);
另一个编辑好的,我想我理解原始的海报请求。特别是当他们问,“另外,如果一个句子有一个双字母我想要加倍它的价值。”我和其他人解释为连续两个字母,如ii
,但似乎如果那两个字母只用然后出现在句子中,分数会加倍。所以我重新设计逻辑来解释i
出现在句子中的任何两个实例。而且,由于不清楚如果句子中出现超过2 i
会发生什么,我会设置逻辑来解释这样的情况;那些额外的i
只获得一个值。添加我的新版本。比较&amp;与上面的第一个版本形成对比。你现在应该能够做任何你需要的事。
// Set the '$words' string.
$words = "Try to do thiiis.";
// Set an array for double score items.
$double_score_array = array('i');
// Set a double score multiplier.
$double_score_multiplier = 2;
// Init the '$raw_results' array
$raw_results = array();
// Create a '$value_array' using the range of 'a' to 'z'
$value_array = range('a','z');
// Prepend a '0' onto the '$value_array'
array_unshift($value_array, 0);
// Flip the '$value_array' so the index/key values can be used for scores.
$value_array_flipped = array_flip($value_array);
// Filter out any character that is not alphabetical.
$words = preg_replace('/[^a-zA-Z]/', '', strtolower($words));
// Let's roll through the double score items.
$double_score_count = $non_double_count = 0;
foreach ($double_score_array as $double_score_letter) {
$double_score_regex = sprintf('/%s{1}/', $double_score_letter);
preg_match_all($double_score_regex, $words, $matches);
$count = count($matches[0]);
// We only want to double the score for the first two letters found.
if ($count >= 2) {
$double_score_count = 2;
}
// This handles the accounting for items past the first two letters found.
$non_double_count += ($count - 2);
// This handles the accounting for single items less than the first two letters found.
if ($count < 2) {
$non_double_count += $count;
}
// With double score items accounted, let's get rid of the double score item to get normal scores.
$words = preg_replace($double_score_regex, '', $words);
}
// Split the '$words' string into a '$letters_array'
$letters_array = str_split($words);
// Now let's set the value for the double score items.
if ($double_score_count > 0) {
$raw_results[] = (($value_array_flipped[$double_score_letter] * $double_score_multiplier) * $double_score_count);
}
// And get the values of items that are non-double value.
if ($non_double_count > 0) {
$raw_results[] = $value_array_flipped[$double_score_letter] * $non_double_count;
}
// Roll through the '$letters_array' and assign values.
foreach ($letters_array as $letter_key => $letter_value) {
$raw_results[] = $value_array_flipped[$letter_value];
}
// Filter out the empty values from '$raw_results'.
$filtered_results = array_filter($raw_results);
// Run an 'array_sum()' on the '$filtered_results' to get a final score.
$final_results = array_sum($filtered_results);
// Echo the score value in '$final_results'
echo 'Score: ' . $final_results;
// Dump the '$filtered_results' for debugging.
echo '<pre>';
print_r($filtered_results);
echo '</pre>';
答案 3 :(得分:0)
我找到了更好的解决方案 检查此代码
<?php
/**
* Script to calculate the total score of a sentence (a=1, b=2, c=3), according to the letters that form each word.
* Also, if a sentence has a double letter i want to double its value.
* Finally, I want to filter out characters different from a-z.
*
* Author: Viswanath Polaki
* Created: 5-12-2013
*/
//array to define weights
$weight = array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
'e' => 5,
'f' => 6,
'g' => 7,
'h' => 8,
'i' => 9,
'j' => 10,
'k' => 11,
'l' => 12,
'm' => 13,
'n' => 14,
'o' => 15,
'p' => 16,
'q' => 17,
'r' => 18,
's' => 19,
't' => 20,
'u' => 21,
'v' => 22,
'w' => 23,
'x' => 24,
'y' => 25,
'z' => 26
);
//your sentance
$sentance = "My name is Viswanath Polaki. And my lucky number is 33";
$asentance = array();
$strlen = strlen($sentance);
//converting sentance to array and removing spaces
for ($i = 0; $i < $strlen; $i++) {
if ($sentance[$i] != " ")
$asentance[] = strtolower($sentance[$i]);
}
$sumweights = array();
//calculation of weights
foreach ($asentance as $val) {
if (key_exists($val, $weight)) {
$sumweights[$val] += $weight[$val];
} else {
$sumweights['_unknown'][] = $val;
}
}
ksort($sumweights);//sorting result
echo "<pre>";
print_r($sumweights);
echo "</pre>";
?>