где-нибудь за пределами любого раздела [квадратные скобки], и соответствующий HPH, где-нибудь внутри [квадратных скобок].
PHP – это любая трехбуквенная последовательность, в которой дважды содержится одна и та же буква, а между ними есть разные буквы, например «uvu» или « ага».
Соответствующий HPH — это те же буквы, но в перевернутых позициях, например «вув» и «ха» соответственно. В CrazyID может быть много таких последовательностей [квадратных скобок] любой длины.
Программа PHP должна выводить только целое значение количества проверенных CrazyID.
Код: Выделить всё
function is_valid_crazy_id($crazy_id) {
// Split the string into parts inside and outside square brackets
preg_match_all('/\[([^\]]+)\]/', $crazy_id, $inside_brackets); //all string inside square bracket
preg_match_all('/([^\[\]]+)/', preg_replace('/\[[^\]]+\]/', '|', $crazy_id), $outside_brackets); //all string outside square bracket separated by |
// Flatten the arrays
$inside_parts = implode(' ', $inside_brackets[1]); //0th array having square bracket and 1st array having plain text. so taking 1st array value
$outside_parts = implode(' ', $outside_brackets[0]); //all arrays are same, so taking 0th means first array value
// Get all PHP patterns outside brackets
$outside_phps = find_php_patterns($outside_parts);
// Check if any PHP pattern has a corresponding HPH pattern inside brackets
foreach ($outside_phps as $php) {
$hph = $php[1] . $php[0] . $php[1]; //creating crazy string, eg. from "php" to "hph"
if (strpos($inside_parts, $hph) !== false) { //find occurance of first string
return true; //if found return true
}
}
return false; //if not found return false
}
// Function to find all PHP patterns in a string
function find_php_patterns($str) {
preg_match_all('/(.)(.)\1/', $str, $matches);
/*The pattern (.) captures the first character.
The next (.) captures the second character.
The \1 backreference matches the first captured character.*/
return $matches[0];
}
$input_file = 'puzzle_input.txt'; // Change this to the path of your input file
$validated_count = 0;
// Read the file line by line
$handle = fopen($input_file, 'r'); //fopen to open file in reading mode
if ($handle) {
while (($line = fgets($handle)) !== false) { //fgets returns a line from an open file, loop intil end of file/line
$crazy_id = trim($line); //trim to removes whitespace and other predefined characters from both sides of a string
if (is_valid_crazy_id($crazy_id)) {
$validated_count++; //if found increment the count
}
}
fclose($handle); //closing the opened file
} else { //handled if any error occurs at time of file opening
echo "Error: Unable to open the file.";
}
echo $validated_count;

Я хочу, чтобы первая и третья буквы внешней строки сравнивались со средней буквой скобки spqure, а средняя буква внешней строки сравнивалась с первой и третьей буквой квадратной скобки. Если этот случай соответствует, счетчик будет увеличиваться.
Спасибо
Подробнее здесь: https://stackoverflow.com/questions/787 ... nput-array