Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save muratbaskicioglu/2313c990712c7b92c005d8a008d8e031 to your computer and use it in GitHub Desktop.
Save muratbaskicioglu/2313c990712c7b92c005d8a008d8e031 to your computer and use it in GitHub Desktop.
Calculate the sum of suffixes similarities of a string
<?php
/**
* Creates an input prompt with an optional title.
*
* @param string|null $title
* @return string
*/
function input(string $title = null): ?string
{
if ($title) {
print($title);
}
return trim(fgets(STDIN, 1024));
}
/**
* Outputs given string.
*
* @param string $str
* @param bool $newLine
*/
function output(string $str, bool $newLine = false): void
{
if ($newLine) $str .= PHP_EOL;
print_r($str);
}
/**
* Get character counts of similar prefixes of two strings.
*
* @param string $a
* @param string $b
* @return int
*/
function similarity(string $a, string $b): int {
$i = 0;
while ($i < strlen($a) && $i < strlen($b)) {
if ($a[$i] === $b[$i]) $i++;
else { break; }
}
return $i;
}
/**
* Get sum of suffixes similarity counts of a string
*
* @param string $str
* @return int
*/
function sumOfSuffixesSimilarity(string $str): int {
// The similarity of string with itself is always up to be length of itself
$sum = strlen($str);
for ($i = 1; $i < strlen($str); $i++) {
$sum += similarity($str, substr($str, $i));
}
return $sum;
}
function main()
{
while (input('Type \'e\' to exit or press enter to continue.') !== 'e') {
$count = (int)input('Please, enter count of test cases: ');
$testCases = [];
for ($i = 0; $i < $count; $i++) {
$testCases[] = input();
}
if (!empty($testCases)) {
output('Sum of suffixes similarity of the given test cases: ', true);
foreach ($testCases as $testCase) {
output(sumOfSuffixesSimilarity($testCase), true);
}
}
}
}
main();
@muratbaskicioglu
Copy link
Author

Execute php sum_of_suffixes_similarities_of_a_string.php command to run the CLI program.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment