Return false if the repeated occurrence of 0's or 1's in the string is greater than number($k).
I have written a function which works, but I need to optimize it:
<?php
function satisfied($str, $k){
$stream = $last = $str[0];
for($i = 1; $i <= strlen($str)-1; $i++){
if($str[$i] != $last) $last = $stream = $str[$i];
else $stream .= $str[$i];
if(strlen($stream) > $k) return false;
}
return true;
}
Example:
satisfied("0111", 2) - False
satisfied("0111", 3) - True
satisfied("00111000111", 3) - True
satisfied("00111000111", 4) - True
I wanted to know if I can do this with help of preg_match?
something like:
preg_match('/(0+|1+){'.$k.'}/', "0111");, this is not even close to what i want to achieve.
I want to avoid for loops to optimize the code. Will the preg_match be faster than the function above ? And obviously, you can also suggest me tweaks to my existing function.
Can someone help me out.
You can do it with strpos:
function satisfied($str, $k) {
return strpos($str, str_repeat('0', $k+1)) === false
&& strpos($str, str_repeat('1', $k+1)) === false;
}
or you can use preg_match with a simple alternation:
function satisfied($str, $k) {
$k++;
$pattern = '~0{' . $k . '}|1{' . $k . '}~';
return !preg_match($pattern, $str);
}
Note that preg_match returns an integer (or false if a problem occurs), but since there is a negation operator, the returned value is casted to a boolean.
You can take the input as character array and Here's exactly what your looking for :
<?php
function printCharMostRepeated($str)
{
if (!empty($str))
{
$max = 0;
foreach (count_chars($str, 1) as $key => $val)
if ($max < $val) {
$max = $val;
$i = 0;
unset($letter);
$letter[$i++] = chr($key);
} else if ($max == $val)
$letter[$i++] = chr($key);
if (count($letter) === 1)
echo 'The character the most repeated is "'.$letter[0].'"';
else if (count($letter) > 1) {
echo 'The characters the most repeated are : ';
$count = count($letter);
foreach ($letter as $key => $value) {
echo '"'.$value.'"';
echo ($key === $count - 1) ? '.': ', ';
}
}
} else
echo 'value passed to '.__FUNCTION__.' can\'t be empty';
}
$str = 'ddaabbccccsdfefffffqqqqqqdddaaa';
printCharMostRepeated($str);
Related
I need to find the min and max position into an array where some value exist!
use a loop inside a loop to compare values is not an option ( my array has 100.000 values )
e.g=
$myarray[0]="red";
$myarray[1]="red";
$myarray[2]="blue";
$myarray[3]="blue";
$myarray[4]="blue";
$myarray[5]="red";
how to get the min and max position where blue exist?
Use the second argument for array_keys:
if($blue = array_keys($myarray, 'blue')) {
$min = min($blue);
$max = max($blue);
}
may be this is the answer?
function getMinKey($arr, $search){
if(!in_array($search, $arr)){
return false;
}
foreach($arr as $key => $value){
if($value == $search){
return $key;
}
}
}
function getMaxKey($arr, $search){
if(!in_array($search, $arr)){
return false;
}
$arrCount = count($arr)-1;
for($i = $arrCount; $i >=0; $i--){
if($arr[$i] == $search){
return $i;
}
}
}
All solutions, so far, have searched the whole array, which might be quite inefficient. You only need to search from the start upto the first "blue" and from the end downto the last "blue". Like this:
$find = "blue";
$first = false;
$last = false;
$max = count($myarray);
$key = 0;
while ($key < $max) {
if ($myarray[$key] == $find) {
$first = $key;
break;
}
$key++;
}
if ($first !== false) {
$key = --$max;
while ($key > 0) {
if ($myarray[$key] == $find) {
$last = $key;
break;
}
$key--;
}
}
Note that this code takes into account that nothing will be found. In that case $first and $last will contain false. It also checks to see if the $first was found to prevent searching through the array twice when there's clearly no need for that.
You can use array_keys with the search_value to extract all the matching keys, and then max and min to get the two ones that you want.
$keys = array_keys($myarray,'blue'); //[2,3,4]
$maxKey = max($keys); //4
$minKey = min($keys); //2
I have to advise that performance wise is better to do a for loop:
$length = count($myarray);
$minKey = FALSE;
$maxKey = FALSE;
$search = 'blue';
for($i=0;$i<$length;$i++){
if($myarray[$i] == $search){
if($minKey === FALSE) $minKey = $i;
$maxKey = $i;
}
}
Three steps to find the palindrome?
use strrev on the given value
Then split using the str_split.
Then use foreach and concate the split value.
Example
$a = "madam";
$b = strrev($a);
$string_reverse = str_split($b);
$palin = '';
foreach($string_reverse as $value){
$palin.= $value;
}
print $palin;
if($a == $palin){
print "<br>Palindrome";
} else {
print "<br>Not Palindrome";
}
Output
madam
Palindrome
try this:
<?php
function check_plaindrome($string) {
//remove all spaces
$string = str_replace(' ', '', $string);
//remove special characters
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
//change case to lower
$string = strtolower($string);
//reverse the string
$reverse = strrev($string);
if ($string == $reverse) {
echo "<p>It is Palindrome</p>";
}
else {
echo "</p>Not Palindrome</p>";
}
}
$string = "A man, a plan, a canal, Panama";
check_plaindrome($string);
########Output#######
<p>It is Palindrome</p>
To check a string whether it is palindrome or not without PHP function.
<?php
$str = 'level';
$strLen = strlen($str)-1;
$revStr = '';
for($i=$strLen; $i>=0; $i--){
$revStr.=$str[$i];
}
if($revStr == $str)
echo 'Palindrome';
else
echo "Not Palindrome";
?>
function checkpala(string $input){
for( $i=0; $i < strlen($input); $i++){ //for each char in the string
if (substr($input,$i,1) != substr($input, strlen($input)-($i+1),1)){ //get the first char and the last char and compare them. Then get the 2nd and the 2nd from the end and compare them. repeate
//if at any point there is no match, stop checking, return false
//echo "$input is not a palindrome";
return false;
}
}
//if the loop completes and every character checked out, return true.
//echo "$input is a palindrome";
return true;
}
There is a simple way who we can write like this to don't make it complicate:
$a = "1681";
$b = strrev($a);
print $b;
if($a == $b){
print "<br>Plaindrome";
} else {
print "<br>Not Plaindrome";
}
You can try this, it reverses the string or value...
function fn_palindrome($palindrome) {
$reversed = '';
$original = $palindrome;
$string = array(); $j = 0;
$converted = (string) $palindrome;
$palindrome = str_split($converted);
$i = count($palindrome) - 1;
while($i >= 0) {
$string[$j] = $palindrome[$i];
$j++; $i--;
}
$reversed = implode('', $string);
if($reversed == $original) {
return TRUE;
} else {
return FALSE;
}
}
function checkPalindrome($string) {
return $string == strrev($string);
}
<?php
$word = "level"; // declare a varibale
echo "String: " . $word . "<br>";
$reverse = strrev($word); // reverse the word
if ($word == $reverse) // compare if the original word is same as the reverse of the same word
echo 'Output: This string is a palindrome';
else
echo 'Output: This is not a palindrome';
?>
Dummy String to be tested
$s = 'abcdefg';
Reverse the string order
$t = strrev($s);
Get the length of the string
$length = mb_strlen($s);
Variable to be used for concating string while traversing using for loop
$new = '';
Loop to traverse string
for ($i = 0; $i < $length; $i++) {
$new = $s[$i].$new;
}
Check string traversed using for loop is equal to string reversed using PHP function
if ($s == $new){
echo "Yes palindrome";
} else {
echo "No palindrome";
}
If output is yes then it is palindrome otherwise it is Not a palindrome string.
*** I have update the answer.
You can try the following code:
function checkPalindrome($string){
$string = strtolower($string);
$reverse = strrev($string);
if($string == $reverse){
return true;
} else {
return false;
}
}
Try this one..
<?php
$strng = 'SMS';
$rvsstr = '';
$i = 0;
while (!empty($strng[$i])) {
$rvsstr = $strng[$i].$rvsstr;
$i++;
}
// echo $rvsstr;
if ($strng === $rvsstr) {
echo "Number is Palindrome";
} else {
echo "Number is not palindrome";
}
?>
Could it be as simple as this?
function isPalindrome(string $word) : bool
{
$word = strtolower($word);
if(strrev($word) === $word){
return true;
} else {
return false;
}
}
echo isPalindrome('Deleveled');
People are already correct here, anyway simply you can try this.
function checkPalindrome($string) {
$string = strtolower($string);
return $string == strrev($string);
}
function isPalindrome($string): bool {
return strtolower($string) === strtolower(strrev($string));
}
Didn't find solution for my 'kąyąk' problem when You have different characters encoding.
Below is originally from php.net comment changed sligtly by me to see on xdebug in phpStorm whats going on.
public function isPalindrome(): bool {
$r = '';
for ($i = mb_strlen($this->string); $i >= 0; $i--) {
$r .= mb_substr($this->string, $i, 1);
}
for ($i = 0 ; $i <= strlen($r); $i++) {
$o = mb_substr($this->string, $i, 1); // original current char
$s = mb_substr($r, $i, 1); // inverted current char
if ($o != $s) {
return false; // if does not match return false
}
}
return true;
}
$a = readline("Enter word: ");
$i=0;
for ($i=0; $i < strlen($a) && substr($a,$i,1) == substr($a,strlen($a)-($i+1),1); $i++);
echo ($i == strlen($a))?"Pallindrome":"Not Pallindrome";
$i < strlen($a) && substr($a,$i,1) == substr($a,strlen($a)-($i+1),1)
This test is the key where the loop tries to keep checking if the characters starting from the left of the string matches with the characters from the right, and it should continue till all characters are checked or till it doesn't find a matching character.
So, first of all, what is palindrome?
Palindrome is a word, phrase, or sequence that reads the same backward as forward.
So, to know wether the string is a palindrome or not, we only need to reverse the original string and then compare it.
Let's say we want to check wether the string Level is a palindrome or not:
$str = 'Level';
This step is for ignoring the case-sensitivity so Level and level will be considered the same.
$str = strtolower($str);
Then we can use the strrev() to reverse the string, then compare it to the original as follow:
echo (strrev($str) === $str) ? 'Palindrome' : 'Not palindrome';
You can also write it with if-else block if you consider it easier to read:
if (strrev($str) === $str) {
echo "Palindrome";
} else {
echo "Not palindrome";
}
Final code:
$str = 'Level';
$str = strtolower($str);
echo (strrev($str) === $str) ? 'Palindrome' : 'Not palindrome';
I have found many examples of how to find repeat characters in a string. I believe my requirement is unique.
I have string
$string=aabbbccddd;
I need to determine which character was repeated the most.
So for the above example it would say
The character repeated the most is "B".
However in the example above both B and D are repeated 3 times.
Would need to spot that. B AND D are both repeated 3 times.
This is what I have so far. FAR from what I need but starting point
<?php
$string = "aabbbccddd";
$array=array($array);
foreach (count_chars($string, 1) as $i => $val) {
$count=chr($i);
$array[]= $val.",".$count;
}
print_r($array);
?>
Anyone have any thing that could help me?
Based on georg's great point, I would use a regex. This will handle split duplicates like ddaaddd with array keys dd=>2 and ddd=>3 but will only show one entry for dd when given ddaadd. To represent both would require a more complex array:
$string = "ddaabbbccddda";
preg_match_all('/(.)\1+/', $string, $matches);
$result = array_combine($matches[0], array_map('strlen', $matches[0]));
arsort($result);
If you only need a count of ALL occurrences try:
$result = array_count_values(str_split($string));
arsort($result);
Legacy Answers:
If you don't have split duplicates:
$string = 'aabbbccddd';
$letters = str_split($string);
$result = array_fill_keys($letters, 1);
$previous = '';
foreach($letters as $letter) {
if($letter == $previous) {
$result[$letter]++;
}
$previous = $letter;
}
arsort($result);
print_r($result);
Or for a regex approach:
preg_match_all('/(.)\1+/', $string, $matches);
$result = array_combine($matches[1], array_map('strlen', $matches[0]));
arsort($result);
Here's exactly what your looking for :
<?php
function printCharMostRepeated($str)
{
if (!empty($str))
{
$max = 0;
foreach (count_chars($str, 1) as $key => $val)
if ($max < $val) {
$max = $val;
$i = 0;
unset($letter);
$letter[$i++] = chr($key);
} else if ($max == $val)
$letter[$i++] = chr($key);
if (count($letter) === 1)
echo 'The character the most repeated is "'.$letter[0].'"';
else if (count($letter) > 1) {
echo 'The characters the most repeated are : ';
$count = count($letter);
foreach ($letter as $key => $value) {
echo '"'.$value.'"';
echo ($key === $count - 1) ? '.': ', ';
}
}
} else
echo 'value passed to '.__FUNCTION__.' can\'t be empty';
}
$str = 'ddaabbccccsdfefffffqqqqqqdddaaa';
printCharMostRepeated($str);
use count-chars()
http://php.net/manual/en/function.count-chars.php
and then asort()
http://php.net/manual/en/function.asort.php
<?php
$word = "abcdefghbi";
for($i=0; $i<strlen($word);$i++){
for($k=0;$k<strlen($word);$k++){
if($word[$i] == $word[$k] && $i != $k){
echo $word[$k]." is duplicate";
exit;
}
}
}
echo "no match found";
?>
$data = "aabbbcccdddz";
$array = str_split($data);
$v = array_count_values($array);
foreach($v as $k => $val){
echo $k.' = '.$val.'<br>';
}
I have an array:
$haystack = array(1,2,3,4,5,6,7,8,9,10...);
$needle = array(3,4,5);
$bad_needle = array(3,5,4);
And I need to got true if I check if haystack contains a needle. But I also need false if I check if haystack contains bad_needle.
Tip without foreach for all haystacks and needles?
$offset = array_search($needle[0], $haystack);
$slice = array_slice($haystack, $offset, count($needle));
if ($slice === $needle) {
// yes, contains needle
}
This fails if the values in $haystack are not unique though. In this case, I'd go with a nice loop:
$found = false;
$j = 0;
$length = count($needle);
foreach ($haystack as $i) {
if ($i == $needle[$j]) {
$j++;
} else {
$j = 0;
}
if ($j >= $length) {
$found = true;
break;
}
}
if ($found) {
// yes, contains needle
}
var_dump(strpos(implode(',', $haystack), implode(',', $needle)) !== false);
var_dump(strpos(implode(',', $haystack), implode(',', $bad_needle)) !== false);
A working array_slice() would still need a loop as far as I can work out:
foreach(array_keys($haystack, reset($needle)) as $offset) {
if($needle == array_slice($haystack, $offset, count($needle))) {
// yes, contains needle
break;
}
}
How to get the count of string 2 occurrence in string 1 without php built-in functions.
Example:
$strone = "Arun sukumar";
$strtwo = "a";
//Expected Output: 2
$strone = "Arun sukumar";
$strtwo = "uk";
//Expected Output: 1
I need to get the count without using any php built-in functions.
This is the question asked in a interview, is there any logic in that?
You need to take your needle, get the first char.. then iterate over each char of the haystack until you get match. Then take the next char of needle and check the next char of the haystack for a match... continue until you have the complete match for needle or until you fial to match a char.
hint: you can access the individual chars of a string by index with $string{0} where 0 is the zero based index of the char in the string.
$strone = 'arun sukumar';
$strtwo = 'a';
echo parsestr($strone, $strtwo);
function parsestr($strone, $strtwo)
{
$len = 0;
while ($strtwo{$len} != '') {
$len++;
}
$nr = 0;
while ($strone{$nr} != '')
{
if($strone{$nr} != ' ')
{
$data[$nr] = $strone{$nr};
}
$nr++;
}
$newdata = $data;
if($len > 1)
{
$newdata = array();
$j = 0;
foreach($data as $val)
{
$str .= $val;
if($j == ($len -1))
{
$newdata[] = $str;
$str = '';
$j = 0;
}
else
$j++;
}
}
$i = 0;
foreach($newdata as $val)
{
if($val == $strtwo)
{
$i++;
}
}
return $i;
}
Try this
$string = 'Arun sukumar';
$sub_string = 'a';
$count = 0;
for($i=0;$i < strlen($string); $i++){
$flag = 0;
$j=0;
if(strtolower($string[$i]) == $sub_string[$j])
{
//echo "match";
$flag = 1;
$k = $i;
for(;$j< strlen($sub_string); $j++){//echo "[".$j . $k."] $count $flag";
if(strtolower($string[$k]) != $sub_string[$j]){
$flag = 0;
break;
}
$k++;
}//echo "<br> $flag";
}
if($flag == 1){
$count++;
$flag = 0;
}
}
echo $count;
?>
Not sure why you would not want to use the built-in PHP functions since they would be faster, but something like this would work:
<?php
$haystack = 'Arun sukumar';
$needle = 'a';
// you seem to want a case insensitive search, so do a strtolower first
$haystack = strtolower($haystack);
$hitCount = 0;
for ($i = 0; $i < strlen($haystack); ++$i) {
if ($needle === substr($haystack, $i, strlen($needle))) {
$hitCount++;
}
}
echo 'Output: ' . $hitCount;
?>