Three the same characters in a row in string PHP - php

I have no idea how to create function which counts how many times 3 the same letters in a row reapets in one string?
For example: avcdddjrg return 1, aaargthbbb return 2
I can detect if there are 3 the same characters in a row, but can't figure it out how to count it
$input = 'hellooommm';
if (preg_match('/(.)\1{2}/', $input)) {
return 1;
}else {
return 0;
}
Thank you

Use preg_match_all(), like this:
$input = 'hellooommm';
$n = preg_match_all('/(.)\1{2}/', $input);
if ($n !== false) {
echo "$n matches found", PHP_EOL;
} else {
echo "an error occurred when calling preg_match_all()", PHP_EOL;
}

#hek2mgl's answer above is simple and eloquently solves the problem using regex. But I get the feeling you may benefit from hashing this out logically a bit more. Another approach you could use is iterating over the characters and counting the repetitions like this:
function countGroupsOfThree($str) {
$length = strlen($str);
$count = 1;
$groups = 0;
for ($i = 0; $i < $length; $i++){
// is this character the same as the last one?
if ($i && $str[$i] === $str[$i-1]) {
// if so, increment the counter
$count++;
// is this the third repeated character in a row?
if ($count == 3) {
// if so, increment $groups
$groups++;
}
} else {
// if not, reset the counter
$count = 1;
}
}
return $groups;
}
$str = 'aaavgfwbbb3ds';
echo countGroupsOfThree($str);
OUTPUT: 2
In the grand scheme of things, this function is probably not very useful but hopefully it illustrates some key concepts that will help you figure things like this out in the future.

Related

How to achieve the same result for a function without using loops, arrays, strings, and lists?

For starters, i'm new in PHP.
I have the function, that prints a row of numbers from 1 to $nums.
But my task is not allows me to use loops, lists, arrays, and strings.
So how can I achieve the same result without using these?
I really do not know, though i tried.
function returnString($nums) {
$error = "Error!";
$str = "";
if ($nums > 0) {
for ($i = 0; $i < $nums; $i++) {
$iter = $i + 1;
$str .= $iter . PHP_EOL;
}
return $str;
}
else {
return $error;
}
}
$numString = returnString(30);
echo $numString;
Also, range() is not allowed too, because it's creates an array from range. Maybe i can create a counter, that increments number from 1? Like $num = 0 $num + 1. I need your advice how can i pull this off, guys.
Thanks, any help will be immeasurable!
If strings are allowed for transfer, then recursion is a solution:
function returnString($nums) {
if ($nums<=0)
return '';
return returnString($nums-1) .$nums.PHP_EOL;
}
$numString = returnString(30);
echo $numString;

Counting the number of times a substring occurs in a string using strlen+substr+strpos ONLY PHP

I would like to write a function that can count the number of times a substring occurs in a string using strlen+substr+strpos ONLY ,in PHP.
Without using substr_count!
example: fn('iwritecodeiwritecode-','i');
Thanks Ahead
You will not need strlen() or substr() for this task.
Merely iterate your string with a while loop, advance the output of strpos() with every successful found needle and count the number of successful matches.
The "magic" in this technique is using the previous strpos() value (plus 1) as the the starting point for all subsequent strpos() calls.
Code: (Demo)
function countSubstrings($haystack,$needle) {
$pos = -1; // start at -1 so that first iteration uses $pos of 0 as starting offset
$tally = 0;
while (($pos = strpos($haystack, $needle, ++$pos)) !== false) {
++$tally;
}
return $tally;
}
echo countSubstrings('iwritecodeiwritecodeiwritecode', 'i'); // 6
echo countSubstrings('iwritecodeiwritecodeiwritecode', 'Perumal'); // 0
echo countSubstrings('iwritecodeiwritecodeiwritecode', 'write'); // 3
A note to future readers, this question is not best practice. The correct method would be a simple call of the pre-existing php function substr_count().
echo substr_count('iwritecodeiwritecodeiwritecode', 'i');
Or, less efficient versus substring_count() would be preg_match_all() which returns the number of matches.
echo preg_match_all('/i/', 'iwritecodeiwritecodeiwritecode'); // 6
function fn($string, $char){
$count=0;
for($i=0; $i<strlen($string);$i++){
if($string[$i] == $char){
$count++;
}
}
print($count);
}
fn('iwritecodeiwritecode-','i');
I hope it helps Cheers!
I've come up with my own best solution.
<?php
$str = "iwritecodeiwritecode";
function find_substr_count($str, $substr) {
$substr_len = strlen($substr);
$substr_count = 0;
for($i = 0; $i < strlen($str); $i++) {
$substr_temp = '';
for($j = $i; $j < $i + $substr_len; $j++) {
if($j < strlen($str)) {
$substr_temp .= $str[$j];
}
}
if($substr_temp == $substr) {
$substr_count += 1;
}
}
return $substr_count;
}
echo find_substr_count($str, "i");
?>
It doesn't only work for single character. You can also try passing two or more characters in the function like:
echo find_substr_count($str, "write");
I've given my best to help you.
Hope it helps!

I dont know what to do with this PHP Code

The code below basically helps in finding out if a number is a Palindromic Number or not. Although I get my execution done with the output, I just can seem to handle all the "screams" and fatal errors that I get. How do I handle this. Just a beginner and trust you can explain in a way that I may be able to understand..
<?php
for ($num = 1; $num <= 20; ++$num){
$_array1 = str_split($num);
//print_r($_array1);
//echo "<br/>";
$_array2 = array_reverse($_array1);
//print_r($_array2);
//echo "<br/>";
$i = 0;
$j = 0;
while ($i < sizeof($_array1) && $j < sizeof($_array2)){
if ($_array1[$i] == $_array2[$j]){
++$i;
++$j;
}
}
if ($_array1[$i] == $_array2[$j]){
echo "The number $num is a Palindrome Number";
}
}
?>
You get to the size of elements, which is 1. However, if your array has only one element, which is the case for 1-digit numbers, then sizeof($_array) === 1. Which means that the biggest possible index you can use is 0. You need to change your code to something like this:
<?php
for ($num = 1; $num <= 20; ++$num){
$_array1 = str_split($num);
//print_r($_array1);
//echo "<br/>";
$_array2 = array_reverse($_array1);
//print_r($_array2);
//echo "<br/>";
$i = 0;
$j = 0;
$different = false;
while ((!$different) && ($i < sizeof($_array1))){
if ($_array1[$i] == $_array2[$j]){
++$i;
++$j;
} else {
$different = true;
}
}
if (!$different){
echo "The number $num is a Palindrome Number";
}
}
?>
But you are inversing the array without a need to do so and you are looping for unnecessarily long. I propose this function to determine whether an array is a palindrome:
function isPalindrome($input) {
$size = count($input);
for ($index = 0; $index < $size / 2; $index++) {
if ($input[$index] != $input[$size - $index - 1]) {
return false;
}
}
return true;
}
Note, that:
the function assumes that the keys of the array are numbers
the function uses a single array
the size of the array is stored into a local variable to not calculate it repeatedly
the cycle cycles until half of the array, since going beyond that is unnecessary, due to the symmetrical nature of the != operator
the function returns false when the first difference is found, to further optimize the checking
if there were no differences, the function returns true, representing that the input is a palindrome

PHP unique numbers not unique

I have two different functions, one that generates 5 random cards from value 0-51 (unique), and one function that contain an array containing those 5 cards, and an array that contains some of the numbers from array #1 that would be stored.
The function two function two is to replace new values to array #1 if the value is not in array #2.
It seems to be something wrong here. after generating numbers for a bit i got:
array(27,18,37,27,45)
returned from the newCards function.
Question: How can i fix newCards function 100% to do what it is supposed to do? (aka use first array, check if number is in 2nd array, if not, make unique here too) since here it went something wrong since it returned two of the same numbers.
code:
function UniqueCards() {
$result = array();
while(count($result) != 5) {
$rand = rand(0,51); // reads as 0 = 1, and 51 = 52. aka starts at zero.
if(!in_array($rand,$result)){
$result[] = $rand;
}
}
return $result;
}
function newCards($input,$exclude) {
$i = 0;
$output = array();
while($i < count($input)) {
$rand = rand(0,51);
if(in_array($input[$i], $exclude)) {
$output[$i] = $input[$i];
$i++;
}
else if(!in_array($rand, $input)){
$output[$i] = $rand;
$i++;
}
}
return $output;
}
If you add checking if $rand is already in $output will it fix the problem?
function newCards($input,$exclude) {
...
else if(!in_array($rand, $input) && !in_array($rand, $output)) {
$output[$i] = $rand;
$i++;
}
...
}

PHP substring find infinite loop error

I have this code that for some reason it keeps in an infinite loop, when it is suppose to just print all possible substrings. This is part of the complete function. The purpose of the function is to return the indexes of the substring from string $str2 found in string $str1. Thanks a lot for the help.
$str1='QYDIKYTWNVPKIAPKS';
$str2='KYTWNVPKSS';
print($str1);echo"</br>";print($str2);echo"</br>";
function overlapping($str1,$str2) {
$peptide1 = str_split($str1);
$peptide2 = str_split($str2);
$longest_seq=array();
$len=count($peptide2)-1;
for ($i = 0; $i < count($peptide1); ++$i) {
for ($j = 0; $j < count($peptide2); ++$j) {
if ($peptide2[$j]==$peptide1[$i]){
$k=$j;
$start=$j;
$l=$i;
$tmp=array();
while ($peptide2[$k]==$peptide1[$l]){
array_push($tmp, $peptide2[$k]);
$substring=implode($tmp);
print $substring;
echo"</br>";
$k=$k+1;
$l=$l+1;
}
}
}
}
}
Maybe you have another idea of how to extract the index of a matching substring, I can also try that
You never check to insure that $k and $l are valid offsets. Check for it here :
while (isset($peptide2[$k]) && isset($peptide1[$l]) && $peptide2[$k]==$peptide1[$l]){
instead of
while ($peptide2[$k]==$peptide1[$l]){
I'm not sure if this has anything to do with your issue, but I always post-increment in my for loops.
for ($i = 0; $i < count($peptide1); $i++) {
// do stuff
}

Categories